diff --git a/pom.xml b/pom.xml index 7450d57f5be..59652833665 100644 --- a/pom.xml +++ b/pom.xml @@ -24,7 +24,7 @@ - 0.0.9 + 0.0.11 0.0.1.RELEASE diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java index b18fba1ff87..0ad2e1d9ef2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,15 +40,13 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { private final Class annotationType; - protected OnEndpointElementCondition(String prefix, - Class annotationType) { + protected OnEndpointElementCondition(String prefix, Class annotationType) { this.prefix = prefix; this.annotationType = annotationType; } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); String endpointName = annotationAttributes.getString("value"); @@ -59,25 +57,21 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { return getDefaultEndpointsOutcome(context); } - protected ConditionOutcome getEndpointOutcome(ConditionContext context, - String endpointName) { + protected ConditionOutcome getEndpointOutcome(ConditionContext context, String endpointName) { Environment environment = context.getEnvironment(); String enabledProperty = this.prefix + endpointName + ".enabled"; if (environment.containsProperty(enabledProperty)) { boolean match = environment.getProperty(enabledProperty, Boolean.class, true); - return new ConditionOutcome(match, - ConditionMessage.forCondition(this.annotationType).because( - this.prefix + endpointName + ".enabled is " + match)); + return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) + .because(this.prefix + endpointName + ".enabled is " + match)); } return null; } protected ConditionOutcome getDefaultEndpointsOutcome(ConditionContext context) { - boolean match = Boolean.valueOf(context.getEnvironment() - .getProperty(this.prefix + "defaults.enabled", "true")); - return new ConditionOutcome(match, - ConditionMessage.forCondition(this.annotationType).because( - this.prefix + "defaults.enabled is considered " + match)); + boolean match = Boolean.valueOf(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); + return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) + .because(this.prefix + "defaults.enabled is considered " + match)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfiguration.java index c73559729b8..1c09abf877b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfiguration.java @@ -46,13 +46,12 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnEnabledHealthIndicator("rabbit") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(RabbitAutoConfiguration.class) -public class RabbitHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class RabbitHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "rabbitHealthIndicator") - public HealthIndicator rabbitHealthIndicator( - Map rabbitTemplates) { + public HealthIndicator rabbitHealthIndicator(Map rabbitTemplates) { return createHealthIndicator(rabbitTemplates); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.java index 6d0c31490d0..7af9e5f4e37 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.java @@ -41,8 +41,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration(proxyBeanMethods = false) @ConditionalOnBean(AuditEventRepository.class) -@ConditionalOnProperty(prefix = "management.auditevents", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.auditevents", name = "enabled", matchIfMissing = true) public class AuditAutoConfiguration { @Bean @@ -52,16 +51,14 @@ public class AuditAutoConfiguration { } @Bean - @ConditionalOnClass( - name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent") + @ConditionalOnClass(name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent") @ConditionalOnMissingBean(AbstractAuthenticationAuditListener.class) public AuthenticationAuditListener authenticationAuditListener() throws Exception { return new AuthenticationAuditListener(); } @Bean - @ConditionalOnClass( - name = "org.springframework.security.access.event.AbstractAuthorizationEvent") + @ConditionalOnClass(name = "org.springframework.security.access.event.AbstractAuthorizationEvent") @ConditionalOnMissingBean(AbstractAuthorizationAuditListener.class) public AuthorizationAuditListener authorizationAuditListener() throws Exception { return new AuthorizationAuditListener(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfiguration.java index b0b72b66120..c67d7950b4a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfiguration.java @@ -42,8 +42,7 @@ public class AuditEventsEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(AuditEventRepository.class) - public AuditEventsEndpoint auditEventsEndpoint( - AuditEventRepository auditEventRepository) { + public AuditEventsEndpoint auditEventsEndpoint(AuditEventRepository auditEventRepository) { return new AuditEventsEndpoint(auditEventRepository); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfiguration.java index a398570b82a..48287e8f987 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfiguration.java @@ -36,8 +36,7 @@ public class BeansEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public BeansEndpoint beansEndpoint( - ConfigurableApplicationContext applicationContext) { + public BeansEndpoint beansEndpoint(ConfigurableApplicationContext applicationContext) { return new BeansEndpoint(applicationContext); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfiguration.java index f8118eaee7b..f17d0bbb1d0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfiguration.java @@ -53,8 +53,7 @@ public class CachesEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(CachesEndpoint.class) - public CachesEndpointWebExtension cachesEndpointWebExtension( - CachesEndpoint cachesEndpoint) { + public CachesEndpointWebExtension cachesEndpointWebExtension(CachesEndpoint cachesEndpoint) { return new CachesEndpointWebExtension(cachesEndpoint); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.java index 512e611c4f6..70fc6daa3b5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.java @@ -50,16 +50,14 @@ import org.springframework.data.cassandra.core.CassandraOperations; @ConditionalOnBean(CassandraOperations.class) @ConditionalOnEnabledHealthIndicator("cassandra") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) -@AutoConfigureAfter({ CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class, +@AutoConfigureAfter({ CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, CassandraReactiveHealthIndicatorAutoConfiguration.class }) -public class CassandraHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class CassandraHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "cassandraHealthIndicator") - public HealthIndicator cassandraHealthIndicator( - Map cassandraOperations) { + public HealthIndicator cassandraHealthIndicator(Map cassandraOperations) { return createHealthIndicator(cassandraOperations); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationException.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationException.java index a032295cafe..93f33f1b06a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationException.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ public class CloudFoundryAuthorizationException extends RuntimeException { this(reason, message, null); } - public CloudFoundryAuthorizationException(Reason reason, String message, - Throwable cause) { + public CloudFoundryAuthorizationException(Reason reason, String message, Throwable cause) { super(message, cause); this.reason = reason; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java index a41ce4ffd93..7f510589564 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java @@ -50,18 +50,16 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { * @param filters filters to apply */ public CloudFoundryWebEndpointDiscoverer(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, - EndpointMediaTypes endpointMediaTypes, List endpointPathMappers, - Collection invokerAdvisors, + ParameterValueMapper parameterValueMapper, EndpointMediaTypes endpointMediaTypes, + List endpointPathMappers, Collection invokerAdvisors, Collection> filters) { - super(applicationContext, parameterValueMapper, endpointMediaTypes, - endpointPathMappers, invokerAdvisors, filters); + super(applicationContext, parameterValueMapper, endpointMediaTypes, endpointPathMappers, invokerAdvisors, + filters); } @Override protected boolean isExtensionExposed(Object extensionBean) { - if (isHealthEndpointExtension(extensionBean) - && !isCloudFoundryHealthEndpointExtension(extensionBean)) { + if (isHealthEndpointExtension(extensionBean) && !isCloudFoundryHealthEndpointExtension(extensionBean)) { // Filter regular health endpoint extensions so a CF version can replace them return false; } @@ -69,14 +67,12 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { } private boolean isHealthEndpointExtension(Object extensionBean) { - return MergedAnnotations.from(extensionBean.getClass()) - .get(EndpointWebExtension.class).getValue("endpoint", Class.class) - .map(HealthEndpoint.class::isAssignableFrom).orElse(false); + return MergedAnnotations.from(extensionBean.getClass()).get(EndpointWebExtension.class) + .getValue("endpoint", Class.class).map(HealthEndpoint.class::isAssignableFrom).orElse(false); } private boolean isCloudFoundryHealthEndpointExtension(Object extensionBean) { - return MergedAnnotations.from(extensionBean.getClass()) - .isPresent(EndpointCloudFoundryExtension.class); + return MergedAnnotations.from(extensionBean.getClass()).isPresent(EndpointCloudFoundryExtension.class); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/Token.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/Token.java index 202333d0b45..5e32f256adc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/Token.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/Token.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,12 +61,10 @@ public class Token { private Map parseJson(String base64) { try { byte[] bytes = Base64Utils.decodeFromUrlSafeString(base64); - return JsonParserFactory.getJsonParser() - .parseMap(new String(bytes, StandardCharsets.UTF_8)); + return JsonParserFactory.getJsonParser().parseMap(new String(bytes, StandardCharsets.UTF_8)); } catch (RuntimeException ex) { - throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, - "Token could not be parsed", ex); + throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Token could not be parsed", ex); } } @@ -103,8 +101,7 @@ public class Token { private T getRequired(Map map, String key, Class type) { Object value = map.get(key); if (value == null) { - throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, - "Unable to get value from key " + key); + throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Unable to get value from key " + key); } if (!type.isInstance(value)) { throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtension.java index ab68f44a99a..11c9a09e6f5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtension.java @@ -39,8 +39,7 @@ public class CloudFoundryReactiveHealthEndpointWebExtension { private final ReactiveHealthEndpointWebExtension delegate; - public CloudFoundryReactiveHealthEndpointWebExtension( - ReactiveHealthEndpointWebExtension delegate) { + public CloudFoundryReactiveHealthEndpointWebExtension(ReactiveHealthEndpointWebExtension delegate) { this.delegate = delegate; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java index 9ca595754ef..096313574ec 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.web.server.ServerWebExchange; */ class CloudFoundrySecurityInterceptor { - private static final Log logger = LogFactory - .getLog(CloudFoundrySecurityInterceptor.class); + private static final Log logger = LogFactory.getLog(CloudFoundrySecurityInterceptor.class); private final ReactiveTokenValidator tokenValidator; @@ -48,12 +47,10 @@ class CloudFoundrySecurityInterceptor { private final String applicationId; - private static final Mono SUCCESS = Mono - .just(SecurityResponse.success()); + private static final Mono SUCCESS = Mono.just(SecurityResponse.success()); CloudFoundrySecurityInterceptor(ReactiveTokenValidator tokenValidator, - ReactiveCloudFoundrySecurityService cloudFoundrySecurityService, - String applicationId) { + ReactiveCloudFoundrySecurityService cloudFoundrySecurityService, String applicationId) { this.tokenValidator = tokenValidator; this.cloudFoundrySecurityService = cloudFoundrySecurityService; this.applicationId = applicationId; @@ -65,15 +62,14 @@ class CloudFoundrySecurityInterceptor { return SUCCESS; } if (!StringUtils.hasText(this.applicationId)) { - return Mono.error(new CloudFoundryAuthorizationException( - Reason.SERVICE_UNAVAILABLE, "Application id is not available")); + return Mono.error(new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, + "Application id is not available")); } if (this.cloudFoundrySecurityService == null) { - return Mono.error(new CloudFoundryAuthorizationException( - Reason.SERVICE_UNAVAILABLE, "Cloud controller URL is not available")); + return Mono.error(new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, + "Cloud controller URL is not available")); } - return check(exchange, id).then(SUCCESS).doOnError(this::logError) - .onErrorResume(this::getErrorResponse); + return check(exchange, id).then(SUCCESS).doOnError(this::logError).onErrorResume(this::getErrorResponse); } private void logError(Throwable ex) { @@ -84,13 +80,11 @@ class CloudFoundrySecurityInterceptor { try { Token token = getToken(exchange.getRequest()); return this.tokenValidator.validate(token) - .then(this.cloudFoundrySecurityService - .getAccessLevel(token.toString(), this.applicationId)) + .then(this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId)) .filter((accessLevel) -> accessLevel.isAccessAllowed(id)) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException( - Reason.ACCESS_DENIED, "Access denied"))) - .doOnSuccess((accessLevel) -> exchange.getAttributes() - .put("cloudFoundryAccessLevel", accessLevel)) + .switchIfEmpty( + Mono.error(new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"))) + .doOnSuccess((accessLevel) -> exchange.getAttributes().put("cloudFoundryAccessLevel", accessLevel)) .then(); } catch (CloudFoundryAuthorizationException ex) { @@ -104,15 +98,13 @@ class CloudFoundrySecurityInterceptor { return Mono.just(new SecurityResponse(cfException.getStatusCode(), "{\"security_error\":\"" + cfException.getMessage() + "\"}")); } - return Mono.just(new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, - throwable.getMessage())); + return Mono.just(new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, throwable.getMessage())); } private Token getToken(ServerHttpRequest request) { String authorization = request.getHeaders().getFirst("Authorization"); String bearerPrefix = "bearer "; - if (authorization == null - || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) { + if (authorization == null || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) { throw new CloudFoundryAuthorizationException(Reason.MISSING_AUTHORIZATION, "Authorization header is missing or invalid"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java index 7a790421106..5a3307157ab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,17 +50,15 @@ import org.springframework.web.server.ServerWebExchange; * @author Phillip Webb * @author Brian Clozel */ -class CloudFoundryWebFluxEndpointHandlerMapping - extends AbstractWebFluxEndpointHandlerMapping { +class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping { private final CloudFoundrySecurityInterceptor securityInterceptor; private final EndpointLinksResolver linksResolver; CloudFoundryWebFluxEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration, - CloudFoundrySecurityInterceptor securityInterceptor, + Collection endpoints, EndpointMediaTypes endpointMediaTypes, + CorsConfiguration corsConfiguration, CloudFoundrySecurityInterceptor securityInterceptor, EndpointLinksResolver linksResolver) { super(endpointMapping, endpoints, endpointMediaTypes, corsConfiguration); this.linksResolver = linksResolver; @@ -68,10 +66,9 @@ class CloudFoundryWebFluxEndpointHandlerMapping } @Override - protected ReactiveWebOperation wrapReactiveWebOperation(ExposableWebEndpoint endpoint, - WebOperation operation, ReactiveWebOperation reactiveWebOperation) { - return new SecureReactiveWebOperation(reactiveWebOperation, - this.securityInterceptor, endpoint.getEndpointId()); + protected ReactiveWebOperation wrapReactiveWebOperation(ExposableWebEndpoint endpoint, WebOperation operation, + ReactiveWebOperation reactiveWebOperation) { + return new SecureReactiveWebOperation(reactiveWebOperation, this.securityInterceptor, endpoint.getEndpointId()); } @Override @@ -84,30 +81,26 @@ class CloudFoundryWebFluxEndpointHandlerMapping @Override public Publisher> links(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); - return CloudFoundryWebFluxEndpointHandlerMapping.this.securityInterceptor - .preHandle(exchange, "").map((securityResponse) -> { + return CloudFoundryWebFluxEndpointHandlerMapping.this.securityInterceptor.preHandle(exchange, "") + .map((securityResponse) -> { if (!securityResponse.getStatus().equals(HttpStatus.OK)) { return new ResponseEntity<>(securityResponse.getStatus()); } - AccessLevel accessLevel = exchange - .getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); Map links = CloudFoundryWebFluxEndpointHandlerMapping.this.linksResolver .resolveLinks(request.getURI().toString()); return new ResponseEntity<>( - Collections.singletonMap("_links", - getAccessibleLinks(accessLevel, links)), + Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)), HttpStatus.OK); }); } - private Map getAccessibleLinks(AccessLevel accessLevel, - Map links) { + private Map getAccessibleLinks(AccessLevel accessLevel, Map links) { if (accessLevel == null) { return new LinkedHashMap<>(); } return links.entrySet().stream() - .filter((entry) -> entry.getKey().equals("self") - || accessLevel.isAccessAllowed(entry.getKey())) + .filter((entry) -> entry.getKey().equals("self") || accessLevel.isAccessAllowed(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @@ -129,8 +122,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping private final EndpointId endpointId; - SecureReactiveWebOperation(ReactiveWebOperation delegate, - CloudFoundrySecurityInterceptor securityInterceptor, + SecureReactiveWebOperation(ReactiveWebOperation delegate, CloudFoundrySecurityInterceptor securityInterceptor, EndpointId endpointId) { this.delegate = delegate; this.securityInterceptor = securityInterceptor; @@ -138,16 +130,13 @@ class CloudFoundryWebFluxEndpointHandlerMapping } @Override - public Mono> handle(ServerWebExchange exchange, - Map body) { - return this.securityInterceptor - .preHandle(exchange, this.endpointId.toLowerCaseString()) - .flatMap((securityResponse) -> flatMapResponse(exchange, body, - securityResponse)); + public Mono> handle(ServerWebExchange exchange, Map body) { + return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString()) + .flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse)); } - private Mono> flatMapResponse(ServerWebExchange exchange, - Map body, SecurityResponse securityResponse) { + private Mono> flatMapResponse(ServerWebExchange exchange, Map body, + SecurityResponse securityResponse) { if (!securityResponse.getStatus().equals(HttpStatus.OK)) { return Mono.just(new ResponseEntity<>(securityResponse.getStatus())); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java index 2d931b117d2..5fbce52668c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java @@ -75,10 +75,8 @@ import org.springframework.web.server.WebFilter; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", - matchIfMissing = true) -@AutoConfigureAfter({ HealthEndpointAutoConfiguration.class, - InfoEndpointAutoConfiguration.class }) +@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true) +@AutoConfigureAfter({ HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) public class ReactiveCloudFoundryActuatorAutoConfiguration { @@ -89,21 +87,18 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { @ConditionalOnBean({ HealthEndpoint.class, ReactiveHealthEndpointWebExtension.class }) public CloudFoundryReactiveHealthEndpointWebExtension cloudFoundryReactiveHealthEndpointWebExtension( ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension) { - return new CloudFoundryReactiveHealthEndpointWebExtension( - reactiveHealthEndpointWebExtension); + return new CloudFoundryReactiveHealthEndpointWebExtension(reactiveHealthEndpointWebExtension); } @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @ConditionalOnBean({ InfoEndpoint.class, GitProperties.class }) - public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension( - GitProperties properties, ObjectProvider infoContributors) { + public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension(GitProperties properties, + ObjectProvider infoContributors) { List contributors = infoContributors.orderedStream() .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) - ? new GitInfoContributor(properties, - InfoPropertiesInfoContributor.Mode.FULL) - : infoContributor) + ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) .collect(Collectors.toList()); return new CloudFoundryInfoEndpointWebExtension(new InfoEndpoint(contributors)); } @@ -111,51 +106,45 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { @Bean public CloudFoundryWebFluxEndpointHandlerMapping cloudFoundryWebFluxEndpointHandlerMapping( ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes, - WebClient.Builder webClientBuilder, - ControllerEndpointsSupplier controllerEndpointsSupplier, + WebClient.Builder webClientBuilder, ControllerEndpointsSupplier controllerEndpointsSupplier, ApplicationContext applicationContext) { - CloudFoundryWebEndpointDiscoverer endpointDiscoverer = new CloudFoundryWebEndpointDiscoverer( - applicationContext, parameterMapper, endpointMediaTypes, null, - Collections.emptyList(), Collections.emptyList()); - CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor( - webClientBuilder, applicationContext.getEnvironment()); + CloudFoundryWebEndpointDiscoverer endpointDiscoverer = new CloudFoundryWebEndpointDiscoverer(applicationContext, + parameterMapper, endpointMediaTypes, null, Collections.emptyList(), Collections.emptyList()); + CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor(webClientBuilder, + applicationContext.getEnvironment()); Collection webEndpoints = endpointDiscoverer.getEndpoints(); List> allEndpoints = new ArrayList<>(); allEndpoints.addAll(webEndpoints); allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints()); - return new CloudFoundryWebFluxEndpointHandlerMapping( - new EndpointMapping("/cloudfoundryapplication"), webEndpoints, - endpointMediaTypes, getCorsConfiguration(), securityInterceptor, + return new CloudFoundryWebFluxEndpointHandlerMapping(new EndpointMapping("/cloudfoundryapplication"), + webEndpoints, endpointMediaTypes, getCorsConfiguration(), securityInterceptor, new EndpointLinksResolver(allEndpoints)); } - private CloudFoundrySecurityInterceptor getSecurityInterceptor( - WebClient.Builder webClientBuilder, Environment environment) { + private CloudFoundrySecurityInterceptor getSecurityInterceptor(WebClient.Builder webClientBuilder, + Environment environment) { ReactiveCloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService( webClientBuilder, environment); - ReactiveTokenValidator tokenValidator = new ReactiveTokenValidator( - cloudfoundrySecurityService); - return new CloudFoundrySecurityInterceptor(tokenValidator, - cloudfoundrySecurityService, + ReactiveTokenValidator tokenValidator = new ReactiveTokenValidator(cloudfoundrySecurityService); + return new CloudFoundrySecurityInterceptor(tokenValidator, cloudfoundrySecurityService, environment.getProperty("vcap.application.application_id")); } - private ReactiveCloudFoundrySecurityService getCloudFoundrySecurityService( - WebClient.Builder webClientBuilder, Environment environment) { + private ReactiveCloudFoundrySecurityService getCloudFoundrySecurityService(WebClient.Builder webClientBuilder, + Environment environment) { String cloudControllerUrl = environment.getProperty("vcap.application.cf_api"); - boolean skipSslValidation = environment.getProperty( - "management.cloudfoundry.skip-ssl-validation", Boolean.class, false); - return (cloudControllerUrl != null) ? new ReactiveCloudFoundrySecurityService( - webClientBuilder, cloudControllerUrl, skipSslValidation) : null; + boolean skipSslValidation = environment.getProperty("management.cloudfoundry.skip-ssl-validation", + Boolean.class, false); + return (cloudControllerUrl != null) + ? new ReactiveCloudFoundrySecurityService(webClientBuilder, cloudControllerUrl, skipSslValidation) + : null; } private CorsConfiguration getCorsConfiguration() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); - corsConfiguration.setAllowedMethods( - Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + corsConfiguration.setAllowedHeaders(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); return corsConfiguration; } @@ -173,8 +162,7 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { private static class WebFilterChainPostProcessor implements BeanPostProcessor { @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebFilterChainProxy) { return postProcess((WebFilterChainProxy) bean); } @@ -188,10 +176,8 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { MatcherSecurityWebFilterChain ignoredRequestFilterChain = new MatcherSecurityWebFilterChain( cloudFoundryRequestMatcher, Collections.singletonList(noOpFilter)); MatcherSecurityWebFilterChain allRequestsFilterChain = new MatcherSecurityWebFilterChain( - ServerWebExchangeMatchers.anyExchange(), - Collections.singletonList(existing)); - return new WebFilterChainProxy(ignoredRequestFilterChain, - allRequestsFilterChain); + ServerWebExchangeMatchers.anyExchange(), Collections.singletonList(existing)); + return new WebFilterChainProxy(ignoredRequestFilterChain, allRequestsFilterChain); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java index cecefdb5331..808cee0c086 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class ReactiveCloudFoundrySecurityService { private Mono uaaUrl; - ReactiveCloudFoundrySecurityService(WebClient.Builder webClientBuilder, - String cloudControllerUrl, boolean skipSslValidation) { + ReactiveCloudFoundrySecurityService(WebClient.Builder webClientBuilder, String cloudControllerUrl, + boolean skipSslValidation) { Assert.notNull(webClientBuilder, "Webclient must not be null"); Assert.notNull(cloudControllerUrl, "CloudControllerUrl must not be null"); if (skipSslValidation) { @@ -66,8 +66,8 @@ class ReactiveCloudFoundrySecurityService { } protected ReactorClientHttpConnector buildTrustAllSslConnector() { - HttpClient client = HttpClient.create().secure( - (sslContextSpec) -> sslContextSpec.sslContext(createSslContext())); + HttpClient client = HttpClient.create() + .secure((sslContextSpec) -> sslContextSpec.sslContext(createSslContext())); return new ReactorClientHttpConnector(client); } @@ -86,26 +86,21 @@ class ReactiveCloudFoundrySecurityService { public Mono getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { String uri = getPermissionsUri(applicationId); - return this.webClient.get().uri(uri).header("Authorization", "bearer " + token) - .retrieve().bodyToMono(Map.class).map(this::getAccessLevel) - .onErrorMap(this::mapError); + return this.webClient.get().uri(uri).header("Authorization", "bearer " + token).retrieve().bodyToMono(Map.class) + .map(this::getAccessLevel).onErrorMap(this::mapError); } private Throwable mapError(Throwable throwable) { if (throwable instanceof WebClientResponseException) { - HttpStatus statusCode = ((WebClientResponseException) throwable) - .getStatusCode(); + HttpStatus statusCode = ((WebClientResponseException) throwable).getStatusCode(); if (statusCode.equals(HttpStatus.FORBIDDEN)) { - return new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, - "Access denied"); + return new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } if (statusCode.is4xxClientError()) { - return new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, - "Invalid token", throwable); + return new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", throwable); } } - return new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "Cloud controller not reachable"); + return new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable"); } private AccessLevel getAccessLevel(Map body) { @@ -129,9 +124,8 @@ class ReactiveCloudFoundrySecurityService { private Mono> fetchTokenKeys(String url) { RequestHeadersSpec uri = this.webClient.get().uri(url + "/token_keys"); - return uri.retrieve().bodyToMono(STRING_OBJECT_MAP).map(this::extractTokenKeys) - .onErrorMap(((ex) -> new CloudFoundryAuthorizationException( - Reason.SERVICE_UNAVAILABLE, ex.getMessage()))); + return uri.retrieve().bodyToMono(STRING_OBJECT_MAP).map(this::extractTokenKeys).onErrorMap( + ((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, ex.getMessage()))); } private Map extractTokenKeys(Map response) { @@ -148,11 +142,9 @@ class ReactiveCloudFoundrySecurityService { * @return the UAA url Mono */ public Mono getUaaUrl() { - this.uaaUrl = this.webClient.get().uri(this.cloudControllerUrl + "/info") - .retrieve().bodyToMono(Map.class) + this.uaaUrl = this.webClient.get().uri(this.cloudControllerUrl + "/info").retrieve().bodyToMono(Map.class) .map((response) -> (String) response.get("token_endpoint")).cache() - .onErrorMap((ex) -> new CloudFoundryAuthorizationException( - Reason.SERVICE_UNAVAILABLE, + .onErrorMap((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Unable to fetch token keys from UAA.")); return this.uaaUrl; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java index 80ffdabff0a..4f3c5b11c37 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,20 +51,18 @@ class ReactiveTokenValidator { } public Mono validate(Token token) { - return validateAlgorithm(token).then(validateKeyIdAndSignature(token)) - .then(validateExpiry(token)).then(validateIssuer(token)) - .then(validateAudience(token)); + return validateAlgorithm(token).then(validateKeyIdAndSignature(token)).then(validateExpiry(token)) + .then(validateIssuer(token)).then(validateAudience(token)); } private Mono validateAlgorithm(Token token) { String algorithm = token.getSignatureAlgorithm(); if (algorithm == null) { - return Mono.error(new CloudFoundryAuthorizationException( - Reason.INVALID_SIGNATURE, "Signing algorithm cannot be null")); + return Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, + "Signing algorithm cannot be null")); } if (!algorithm.equals("RS256")) { - return Mono.error(new CloudFoundryAuthorizationException( - Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, + return Mono.error(new CloudFoundryAuthorizationException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, "Signing algorithm " + algorithm + " not supported")); } return Mono.empty(); @@ -72,8 +70,8 @@ class ReactiveTokenValidator { private Mono validateKeyIdAndSignature(Token token) { return getTokenKey(token).filter((tokenKey) -> hasValidSignature(token, tokenKey)) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException( - Reason.INVALID_SIGNATURE, "RSA Signature did not match content"))) + .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, + "RSA Signature did not match content"))) .then(); } @@ -84,11 +82,9 @@ class ReactiveTokenValidator { return Mono.just(cached); } return this.securityService.fetchTokenKeys().doOnSuccess(this::cacheTokenKeys) - .filter((tokenKeys) -> tokenKeys.containsKey(keyId)) - .map((tokenKeys) -> tokenKeys.get(keyId)) - .switchIfEmpty(Mono.error( - new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, - "Key Id present in token header does not match"))); + .filter((tokenKeys) -> tokenKeys.containsKey(keyId)).map((tokenKeys) -> tokenKeys.get(keyId)) + .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, + "Key Id present in token header does not match"))); } private void cacheTokenKeys(Map tokenKeys) { @@ -108,8 +104,7 @@ class ReactiveTokenValidator { } } - private PublicKey getPublicKey(String key) - throws NoSuchAlgorithmException, InvalidKeySpecException { + private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { key = key.replace("-----BEGIN PUBLIC KEY-----\n", ""); key = key.replace("-----END PUBLIC KEY-----", ""); key = key.trim().replace("\n", ""); @@ -121,25 +116,23 @@ class ReactiveTokenValidator { private Mono validateExpiry(Token token) { long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); if (currentTime > token.getExpiry()) { - return Mono.error(new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, - "Token expired")); + return Mono.error(new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired")); } return Mono.empty(); } private Mono validateIssuer(Token token) { - return this.securityService.getUaaUrl() - .map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) + return this.securityService.getUaaUrl().map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) .filter((issuerUri) -> issuerUri.equals(token.getIssuer())) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException( - Reason.INVALID_ISSUER, "Token issuer does not match"))) + .switchIfEmpty(Mono.error( + new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match"))) .then(); } private Mono validateAudience(Token token) { if (!token.getScope().contains("actuator.read")) { - return Mono.error(new CloudFoundryAuthorizationException( - Reason.INVALID_AUDIENCE, "Token does not have audience actuator")); + return Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_AUDIENCE, + "Token does not have audience actuator")); } return Mono.empty(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java index 9d65fbf131c..aad22111d45 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java @@ -75,10 +75,9 @@ import org.springframework.web.servlet.DispatcherServlet; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", - matchIfMissing = true) -@AutoConfigureAfter({ ServletManagementContextAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class }) +@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true) +@AutoConfigureAfter({ ServletManagementContextAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + InfoEndpointAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @ConditionalOnBean(DispatcherServlet.class) @@ -98,13 +97,11 @@ public class CloudFoundryActuatorAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @ConditionalOnBean({ InfoEndpoint.class, GitProperties.class }) - public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension( - GitProperties properties, ObjectProvider infoContributors) { + public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension(GitProperties properties, + ObjectProvider infoContributors) { List contributors = infoContributors.orderedStream() .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) - ? new GitInfoContributor(properties, - InfoPropertiesInfoContributor.Mode.FULL) - : infoContributor) + ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) .collect(Collectors.toList()); return new CloudFoundryInfoEndpointWebExtension(new InfoEndpoint(contributors)); } @@ -112,52 +109,45 @@ public class CloudFoundryActuatorAutoConfiguration { @Bean public CloudFoundryWebEndpointServletHandlerMapping cloudFoundryWebEndpointServletHandlerMapping( ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes, - RestTemplateBuilder restTemplateBuilder, - ServletEndpointsSupplier servletEndpointsSupplier, - ControllerEndpointsSupplier controllerEndpointsSupplier, - ApplicationContext applicationContext) { - CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer( - applicationContext, parameterMapper, endpointMediaTypes, null, - Collections.emptyList(), Collections.emptyList()); - CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor( - restTemplateBuilder, applicationContext.getEnvironment()); + RestTemplateBuilder restTemplateBuilder, ServletEndpointsSupplier servletEndpointsSupplier, + ControllerEndpointsSupplier controllerEndpointsSupplier, ApplicationContext applicationContext) { + CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer(applicationContext, + parameterMapper, endpointMediaTypes, null, Collections.emptyList(), Collections.emptyList()); + CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor(restTemplateBuilder, + applicationContext.getEnvironment()); Collection webEndpoints = discoverer.getEndpoints(); List> allEndpoints = new ArrayList<>(); allEndpoints.addAll(webEndpoints); allEndpoints.addAll(servletEndpointsSupplier.getEndpoints()); allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints()); - return new CloudFoundryWebEndpointServletHandlerMapping( - new EndpointMapping("/cloudfoundryapplication"), webEndpoints, - endpointMediaTypes, getCorsConfiguration(), securityInterceptor, + return new CloudFoundryWebEndpointServletHandlerMapping(new EndpointMapping("/cloudfoundryapplication"), + webEndpoints, endpointMediaTypes, getCorsConfiguration(), securityInterceptor, new EndpointLinksResolver(allEndpoints)); } - private CloudFoundrySecurityInterceptor getSecurityInterceptor( - RestTemplateBuilder restTemplateBuilder, Environment environment) { - CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService( - restTemplateBuilder, environment); + private CloudFoundrySecurityInterceptor getSecurityInterceptor(RestTemplateBuilder restTemplateBuilder, + Environment environment) { + CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService(restTemplateBuilder, + environment); TokenValidator tokenValidator = new TokenValidator(cloudfoundrySecurityService); - return new CloudFoundrySecurityInterceptor(tokenValidator, - cloudfoundrySecurityService, + return new CloudFoundrySecurityInterceptor(tokenValidator, cloudfoundrySecurityService, environment.getProperty("vcap.application.application_id")); } - private CloudFoundrySecurityService getCloudFoundrySecurityService( - RestTemplateBuilder restTemplateBuilder, Environment environment) { + private CloudFoundrySecurityService getCloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, + Environment environment) { String cloudControllerUrl = environment.getProperty("vcap.application.cf_api"); - boolean skipSslValidation = environment.getProperty( - "management.cloudfoundry.skip-ssl-validation", Boolean.class, false); - return (cloudControllerUrl != null) ? new CloudFoundrySecurityService( - restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null; + boolean skipSslValidation = environment.getProperty("management.cloudfoundry.skip-ssl-validation", + Boolean.class, false); + return (cloudControllerUrl != null) + ? new CloudFoundrySecurityService(restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null; } private CorsConfiguration getCorsConfiguration() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); - corsConfiguration.setAllowedMethods( - Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + corsConfiguration.setAllowedHeaders(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); return corsConfiguration; } @@ -169,13 +159,11 @@ public class CloudFoundryActuatorAutoConfiguration { @ConditionalOnClass(WebSecurity.class) @Order(SecurityProperties.IGNORED_ORDER) @Configuration(proxyBeanMethods = false) - public static class IgnoredPathsWebSecurityConfigurer - implements WebSecurityConfigurer { + public static class IgnoredPathsWebSecurityConfigurer implements WebSecurityConfigurer { @Override public void init(WebSecurity builder) throws Exception { - builder.ignoring().requestMatchers( - new AntPathRequestMatcher("/cloudfoundryapplication/**")); + builder.ignoring().requestMatchers(new AntPathRequestMatcher("/cloudfoundryapplication/**")); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java index 7a273219508..5b612dd6bd0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ import org.springframework.web.cors.CorsUtils; */ class CloudFoundrySecurityInterceptor { - private static final Log logger = LogFactory - .getLog(CloudFoundrySecurityInterceptor.class); + private static final Log logger = LogFactory.getLog(CloudFoundrySecurityInterceptor.class); private final TokenValidator tokenValidator; @@ -53,8 +52,7 @@ class CloudFoundrySecurityInterceptor { private static final SecurityResponse SUCCESS = SecurityResponse.success(); CloudFoundrySecurityInterceptor(TokenValidator tokenValidator, - CloudFoundrySecurityService cloudFoundrySecurityService, - String applicationId) { + CloudFoundrySecurityService cloudFoundrySecurityService, String applicationId) { this.tokenValidator = tokenValidator; this.cloudFoundrySecurityService = cloudFoundrySecurityService; this.applicationId = applicationId; @@ -85,22 +83,17 @@ class CloudFoundrySecurityInterceptor { return new SecurityResponse(cfException.getStatusCode(), "{\"security_error\":\"" + cfException.getMessage() + "\"}"); } - return new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, - ex.getMessage()); + return new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage()); } return SecurityResponse.success(); } - private void check(HttpServletRequest request, EndpointId endpointId) - throws Exception { + private void check(HttpServletRequest request, EndpointId endpointId) throws Exception { Token token = getToken(request); this.tokenValidator.validate(token); - AccessLevel accessLevel = this.cloudFoundrySecurityService - .getAccessLevel(token.toString(), this.applicationId); - if (!accessLevel.isAccessAllowed( - (endpointId != null) ? endpointId.toLowerCaseString() : "")) { - throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, - "Access denied"); + AccessLevel accessLevel = this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId); + if (!accessLevel.isAccessAllowed((endpointId != null) ? endpointId.toLowerCaseString() : "")) { + throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } request.setAttribute(AccessLevel.REQUEST_ATTRIBUTE, accessLevel); } @@ -108,8 +101,7 @@ class CloudFoundrySecurityInterceptor { private Token getToken(HttpServletRequest request) { String authorization = request.getHeader("Authorization"); String bearerPrefix = "bearer "; - if (authorization == null - || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) { + if (authorization == null || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) { throw new CloudFoundryAuthorizationException(Reason.MISSING_AUTHORIZATION, "Authorization header is missing or invalid"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityService.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityService.java index 02cd3f470f4..d06cadbd2b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityService.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,13 +47,12 @@ class CloudFoundrySecurityService { private String uaaUrl; - CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, - String cloudControllerUrl, boolean skipSslValidation) { + CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, String cloudControllerUrl, + boolean skipSslValidation) { Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null"); Assert.notNull(cloudControllerUrl, "CloudControllerUrl must not be null"); if (skipSslValidation) { - restTemplateBuilder = restTemplateBuilder - .requestFactory(SkipSslVerificationHttpRequestFactory.class); + restTemplateBuilder = restTemplateBuilder.requestFactory(SkipSslVerificationHttpRequestFactory.class); } this.restTemplate = restTemplateBuilder.build(); this.cloudControllerUrl = cloudControllerUrl; @@ -66,12 +65,10 @@ class CloudFoundrySecurityService { * @return the access level that should be granted * @throws CloudFoundryAuthorizationException if the token is not authorized */ - public AccessLevel getAccessLevel(String token, String applicationId) - throws CloudFoundryAuthorizationException { + public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { try { URI uri = getPermissionsUri(applicationId); - RequestEntity request = RequestEntity.get(uri) - .header("Authorization", "bearer " + token).build(); + RequestEntity request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build(); Map body = this.restTemplate.exchange(request, Map.class).getBody(); if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) { return AccessLevel.FULL; @@ -80,22 +77,18 @@ class CloudFoundrySecurityService { } catch (HttpClientErrorException ex) { if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) { - throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, - "Access denied"); + throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } - throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, - "Invalid token", ex); + throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex); } catch (HttpServerErrorException ex) { - throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "Cloud controller not reachable"); + throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable"); } } private URI getPermissionsUri(String applicationId) { try { - return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId - + "/permissions"); + return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId + "/permissions"); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); @@ -108,12 +101,10 @@ class CloudFoundrySecurityService { */ public Map fetchTokenKeys() { try { - return extractTokenKeys(this.restTemplate - .getForObject(getUaaUrl() + "/token_keys", Map.class)); + return extractTokenKeys(this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class)); } catch (HttpStatusCodeException ex) { - throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "UAA not reachable"); + throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable"); } } @@ -133,8 +124,7 @@ class CloudFoundrySecurityService { public String getUaaUrl() { if (this.uaaUrl == null) { try { - Map response = this.restTemplate - .getForObject(this.cloudControllerUrl + "/info", Map.class); + Map response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class); this.uaaUrl = (String) response.get("token_endpoint"); } catch (HttpStatusCodeException ex) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java index c8792976b9a..4f692456ed2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,17 +49,15 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMappi * @author Phillip Webb * @author Brian Clozel */ -class CloudFoundryWebEndpointServletHandlerMapping - extends AbstractWebMvcEndpointHandlerMapping { +class CloudFoundryWebEndpointServletHandlerMapping extends AbstractWebMvcEndpointHandlerMapping { private final CloudFoundrySecurityInterceptor securityInterceptor; private final EndpointLinksResolver linksResolver; CloudFoundryWebEndpointServletHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration, - CloudFoundrySecurityInterceptor securityInterceptor, + Collection endpoints, EndpointMediaTypes endpointMediaTypes, + CorsConfiguration corsConfiguration, CloudFoundrySecurityInterceptor securityInterceptor, EndpointLinksResolver linksResolver) { super(endpointMapping, endpoints, endpointMediaTypes, corsConfiguration); this.securityInterceptor = securityInterceptor; @@ -67,10 +65,9 @@ class CloudFoundryWebEndpointServletHandlerMapping } @Override - protected ServletWebOperation wrapServletWebOperation(ExposableWebEndpoint endpoint, - WebOperation operation, ServletWebOperation servletWebOperation) { - return new SecureServletWebOperation(servletWebOperation, - this.securityInterceptor, endpoint.getEndpointId()); + protected ServletWebOperation wrapServletWebOperation(ExposableWebEndpoint endpoint, WebOperation operation, + ServletWebOperation servletWebOperation) { + return new SecureServletWebOperation(servletWebOperation, this.securityInterceptor, endpoint.getEndpointId()); } @Override @@ -82,15 +79,13 @@ class CloudFoundryWebEndpointServletHandlerMapping @Override @ResponseBody - public Map> links(HttpServletRequest request, - HttpServletResponse response) { + public Map> links(HttpServletRequest request, HttpServletResponse response) { SecurityResponse securityResponse = CloudFoundryWebEndpointServletHandlerMapping.this.securityInterceptor .preHandle(request, null); if (!securityResponse.getStatus().equals(HttpStatus.OK)) { sendFailureResponse(response, securityResponse); } - AccessLevel accessLevel = (AccessLevel) request - .getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + AccessLevel accessLevel = (AccessLevel) request.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); Map filteredLinks = new LinkedHashMap<>(); if (accessLevel == null) { return Collections.singletonMap("_links", filteredLinks); @@ -98,8 +93,7 @@ class CloudFoundryWebEndpointServletHandlerMapping Map links = CloudFoundryWebEndpointServletHandlerMapping.this.linksResolver .resolveLinks(request.getRequestURL().toString()); filteredLinks = links.entrySet().stream() - .filter((e) -> e.getKey().equals("self") - || accessLevel.isAccessAllowed(e.getKey())) + .filter((e) -> e.getKey().equals("self") || accessLevel.isAccessAllowed(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return Collections.singletonMap("_links", filteredLinks); } @@ -109,11 +103,9 @@ class CloudFoundryWebEndpointServletHandlerMapping return "Actuator root web endpoint"; } - private void sendFailureResponse(HttpServletResponse response, - SecurityResponse securityResponse) { + private void sendFailureResponse(HttpServletResponse response, SecurityResponse securityResponse) { try { - response.sendError(securityResponse.getStatus().value(), - securityResponse.getMessage()); + response.sendError(securityResponse.getStatus().value(), securityResponse.getMessage()); } catch (Exception ex) { logger.debug("Failed to send error response", ex); @@ -133,8 +125,7 @@ class CloudFoundryWebEndpointServletHandlerMapping private final EndpointId endpointId; - SecureServletWebOperation(ServletWebOperation delegate, - CloudFoundrySecurityInterceptor securityInterceptor, + SecureServletWebOperation(ServletWebOperation delegate, CloudFoundrySecurityInterceptor securityInterceptor, EndpointId endpointId) { this.delegate = delegate; this.securityInterceptor = securityInterceptor; @@ -143,11 +134,9 @@ class CloudFoundryWebEndpointServletHandlerMapping @Override public Object handle(HttpServletRequest request, Map body) { - SecurityResponse securityResponse = this.securityInterceptor - .preHandle(request, this.endpointId); + SecurityResponse securityResponse = this.securityInterceptor.preHandle(request, this.endpointId); if (!securityResponse.getStatus().equals(HttpStatus.OK)) { - return new ResponseEntity(securityResponse.getMessage(), - securityResponse.getStatus()); + return new ResponseEntity(securityResponse.getMessage(), securityResponse.getStatus()); } return this.delegate.handle(request, body); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java index b67a0aa6e37..1d40a1d0f35 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory; class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFactory { @Override - protected void prepareConnection(HttpURLConnection connection, String httpMethod) - throws IOException { + protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { prepareHttpsConnection((HttpsURLConnection) connection); } @@ -59,8 +58,7 @@ class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFacto private SSLSocketFactory createSslSocketFactory() throws Exception { SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, new TrustManager[] { new SkipX509TrustManager() }, - new SecureRandom()); + context.init(null, new TrustManager[] { new SkipX509TrustManager() }, new SecureRandom()); return context.getSocketFactory(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidator.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidator.java index 02efd6732c9..0b26f5876af 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidator.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,12 +57,10 @@ class TokenValidator { private void validateAlgorithm(Token token) { String algorithm = token.getSignatureAlgorithm(); if (algorithm == null) { - throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, - "Signing algorithm cannot be null"); + throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, "Signing algorithm cannot be null"); } if (!algorithm.equals("RS256")) { - throw new CloudFoundryAuthorizationException( - Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, + throw new CloudFoundryAuthorizationException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, "Signing algorithm " + algorithm + " not supported"); } } @@ -100,8 +98,7 @@ class TokenValidator { } } - private PublicKey getPublicKey(String key) - throws NoSuchAlgorithmException, InvalidKeySpecException { + private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { key = key.replace("-----BEGIN PUBLIC KEY-----\n", ""); key = key.replace("-----END PUBLIC KEY-----", ""); key = key.trim().replace("\n", ""); @@ -113,8 +110,7 @@ class TokenValidator { private void validateExpiry(Token token) { long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); if (currentTime > token.getExpiry()) { - throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, - "Token expired"); + throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java index ca628c27e70..f05873f64ec 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java @@ -64,15 +64,13 @@ public class ConditionsReportEndpoint { Map contextConditionEvaluations = new HashMap<>(); ConfigurableApplicationContext target = this.context; while (target != null) { - contextConditionEvaluations.put(target.getId(), - new ContextConditionEvaluation(target)); + contextConditionEvaluations.put(target.getId(), new ContextConditionEvaluation(target)); target = getConfigurableParent(target); } return new ApplicationConditionEvaluation(contextConditionEvaluations); } - private ConfigurableApplicationContext getConfigurableParent( - ConfigurableApplicationContext context) { + private ConfigurableApplicationContext getConfigurableParent(ConfigurableApplicationContext context) { ApplicationContext parent = context.getParent(); if (parent instanceof ConfigurableApplicationContext) { return (ConfigurableApplicationContext) parent; @@ -88,8 +86,7 @@ public class ConditionsReportEndpoint { private final Map contexts; - private ApplicationConditionEvaluation( - Map contexts) { + private ApplicationConditionEvaluation(Map contexts) { this.contexts = contexts; } @@ -117,26 +114,23 @@ public class ConditionsReportEndpoint { private final String parentId; public ContextConditionEvaluation(ConfigurableApplicationContext context) { - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); this.positiveMatches = new LinkedMultiValueMap<>(); this.negativeMatches = new LinkedHashMap<>(); this.exclusions = report.getExclusions(); this.unconditionalClasses = report.getUnconditionalClasses(); report.getConditionAndOutcomesBySource().forEach(this::add); - this.parentId = (context.getParent() != null) ? context.getParent().getId() - : null; + this.parentId = (context.getParent() != null) ? context.getParent().getId() : null; } private void add(String source, ConditionAndOutcomes conditionAndOutcomes) { String name = ClassUtils.getShortName(source); if (conditionAndOutcomes.isFullMatch()) { - conditionAndOutcomes.forEach((conditionAndOutcome) -> this.positiveMatches - .add(name, new MessageAndCondition(conditionAndOutcome))); + conditionAndOutcomes.forEach((conditionAndOutcome) -> this.positiveMatches.add(name, + new MessageAndCondition(conditionAndOutcome))); } else { - this.negativeMatches.put(name, - new MessageAndConditions(conditionAndOutcomes)); + this.negativeMatches.put(name, new MessageAndConditions(conditionAndOutcomes)); } } @@ -174,8 +168,8 @@ public class ConditionsReportEndpoint { public MessageAndConditions(ConditionAndOutcomes conditionAndOutcomes) { for (ConditionAndOutcome conditionAndOutcome : conditionAndOutcomes) { - List target = (conditionAndOutcome.getOutcome() - .isMatch() ? this.matched : this.notMatched); + List target = (conditionAndOutcome.getOutcome().isMatch() ? this.matched + : this.notMatched); target.add(new MessageAndCondition(conditionAndOutcome)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfiguration.java index c0151d263dd..e97fdc069b1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfiguration.java @@ -37,8 +37,7 @@ public class ConditionsReportEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) - public ConditionsReportEndpoint conditionsReportEndpoint( - ConfigurableApplicationContext context) { + public ConditionsReportEndpoint conditionsReportEndpoint(ConfigurableApplicationContext context) { return new ConditionsReportEndpoint(context); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfiguration.java index 1bcaf2e900e..a28523a60fa 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfiguration.java @@ -49,13 +49,12 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnEnabledHealthIndicator("couchbase") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(CouchbaseAutoConfiguration.class) -public class CouchbaseReactiveHealthIndicatorAutoConfiguration extends - CompositeReactiveHealthIndicatorConfiguration { +public class CouchbaseReactiveHealthIndicatorAutoConfiguration + extends CompositeReactiveHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "couchbaseReactiveHealthIndicator") - public ReactiveHealthIndicator couchbaseReactiveHealthIndicator( - Map clusters) { + public ReactiveHealthIndicator couchbaseReactiveHealthIndicator(Map clusters) { return createHealthIndicator(clusters); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchClientHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchClientHealthIndicatorAutoConfiguration.java index ec2415f193c..6a4e9571ae0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchClientHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchClientHealthIndicatorAutoConfiguration.java @@ -54,13 +54,12 @@ import org.springframework.context.annotation.Configuration; @AutoConfigureAfter(ElasticsearchAutoConfiguration.class) @EnableConfigurationProperties(ElasticsearchHealthIndicatorProperties.class) @Deprecated -public class ElasticSearchClientHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class ElasticSearchClientHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { private final ElasticsearchHealthIndicatorProperties properties; - public ElasticSearchClientHealthIndicatorAutoConfiguration( - ElasticsearchHealthIndicatorProperties properties) { + public ElasticSearchClientHealthIndicatorAutoConfiguration(ElasticsearchHealthIndicatorProperties properties) { this.properties = properties; } @@ -73,8 +72,7 @@ public class ElasticSearchClientHealthIndicatorAutoConfiguration extends @Override protected ElasticsearchHealthIndicator createHealthIndicator(Client client) { Duration responseTimeout = this.properties.getResponseTimeout(); - return new ElasticsearchHealthIndicator(client, - (responseTimeout != null) ? responseTimeout.toMillis() : 100, + return new ElasticsearchHealthIndicator(client, (responseTimeout != null) ? responseTimeout.toMillis() : 100, this.properties.getIndices()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchJestHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchJestHealthIndicatorAutoConfiguration.java index 975bc6e09dc..dddf5da02dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchJestHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchJestHealthIndicatorAutoConfiguration.java @@ -48,11 +48,10 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnBean(JestClient.class) @ConditionalOnEnabledHealthIndicator("elasticsearch") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) -@AutoConfigureAfter({ JestAutoConfiguration.class, - ElasticSearchClientHealthIndicatorAutoConfiguration.class }) +@AutoConfigureAfter({ JestAutoConfiguration.class, ElasticSearchClientHealthIndicatorAutoConfiguration.class }) @Deprecated -public class ElasticSearchJestHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class ElasticSearchJestHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "elasticsearchHealthIndicator") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthIndicatorAutoConfiguration.java index 0b52b5c1c43..9efdbdd7c9b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthIndicatorAutoConfiguration.java @@ -47,16 +47,14 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnBean(RestClient.class) @ConditionalOnEnabledHealthIndicator("elasticsearch") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) -@AutoConfigureAfter({ RestClientAutoConfiguration.class, - ElasticSearchClientHealthIndicatorAutoConfiguration.class }) +@AutoConfigureAfter({ RestClientAutoConfiguration.class, ElasticSearchClientHealthIndicatorAutoConfiguration.class }) @SuppressWarnings("deprecation") -public class ElasticSearchRestHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class ElasticSearchRestHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "elasticsearchRestHealthIndicator") - public HealthIndicator elasticsearchRestHealthIndicator( - Map clients) { + public HealthIndicator elasticsearchRestHealthIndicator(Map clients) { return createHealthIndicator(clients); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorProperties.java index ac5e6e86757..93863da4abc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorProperties.java @@ -33,8 +33,7 @@ import org.springframework.boot.context.properties.DeprecatedConfigurationProper * @deprecated since 2.2.0 as {@literal org.elasticsearch.client:transport} has been * deprecated upstream */ -@ConfigurationProperties(prefix = "management.health.elasticsearch", - ignoreUnknownFields = false) +@ConfigurationProperties(prefix = "management.health.elasticsearch", ignoreUnknownFields = false) @Deprecated public class ElasticsearchHealthIndicatorProperties { @@ -48,8 +47,7 @@ public class ElasticsearchHealthIndicatorProperties { */ private Duration responseTimeout = Duration.ofMillis(100); - @DeprecatedConfigurationProperty( - reason = "Upstream elasticsearch transport is deprected") + @DeprecatedConfigurationProperty(reason = "Upstream elasticsearch transport is deprected") public List getIndices() { return this.indices; } @@ -58,8 +56,7 @@ public class ElasticsearchHealthIndicatorProperties { this.indices = indices; } - @DeprecatedConfigurationProperty( - reason = "Upstream elasticsearch transport is deprected") + @DeprecatedConfigurationProperty(reason = "Upstream elasticsearch transport is deprected") public Duration getResponseTimeout() { return this.responseTimeout; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.java index 6e93aee5a7b..07c42def213 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.java @@ -45,10 +45,8 @@ public class EndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public CachingOperationInvokerAdvisor endpointCachingOperationInvokerAdvisor( - Environment environment) { - return new CachingOperationInvokerAdvisor( - new EndpointIdTimeToLivePropertyFunction(environment)); + public CachingOperationInvokerAdvisor endpointCachingOperationInvokerAdvisor(Environment environment) { + return new CachingOperationInvokerAdvisor(new EndpointIdTimeToLivePropertyFunction(environment)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunction.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunction.java index b1b76e106e5..6a5495f1715 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunction.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ class EndpointIdTimeToLivePropertyFunction implements Function @Override public Long apply(EndpointId endpointId) { - String name = String.format("management.endpoint.%s.cache.time-to-live", - endpointId.toLowerCaseString()); + String name = String.format("management.endpoint.%s.cache.time-to-live", endpointId.toLowerCaseString()); BindResult duration = Binder.get(this.environment).bind(name, DURATION); return duration.map(Duration::toMillis).orElse(null); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilter.java index 457ec86b220..e9786a23239 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ import org.springframework.util.Assert; * @author Phillip Webb * @since 2.0.0 */ -public class ExposeExcludePropertyEndpointFilter> - implements EndpointFilter { +public class ExposeExcludePropertyEndpointFilter> implements EndpointFilter { private final Class endpointType; @@ -52,8 +51,8 @@ public class ExposeExcludePropertyEndpointFilter> private final Set exposeDefaults; - public ExposeExcludePropertyEndpointFilter(Class endpointType, - Environment environment, String prefix, String... exposeDefaults) { + public ExposeExcludePropertyEndpointFilter(Class endpointType, Environment environment, String prefix, + String... exposeDefaults) { Assert.notNull(endpointType, "EndpointType must not be null"); Assert.notNull(environment, "Environment must not be null"); Assert.hasText(prefix, "Prefix must not be empty"); @@ -64,9 +63,8 @@ public class ExposeExcludePropertyEndpointFilter> this.exposeDefaults = asSet(Arrays.asList(exposeDefaults)); } - public ExposeExcludePropertyEndpointFilter(Class endpointType, - Collection include, Collection exclude, - String... exposeDefaults) { + public ExposeExcludePropertyEndpointFilter(Class endpointType, Collection include, + Collection exclude, String... exposeDefaults) { Assert.notNull(endpointType, "EndpointType Type must not be null"); this.endpointType = endpointType; this.include = asSet(include); @@ -75,8 +73,7 @@ public class ExposeExcludePropertyEndpointFilter> } private Set bind(Binder binder, String name) { - return asSet(binder.bind(name, Bindable.listOf(String.class)).map(this::cleanup) - .orElseGet(ArrayList::new)); + return asSet(binder.bind(name, Bindable.listOf(String.class)).map(this::cleanup).orElseGet(ArrayList::new)); } private List cleanup(List values) { @@ -84,16 +81,14 @@ public class ExposeExcludePropertyEndpointFilter> } private String cleanup(String value) { - return "*".equals(value) ? "*" - : EndpointId.fromPropertyValue(value).toLowerCaseString(); + return "*".equals(value) ? "*" : EndpointId.fromPropertyValue(value).toLowerCaseString(); } private Set asSet(Collection items) { if (items == null) { return Collections.emptySet(); } - return items.stream().map((item) -> item.toLowerCase(Locale.ENGLISH)) - .collect(Collectors.toSet()); + return items.stream().map((item) -> item.toLowerCase(Locale.ENGLISH)).collect(Collectors.toSet()); } @Override @@ -106,8 +101,7 @@ public class ExposeExcludePropertyEndpointFilter> private boolean isExposed(ExposableEndpoint endpoint) { if (this.include.isEmpty()) { - return this.exposeDefaults.contains("*") - || contains(this.exposeDefaults, endpoint); + return this.exposeDefaults.contains("*") || contains(this.exposeDefaults, endpoint); } return this.include.contains("*") || contains(this.include, endpoint); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/AbstractEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/AbstractEndpointCondition.java index 432b81c41ca..2f234018750 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/AbstractEndpointCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/AbstractEndpointCondition.java @@ -53,85 +53,69 @@ abstract class AbstractEndpointCondition extends SpringBootCondition { private static final ConcurrentReferenceHashMap> enabledByDefaultCache = new ConcurrentReferenceHashMap<>(); - AnnotationAttributes getEndpointAttributes(Class annotationClass, - ConditionContext context, AnnotatedTypeMetadata metadata) { + AnnotationAttributes getEndpointAttributes(Class annotationClass, ConditionContext context, + AnnotatedTypeMetadata metadata) { return getEndpointAttributes(getEndpointType(annotationClass, context, metadata)); } - protected ConditionOutcome getEnablementOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata, Class annotationClass) { + protected ConditionOutcome getEnablementOutcome(ConditionContext context, AnnotatedTypeMetadata metadata, + Class annotationClass) { Environment environment = context.getEnvironment(); - AnnotationAttributes attributes = getEndpointAttributes(annotationClass, context, - metadata); + AnnotationAttributes attributes = getEndpointAttributes(annotationClass, context, metadata); EndpointId id = EndpointId.of(attributes.getString("id")); String key = "management.endpoint." + id.toLowerCaseString() + ".enabled"; Boolean userDefinedEnabled = environment.getProperty(key, Boolean.class); if (userDefinedEnabled != null) { - return new ConditionOutcome(userDefinedEnabled, - ConditionMessage.forCondition(annotationClass) - .because("found property " + key + " with value " - + userDefinedEnabled)); + return new ConditionOutcome(userDefinedEnabled, ConditionMessage.forCondition(annotationClass) + .because("found property " + key + " with value " + userDefinedEnabled)); } Boolean userDefinedDefault = isEnabledByDefault(environment); if (userDefinedDefault != null) { - return new ConditionOutcome(userDefinedDefault, - ConditionMessage.forCondition(annotationClass) - .because("no property " + key - + " found so using user defined default from " - + ENABLED_BY_DEFAULT_KEY)); + return new ConditionOutcome(userDefinedDefault, ConditionMessage.forCondition(annotationClass).because( + "no property " + key + " found so using user defined default from " + ENABLED_BY_DEFAULT_KEY)); } boolean endpointDefault = attributes.getBoolean("enableByDefault"); - return new ConditionOutcome(endpointDefault, - ConditionMessage.forCondition(annotationClass).because( - "no property " + key + " found so using endpoint default")); + return new ConditionOutcome(endpointDefault, ConditionMessage.forCondition(annotationClass) + .because("no property " + key + " found so using endpoint default")); } protected Class getEndpointType(Class annotationClass, ConditionContext context, AnnotatedTypeMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(annotationClass.getName()); + Map attributes = metadata.getAnnotationAttributes(annotationClass.getName()); if (attributes != null && attributes.containsKey("endpoint")) { Class target = (Class) attributes.get("endpoint"); if (target != Void.class) { return target; } } - Assert.state( - metadata instanceof MethodMetadata - && metadata.isAnnotated(Bean.class.getName()), + Assert.state(metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName()), "EndpointCondition must be used on @Bean methods when the endpoint is not specified"); MethodMetadata methodMetadata = (MethodMetadata) metadata; try { - return ClassUtils.forName(methodMetadata.getReturnTypeName(), - context.getClassLoader()); + return ClassUtils.forName(methodMetadata.getReturnTypeName(), context.getClassLoader()); } catch (Throwable ex) { throw new IllegalStateException("Failed to extract endpoint id for " - + methodMetadata.getDeclaringClassName() + "." - + methodMetadata.getMethodName(), ex); + + methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(), ex); } } protected AnnotationAttributes getEndpointAttributes(Class type) { - MergedAnnotations annotations = MergedAnnotations.from(type, - SearchStrategy.EXHAUSTIVE); + MergedAnnotations annotations = MergedAnnotations.from(type, SearchStrategy.EXHAUSTIVE); MergedAnnotation endpoint = annotations.get(Endpoint.class); if (endpoint.isPresent()) { return endpoint.asAnnotationAttributes(); } - MergedAnnotation extension = annotations - .get(EndpointExtension.class); - Assert.state(extension.isPresent(), - "No endpoint is specified and the return type of the @Bean method is " - + "neither an @Endpoint, nor an @EndpointExtension"); + MergedAnnotation extension = annotations.get(EndpointExtension.class); + Assert.state(extension.isPresent(), "No endpoint is specified and the return type of the @Bean method is " + + "neither an @Endpoint, nor an @EndpointExtension"); return getEndpointAttributes(extension.getClass("endpoint")); } private Boolean isEnabledByDefault(Environment environment) { Optional enabledByDefault = enabledByDefaultCache.get(environment); if (enabledByDefault == null) { - enabledByDefault = Optional.ofNullable( - environment.getProperty(ENABLED_BY_DEFAULT_KEY, Boolean.class)); + enabledByDefault = Optional.ofNullable(environment.getProperty(ENABLED_BY_DEFAULT_KEY, Boolean.class)); enabledByDefaultCache.put(environment, enabledByDefault); } return enabledByDefault.orElse(null); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java index cc5fadf7c4b..36809efa2dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java @@ -48,8 +48,7 @@ class OnAvailableEndpointCondition extends AbstractEndpointCondition { private static final ConcurrentReferenceHashMap> endpointExposureCache = new ConcurrentReferenceHashMap<>(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionOutcome enablementOutcome = getEnablementOutcome(context, metadata, ConditionalOnAvailableEndpoint.class); if (!enablementOutcome.isMatch()) { @@ -58,40 +57,34 @@ class OnAvailableEndpointCondition extends AbstractEndpointCondition { ConditionMessage message = enablementOutcome.getConditionMessage(); Environment environment = context.getEnvironment(); if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) { - return new ConditionOutcome(true, - message.andCondition(ConditionalOnAvailableEndpoint.class) - .because("application is running on Cloud Foundry")); + return new ConditionOutcome(true, message.andCondition(ConditionalOnAvailableEndpoint.class) + .because("application is running on Cloud Foundry")); } - AnnotationAttributes attributes = getEndpointAttributes( - ConditionalOnAvailableEndpoint.class, context, metadata); + AnnotationAttributes attributes = getEndpointAttributes(ConditionalOnAvailableEndpoint.class, context, + metadata); EndpointId id = EndpointId.of(attributes.getString("id")); - Set exposureInformations = getExposureInformation( - environment); + Set exposureInformations = getExposureInformation(environment); for (ExposureInformation exposureInformation : exposureInformations) { if (exposureInformation.isExposed(id)) { return new ConditionOutcome(true, message.andCondition(ConditionalOnAvailableEndpoint.class) .because("marked as exposed by a 'management.endpoints." - + exposureInformation.getPrefix() - + ".exposure' property")); + + exposureInformation.getPrefix() + ".exposure' property")); } } - return new ConditionOutcome(false, - message.andCondition(ConditionalOnAvailableEndpoint.class).because( - "no 'management.endpoints' property marked it as exposed")); + return new ConditionOutcome(false, message.andCondition(ConditionalOnAvailableEndpoint.class) + .because("no 'management.endpoints' property marked it as exposed")); } private Set getExposureInformation(Environment environment) { - Set exposureInformations = endpointExposureCache - .get(environment); + Set exposureInformations = endpointExposureCache.get(environment); if (exposureInformations == null) { exposureInformations = new HashSet<>(2); Binder binder = Binder.get(environment); if (environment.getProperty(JMX_ENABLED_KEY, Boolean.class, false)) { exposureInformations.add(new ExposureInformation(binder, "jmx", "*")); } - exposureInformations - .add(new ExposureInformation(binder, "web", "info", "health")); + exposureInformations.add(new ExposureInformation(binder, "web", "info", "health")); endpointExposureCache.put(environment, exposureInformations); } return exposureInformations; @@ -109,20 +102,16 @@ class OnAvailableEndpointCondition extends AbstractEndpointCondition { ExposureInformation(Binder binder, String prefix, String... exposeDefaults) { this.prefix = prefix; - this.include = bind(binder, - "management.endpoints." + prefix + ".exposure.include"); - this.exclude = bind(binder, - "management.endpoints." + prefix + ".exposure.exclude"); + this.include = bind(binder, "management.endpoints." + prefix + ".exposure.include"); + this.exclude = bind(binder, "management.endpoints." + prefix + ".exposure.exclude"); this.exposeDefaults = new HashSet<>(Arrays.asList(exposeDefaults)); } private Set bind(Binder binder, String name) { - List values = binder.bind(name, Bindable.listOf(String.class)) - .orElse(Collections.emptyList()); + List values = binder.bind(name, Bindable.listOf(String.class)).orElse(Collections.emptyList()); Set result = new HashSet<>(values.size()); for (String value : values) { - result.add("*".equals(value) ? "*" - : EndpointId.fromPropertyValue(value).toLowerCaseString()); + result.add("*".equals(value) ? "*" : EndpointId.fromPropertyValue(value).toLowerCaseString()); } return result; } @@ -139,8 +128,7 @@ class OnAvailableEndpointCondition extends AbstractEndpointCondition { } } if (this.include.isEmpty()) { - if (this.exposeDefaults.contains("*") - || this.exposeDefaults.contains(id)) { + if (this.exposeDefaults.contains("*") || this.exposeDefaults.contains(id)) { return true; } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnEnabledEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnEnabledEndpointCondition.java index b1cb0119362..2babd17f148 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnEnabledEndpointCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnEnabledEndpointCondition.java @@ -33,10 +33,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnEnabledEndpointCondition extends AbstractEndpointCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - return getEnablementOutcome(context, metadata, - ConditionalOnEnabledEndpoint.class); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + return getEnablementOutcome(context, metadata, ConditionalOnEnabledEndpoint.class); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java index 22ee21513e4..b6b02ea19fe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java @@ -45,23 +45,20 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { private final boolean uniqueNames; - DefaultEndpointObjectNameFactory(JmxEndpointProperties properties, - Environment environment, MBeanServer mBeanServer, String contextId) { + DefaultEndpointObjectNameFactory(JmxEndpointProperties properties, Environment environment, MBeanServer mBeanServer, + String contextId) { this.properties = properties; this.environment = environment; this.mBeanServer = mBeanServer; this.contextId = contextId; - this.uniqueNames = environment.getProperty("spring.jmx.unique-names", - Boolean.class, false); + this.uniqueNames = environment.getProperty("spring.jmx.unique-names", Boolean.class, false); } @Override - public ObjectName getObjectName(ExposableJmxEndpoint endpoint) - throws MalformedObjectNameException { + public ObjectName getObjectName(ExposableJmxEndpoint endpoint) throws MalformedObjectNameException { StringBuilder builder = new StringBuilder(determineDomain()); builder.append(":type=Endpoint"); - builder.append(",name=") - .append(StringUtils.capitalize(endpoint.getEndpointId().toString())); + builder.append(",name=").append(StringUtils.capitalize(endpoint.getEndpointId().toString())); String baseName = builder.toString(); if (this.mBeanServer != null && hasMBean(baseName)) { builder.append(",context=").append(this.contextId); @@ -78,8 +75,7 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { if (StringUtils.hasText(this.properties.getDomain())) { return this.properties.getDomain(); } - return this.environment.getProperty("spring.jmx.default-domain", - "org.springframework.boot"); + return this.environment.getProperty("spring.jmx.default-domain", "org.springframework.boot"); } private boolean hasMBean(String baseObjectName) throws MalformedObjectNameException { @@ -92,8 +88,8 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { return ""; } StringBuilder builder = new StringBuilder(); - this.properties.getStaticNames().forEach((name, value) -> builder.append(",") - .append(name).append("=").append(value)); + this.properties.getStaticNames() + .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); return builder.toString(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java index 2825eaca07d..e2af732276b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java @@ -67,16 +67,14 @@ public class JmxEndpointAutoConfiguration { private final JmxEndpointProperties properties; - public JmxEndpointAutoConfiguration(ApplicationContext applicationContext, - JmxEndpointProperties properties) { + public JmxEndpointAutoConfiguration(ApplicationContext applicationContext, JmxEndpointProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @Bean @ConditionalOnMissingBean(JmxEndpointsSupplier.class) - public JmxEndpointDiscoverer jmxAnnotationEndpointDiscoverer( - ParameterValueMapper parameterValueMapper, + public JmxEndpointDiscoverer jmxAnnotationEndpointDiscoverer(ParameterValueMapper parameterValueMapper, ObjectProvider invokerAdvisors, ObjectProvider> filters) { return new JmxEndpointDiscoverer(this.applicationContext, parameterValueMapper, @@ -86,12 +84,11 @@ public class JmxEndpointAutoConfiguration { @Bean @ConditionalOnSingleCandidate(MBeanServer.class) - public JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, - Environment environment, ObjectProvider objectMapper, - JmxEndpointsSupplier jmxEndpointsSupplier) { + public JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, Environment environment, + ObjectProvider objectMapper, JmxEndpointsSupplier jmxEndpointsSupplier) { String contextId = ObjectUtils.getIdentityHexString(this.applicationContext); - EndpointObjectNameFactory objectNameFactory = new DefaultEndpointObjectNameFactory( - this.properties, environment, mBeanServer, contextId); + EndpointObjectNameFactory objectNameFactory = new DefaultEndpointObjectNameFactory(this.properties, environment, + mBeanServer, contextId); JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper( objectMapper.getIfAvailable()); return new JmxEndpointExporter(mBeanServer, objectNameFactory, responseMapper, @@ -102,8 +99,8 @@ public class JmxEndpointAutoConfiguration { @Bean public ExposeExcludePropertyEndpointFilter jmxIncludeExcludePropertyEndpointFilter() { JmxEndpointProperties.Exposure exposure = this.properties.getExposure(); - return new ExposeExcludePropertyEndpointFilter<>(ExposableJmxEndpoint.class, - exposure.getInclude(), exposure.getExclude(), "*"); + return new ExposeExcludePropertyEndpointFilter<>(ExposableJmxEndpoint.class, exposure.getInclude(), + exposure.getExclude(), "*"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/CorsEndpointProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/CorsEndpointProperties.java index 41e5d95199c..979309da252 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/CorsEndpointProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/CorsEndpointProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,16 +125,11 @@ public class CorsEndpointProperties { PropertyMapper map = PropertyMapper.get(); CorsConfiguration configuration = new CorsConfiguration(); map.from(this::getAllowedOrigins).to(configuration::setAllowedOrigins); - map.from(this::getAllowedHeaders).whenNot(CollectionUtils::isEmpty) - .to(configuration::setAllowedHeaders); - map.from(this::getAllowedMethods).whenNot(CollectionUtils::isEmpty) - .to(configuration::setAllowedMethods); - map.from(this::getExposedHeaders).whenNot(CollectionUtils::isEmpty) - .to(configuration::setExposedHeaders); - map.from(this::getMaxAge).whenNonNull().as(Duration::getSeconds) - .to(configuration::setMaxAge); - map.from(this::getAllowCredentials).whenNonNull() - .to(configuration::setAllowCredentials); + map.from(this::getAllowedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedHeaders); + map.from(this::getAllowedMethods).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedMethods); + map.from(this::getExposedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setExposedHeaders); + map.from(this::getMaxAge).whenNonNull().as(Duration::getSeconds).to(configuration::setMaxAge); + map.from(this::getAllowCredentials).whenNonNull().to(configuration::setAllowCredentials); return configuration; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapper.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapper.java index 76e50fdcd64..a16202314b4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapper.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ class MappingWebEndpointPathMapper implements PathMapper { MappingWebEndpointPathMapper(Map pathMapping) { this.pathMapping = new HashMap<>(); - pathMapping.forEach((id, path) -> this.pathMapping - .put(EndpointId.fromPropertyValue(id), path)); + pathMapping.forEach((id, path) -> this.pathMapping.put(EndpointId.fromPropertyValue(id), path)); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration.java index 5c93fb400cb..2255a262c26 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration.java @@ -50,8 +50,8 @@ public class ServletEndpointManagementContextConfiguration { public ExposeExcludePropertyEndpointFilter servletExposeExcludePropertyEndpointFilter( WebEndpointProperties properties) { WebEndpointProperties.Exposure exposure = properties.getExposure(); - return new ExposeExcludePropertyEndpointFilter<>(ExposableServletEndpoint.class, - exposure.getInclude(), exposure.getExclude()); + return new ExposeExcludePropertyEndpointFilter<>(ExposableServletEndpoint.class, exposure.getInclude(), + exposure.getExclude()); } @Configuration(proxyBeanMethods = false) @@ -59,12 +59,9 @@ public class ServletEndpointManagementContextConfiguration { public static class WebMvcServletEndpointManagementContextConfiguration { @Bean - public ServletEndpointRegistrar servletEndpointRegistrar( - WebEndpointProperties properties, - ServletEndpointsSupplier servletEndpointsSupplier, - DispatcherServletPath dispatcherServletPath) { - return new ServletEndpointRegistrar( - dispatcherServletPath.getRelativePath(properties.getBasePath()), + public ServletEndpointRegistrar servletEndpointRegistrar(WebEndpointProperties properties, + ServletEndpointsSupplier servletEndpointsSupplier, DispatcherServletPath dispatcherServletPath) { + return new ServletEndpointRegistrar(dispatcherServletPath.getRelativePath(properties.getBasePath()), servletEndpointsSupplier.getEndpoints()); } @@ -76,12 +73,9 @@ public class ServletEndpointManagementContextConfiguration { public static class JerseyServletEndpointManagementContextConfiguration { @Bean - public ServletEndpointRegistrar servletEndpointRegistrar( - WebEndpointProperties properties, - ServletEndpointsSupplier servletEndpointsSupplier, - JerseyApplicationPath jerseyApplicationPath) { - return new ServletEndpointRegistrar( - jerseyApplicationPath.getRelativePath(properties.getBasePath()), + public ServletEndpointRegistrar servletEndpointRegistrar(WebEndpointProperties properties, + ServletEndpointsSupplier servletEndpointsSupplier, JerseyApplicationPath jerseyApplicationPath) { + return new ServletEndpointRegistrar(jerseyApplicationPath.getRelativePath(properties.getBasePath()), servletEndpointsSupplier.getEndpoints()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfiguration.java index 8008a868b92..43809884714 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfiguration.java @@ -67,15 +67,13 @@ import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties(WebEndpointProperties.class) public class WebEndpointAutoConfiguration { - private static final List MEDIA_TYPES = Arrays - .asList(ActuatorMediaType.V2_JSON, "application/json"); + private static final List MEDIA_TYPES = Arrays.asList(ActuatorMediaType.V2_JSON, "application/json"); private final ApplicationContext applicationContext; private final WebEndpointProperties properties; - public WebEndpointAutoConfiguration(ApplicationContext applicationContext, - WebEndpointProperties properties) { + public WebEndpointAutoConfiguration(ApplicationContext applicationContext, WebEndpointProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @@ -93,14 +91,11 @@ public class WebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(WebEndpointsSupplier.class) - public WebEndpointDiscoverer webEndpointDiscoverer( - ParameterValueMapper parameterValueMapper, - EndpointMediaTypes endpointMediaTypes, - ObjectProvider endpointPathMappers, + public WebEndpointDiscoverer webEndpointDiscoverer(ParameterValueMapper parameterValueMapper, + EndpointMediaTypes endpointMediaTypes, ObjectProvider endpointPathMappers, ObjectProvider invokerAdvisors, ObjectProvider> filters) { - return new WebEndpointDiscoverer(this.applicationContext, parameterValueMapper, - endpointMediaTypes, + return new WebEndpointDiscoverer(this.applicationContext, parameterValueMapper, endpointMediaTypes, endpointPathMappers.orderedStream().collect(Collectors.toList()), invokerAdvisors.orderedStream().collect(Collectors.toList()), filters.orderedStream().collect(Collectors.toList())); @@ -108,8 +103,7 @@ public class WebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(ControllerEndpointsSupplier.class) - public ControllerEndpointDiscoverer controllerEndpointDiscoverer( - ObjectProvider endpointPathMappers, + public ControllerEndpointDiscoverer controllerEndpointDiscoverer(ObjectProvider endpointPathMappers, ObjectProvider>> filters) { return new ControllerEndpointDiscoverer(this.applicationContext, endpointPathMappers.orderedStream().collect(Collectors.toList()), @@ -118,25 +112,22 @@ public class WebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public PathMappedEndpoints pathMappedEndpoints( - Collection> endpointSuppliers, + public PathMappedEndpoints pathMappedEndpoints(Collection> endpointSuppliers, WebEndpointProperties webEndpointProperties) { - return new PathMappedEndpoints(webEndpointProperties.getBasePath(), - endpointSuppliers); + return new PathMappedEndpoints(webEndpointProperties.getBasePath(), endpointSuppliers); } @Bean public ExposeExcludePropertyEndpointFilter webExposeExcludePropertyEndpointFilter() { WebEndpointProperties.Exposure exposure = this.properties.getExposure(); - return new ExposeExcludePropertyEndpointFilter<>(ExposableWebEndpoint.class, - exposure.getInclude(), exposure.getExclude(), "info", "health"); + return new ExposeExcludePropertyEndpointFilter<>(ExposableWebEndpoint.class, exposure.getInclude(), + exposure.getExclude(), "info", "health"); } @Bean public ExposeExcludePropertyEndpointFilter controllerExposeExcludePropertyEndpointFilter() { WebEndpointProperties.Exposure exposure = this.properties.getExposure(); - return new ExposeExcludePropertyEndpointFilter<>( - ExposableControllerEndpoint.class, exposure.getInclude(), + return new ExposeExcludePropertyEndpointFilter<>(ExposableControllerEndpoint.class, exposure.getInclude(), exposure.getExclude()); } @@ -146,8 +137,7 @@ public class WebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(ServletEndpointsSupplier.class) - public ServletEndpointDiscoverer servletEndpointDiscoverer( - ApplicationContext applicationContext, + public ServletEndpointDiscoverer servletEndpointDiscoverer(ApplicationContext applicationContext, ObjectProvider endpointPathMappers, ObjectProvider> filters) { return new ServletEndpointDiscoverer(applicationContext, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointProperties.java index 7d14b673cac..aded969536d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,7 @@ public class WebEndpointProperties { } public void setBasePath(String basePath) { - Assert.isTrue(basePath.isEmpty() || basePath.startsWith("/"), - "Base path must start with '/' or be empty"); + Assert.isTrue(basePath.isEmpty() || basePath.startsWith("/"), "Base path must start with '/' or be empty"); this.basePath = cleanBasePath(basePath); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java index cea0fb81621..f9a6fd2cdaf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java @@ -60,10 +60,8 @@ import org.springframework.context.annotation.Bean; class JerseyWebEndpointManagementContextConfiguration { @Bean - public ResourceConfigCustomizer webEndpointRegistrar( - WebEndpointsSupplier webEndpointsSupplier, - ServletEndpointsSupplier servletEndpointsSupplier, - EndpointMediaTypes endpointMediaTypes, + public ResourceConfigCustomizer webEndpointRegistrar(WebEndpointsSupplier webEndpointsSupplier, + ServletEndpointsSupplier servletEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, WebEndpointProperties webEndpointProperties) { List> allEndpoints = new ArrayList<>(); allEndpoints.addAll(webEndpointsSupplier.getEndpoints()); @@ -74,10 +72,8 @@ class JerseyWebEndpointManagementContextConfiguration { EndpointMapping endpointMapping = new EndpointMapping(basePath); Collection webEndpoints = Collections .unmodifiableCollection(webEndpointsSupplier.getEndpoints()); - resourceConfig.registerResources( - new HashSet<>(resourceFactory.createEndpointResources(endpointMapping, - webEndpoints, endpointMediaTypes, - new EndpointLinksResolver(allEndpoints, basePath)))); + resourceConfig.registerResources(new HashSet<>(resourceFactory.createEndpointResources(endpointMapping, + webEndpoints, endpointMediaTypes, new EndpointLinksResolver(allEndpoints, basePath)))); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java index af4949f773b..e0ef4be2ac0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java @@ -60,33 +60,26 @@ public class WebFluxEndpointManagementContextConfiguration { @Bean @ConditionalOnMissingBean - public WebFluxEndpointHandlerMapping webEndpointReactiveHandlerMapping( - WebEndpointsSupplier webEndpointsSupplier, - ControllerEndpointsSupplier controllerEndpointsSupplier, - EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, - WebEndpointProperties webEndpointProperties) { - EndpointMapping endpointMapping = new EndpointMapping( - webEndpointProperties.getBasePath()); + public WebFluxEndpointHandlerMapping webEndpointReactiveHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, + ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, + CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties) { + EndpointMapping endpointMapping = new EndpointMapping(webEndpointProperties.getBasePath()); Collection endpoints = webEndpointsSupplier.getEndpoints(); List> allEndpoints = new ArrayList<>(); allEndpoints.addAll(endpoints); allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints()); - return new WebFluxEndpointHandlerMapping(endpointMapping, endpoints, - endpointMediaTypes, corsProperties.toCorsConfiguration(), - new EndpointLinksResolver(allEndpoints, - webEndpointProperties.getBasePath())); + return new WebFluxEndpointHandlerMapping(endpointMapping, endpoints, endpointMediaTypes, + corsProperties.toCorsConfiguration(), + new EndpointLinksResolver(allEndpoints, webEndpointProperties.getBasePath())); } @Bean @ConditionalOnMissingBean public ControllerEndpointHandlerMapping controllerEndpointHandlerMapping( - ControllerEndpointsSupplier controllerEndpointsSupplier, - CorsEndpointProperties corsProperties, + ControllerEndpointsSupplier controllerEndpointsSupplier, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties) { - EndpointMapping endpointMapping = new EndpointMapping( - webEndpointProperties.getBasePath()); - return new ControllerEndpointHandlerMapping(endpointMapping, - controllerEndpointsSupplier.getEndpoints(), + EndpointMapping endpointMapping = new EndpointMapping(webEndpointProperties.getBasePath()); + return new ControllerEndpointHandlerMapping(endpointMapping, controllerEndpointsSupplier.getEndpoints(), corsProperties.toCorsConfiguration()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java index 2c18dcd4464..023d65c8504 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java @@ -60,36 +60,28 @@ public class WebMvcEndpointManagementContextConfiguration { @Bean @ConditionalOnMissingBean - public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping( - WebEndpointsSupplier webEndpointsSupplier, - ServletEndpointsSupplier servletEndpointsSupplier, - ControllerEndpointsSupplier controllerEndpointsSupplier, + public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, + ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties) { List> allEndpoints = new ArrayList<>(); - Collection webEndpoints = webEndpointsSupplier - .getEndpoints(); + Collection webEndpoints = webEndpointsSupplier.getEndpoints(); allEndpoints.addAll(webEndpoints); allEndpoints.addAll(servletEndpointsSupplier.getEndpoints()); allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints()); - EndpointMapping endpointMapping = new EndpointMapping( - webEndpointProperties.getBasePath()); - return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, - endpointMediaTypes, corsProperties.toCorsConfiguration(), - new EndpointLinksResolver(allEndpoints, - webEndpointProperties.getBasePath())); + EndpointMapping endpointMapping = new EndpointMapping(webEndpointProperties.getBasePath()); + return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, + corsProperties.toCorsConfiguration(), + new EndpointLinksResolver(allEndpoints, webEndpointProperties.getBasePath())); } @Bean @ConditionalOnMissingBean public ControllerEndpointHandlerMapping controllerEndpointHandlerMapping( - ControllerEndpointsSupplier controllerEndpointsSupplier, - CorsEndpointProperties corsProperties, + ControllerEndpointsSupplier controllerEndpointsSupplier, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties) { - EndpointMapping endpointMapping = new EndpointMapping( - webEndpointProperties.getBasePath()); - return new ControllerEndpointHandlerMapping(endpointMapping, - controllerEndpointsSupplier.getEndpoints(), + EndpointMapping endpointMapping = new EndpointMapping(webEndpointProperties.getBasePath()); + return new ControllerEndpointHandlerMapping(endpointMapping, controllerEndpointsSupplier.getEndpoints(), corsProperties.toCorsConfiguration()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfiguration.java index fbaa096b3c9..c8af552deab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfiguration.java @@ -41,8 +41,7 @@ public class EnvironmentEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public EnvironmentEndpoint environmentEndpoint(Environment environment, - EnvironmentEndpointProperties properties) { + public EnvironmentEndpoint environmentEndpoint(Environment environment, EnvironmentEndpointProperties properties) { EnvironmentEndpoint endpoint = new EnvironmentEndpoint(environment); String[] keysToSanitize = properties.getKeysToSanitize(); if (keysToSanitize != null) { @@ -54,8 +53,7 @@ public class EnvironmentEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(EnvironmentEndpoint.class) - public EnvironmentEndpointWebExtension environmentEndpointWebExtension( - EnvironmentEndpoint environmentEndpoint) { + public EnvironmentEndpointWebExtension environmentEndpointWebExtension(EnvironmentEndpoint environmentEndpoint) { return new EnvironmentEndpointWebExtension(environmentEndpoint); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/CompositeHealthIndicatorConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/CompositeHealthIndicatorConfiguration.java index 2bd2dd74da2..85b713751e6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/CompositeHealthIndicatorConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/CompositeHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,15 +45,13 @@ public abstract class CompositeHealthIndicatorConfiguration registry.register(name, createHealthIndicator(source))); + beans.forEach((name, source) -> registry.register(name, createHealthIndicator(source))); return new CompositeHealthIndicator(this.healthAggregator, registry); } @SuppressWarnings("unchecked") protected H createHealthIndicator(S source) { - Class[] generics = ResolvableType - .forClass(CompositeHealthIndicatorConfiguration.class, getClass()) + Class[] generics = ResolvableType.forClass(CompositeHealthIndicatorConfiguration.class, getClass()) .resolveGenerics(); Class indicatorClass = (Class) generics[0]; Class sourceClass = (Class) generics[1]; @@ -61,8 +59,8 @@ public abstract class CompositeHealthIndicatorConfiguration registry.register(name, createHealthIndicator(source))); + beans.forEach((name, source) -> registry.register(name, createHealthIndicator(source))); return new CompositeReactiveHealthIndicator(this.healthAggregator, registry); } @SuppressWarnings("unchecked") protected H createHealthIndicator(S source) { - Class[] generics = ResolvableType - .forClass(CompositeReactiveHealthIndicatorConfiguration.class, getClass()) + Class[] generics = ResolvableType.forClass(CompositeReactiveHealthIndicatorConfiguration.class, getClass()) .resolveGenerics(); Class indicatorClass = (Class) generics[0]; Class sourceClass = (Class) generics[1]; @@ -60,8 +58,8 @@ public abstract class CompositeReactiveHealthIndicatorConfiguration healthAggregator, - ReactiveHealthIndicatorRegistry registry, + ObjectProvider healthAggregator, ReactiveHealthIndicatorRegistry registry, HealthWebEndpointResponseMapper responseMapper) { - return new ReactiveHealthEndpointWebExtension( - new CompositeReactiveHealthIndicator( - healthAggregator.getIfAvailable(OrderedHealthAggregator::new), - registry), - responseMapper); + return new ReactiveHealthEndpointWebExtension(new CompositeReactiveHealthIndicator( + healthAggregator.getIfAvailable(OrderedHealthAggregator::new), registry), responseMapper); } } @@ -94,8 +88,7 @@ class HealthEndpointWebExtensionConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(HealthEndpoint.class) - public HealthEndpointWebExtension healthEndpointWebExtension( - HealthEndpoint healthEndpoint, + public HealthEndpointWebExtension healthEndpointWebExtension(HealthEndpoint healthEndpoint, HealthWebEndpointResponseMapper responseMapper) { return new HealthEndpointWebExtension(healthEndpoint, responseMapper); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.java index 0ab5521bfda..d02b5e90acc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.java @@ -57,8 +57,7 @@ public class HealthIndicatorAutoConfiguration { @Bean @ConditionalOnMissingBean(HealthAggregator.class) - public OrderedHealthAggregator healthAggregator( - HealthIndicatorProperties properties) { + public OrderedHealthAggregator healthAggregator(HealthIndicatorProperties properties) { OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator(); if (properties.getOrder() != null) { healthAggregator.setStatusOrder(properties.getOrder()); @@ -68,8 +67,7 @@ public class HealthIndicatorAutoConfiguration { @Bean @ConditionalOnMissingBean(HealthIndicatorRegistry.class) - public HealthIndicatorRegistry healthIndicatorRegistry( - ApplicationContext applicationContext) { + public HealthIndicatorRegistry healthIndicatorRegistry(ApplicationContext applicationContext) { return HealthIndicatorRegistryBeans.get(applicationContext); } @@ -83,8 +81,7 @@ public class HealthIndicatorAutoConfiguration { Map reactiveHealthIndicators, Map healthIndicators) { return new ReactiveHealthIndicatorRegistryFactory() - .createReactiveHealthIndicatorRegistry(reactiveHealthIndicators, - healthIndicators); + .createReactiveHealthIndicatorRegistry(reactiveHealthIndicators, healthIndicators); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorRegistryBeans.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorRegistryBeans.java index 06b39d1d48b..57f5585e591 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorRegistryBeans.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorRegistryBeans.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ final class HealthIndicatorRegistryBeans { Map indicators = new LinkedHashMap<>(); indicators.putAll(applicationContext.getBeansOfType(HealthIndicator.class)); if (ClassUtils.isPresent("reactor.core.publisher.Flux", null)) { - new ReactiveHealthIndicators().get(applicationContext) - .forEach(indicators::putIfAbsent); + new ReactiveHealthIndicators().get(applicationContext).forEach(indicators::putIfAbsent); } HealthIndicatorRegistryFactory factory = new HealthIndicatorRegistryFactory(); return factory.createHealthIndicatorRegistry(indicators); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfiguration.java index 24b7878d280..92ffca446b4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfiguration.java @@ -55,8 +55,7 @@ public class InfoContributorAutoConfiguration { @Bean @ConditionalOnEnabledInfoContributor("env") @Order(DEFAULT_ORDER) - public EnvironmentInfoContributor envInfoContributor( - ConfigurableEnvironment environment) { + public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) { return new EnvironmentInfoContributor(environment); } @@ -67,8 +66,7 @@ public class InfoContributorAutoConfiguration { @Order(DEFAULT_ORDER) public GitInfoContributor gitInfoContributor(GitProperties gitProperties, InfoContributorProperties infoContributorProperties) { - return new GitInfoContributor(gitProperties, - infoContributorProperties.getGit().getMode()); + return new GitInfoContributor(gitProperties, infoContributorProperties.getGit().getMode()); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfiguration.java index ab24e4859c0..ed24ab0cf68 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfiguration.java @@ -42,8 +42,7 @@ public class InfoEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean public InfoEndpoint infoEndpoint(ObjectProvider infoContributors) { - return new InfoEndpoint( - infoContributors.orderedStream().collect(Collectors.toList())); + return new InfoEndpoint(infoContributors.orderedStream().collect(Collectors.toList())); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfiguration.java index 51fa95a4344..63d151b2b90 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfiguration.java @@ -46,8 +46,7 @@ public class IntegrationGraphEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public IntegrationGraphEndpoint integrationGraphEndpoint( - IntegrationGraphServer integrationGraphServer) { + public IntegrationGraphEndpoint integrationGraphEndpoint(IntegrationGraphServer integrationGraphServer) { return new IntegrationGraphEndpoint(integrationGraphServer); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.java index b5c1c658be2..86008dd934f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.java @@ -63,8 +63,7 @@ import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class) public class DataSourceHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration - implements InitializingBean { + CompositeHealthIndicatorConfiguration implements InitializingBean { private final Collection metadataProviders; @@ -72,14 +71,12 @@ public class DataSourceHealthIndicatorAutoConfiguration extends public DataSourceHealthIndicatorAutoConfiguration(Map dataSources, ObjectProvider metadataProviders) { - this.metadataProviders = metadataProviders.orderedStream() - .collect(Collectors.toList()); + this.metadataProviders = metadataProviders.orderedStream().collect(Collectors.toList()); } @Override public void afterPropertiesSet() throws Exception { - this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider( - this.metadataProviders); + this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(this.metadataProviders); } @Bean @@ -88,8 +85,7 @@ public class DataSourceHealthIndicatorAutoConfiguration extends return createHealthIndicator(filterDataSources(dataSources)); } - private Map filterDataSources( - Map candidates) { + private Map filterDataSources(Map candidates) { if (candidates == null) { return null; } @@ -108,8 +104,7 @@ public class DataSourceHealthIndicatorAutoConfiguration extends } private String getValidationQuery(DataSource source) { - DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider - .getDataSourcePoolMetadata(source); + DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider.getDataSourcePoolMetadata(source); return (poolMetadata != null) ? poolMetadata.getValidationQuery() : null; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfiguration.java index 81f8ceb18b7..b65343973a5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfiguration.java @@ -48,13 +48,12 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnEnabledHealthIndicator("jms") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter({ ActiveMQAutoConfiguration.class, ArtemisAutoConfiguration.class }) -public class JmsHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class JmsHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "jmsHealthIndicator") - public HealthIndicator jmsHealthIndicator( - Map connectionFactories) { + public HealthIndicator jmsHealthIndicator(Map connectionFactories) { return createHealthIndicator(connectionFactories); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpoint.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpoint.java index 53d1d5b7da0..bdc668852b5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpoint.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpoint.java @@ -42,8 +42,7 @@ public class JolokiaEndpoint implements Supplier { @Override public EndpointServlet get() { - return new EndpointServlet(AgentServlet.class) - .withInitParameters(this.initParameters); + return new EndpointServlet(AgentServlet.class).withInitParameters(this.initParameters); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfiguration.java index bfc32687231..d494f401cb6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfiguration.java @@ -47,13 +47,12 @@ import org.springframework.ldap.core.LdapOperations; @ConditionalOnEnabledHealthIndicator("ldap") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(LdapAutoConfiguration.class) -public class LdapHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class LdapHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "ldapHealthIndicator") - public HealthIndicator ldapHealthIndicator( - Map ldapOperations) { + public HealthIndicator ldapHealthIndicator(Map ldapOperations) { return createHealthIndicator(ldapOperations); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java index e5fd4492940..671dc9b8b19 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java @@ -58,18 +58,15 @@ public class LiquibaseEndpointAutoConfiguration { return new BeanPostProcessor() { @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceClosingSpringLiquibase) { - ((DataSourceClosingSpringLiquibase) bean) - .setCloseDataSourceOnceMigrated(false); + ((DataSourceClosingSpringLiquibase) bean).setCloseDataSourceOnceMigrated(false); } return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfiguration.java index 02895532143..1efe2c026d8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfiguration.java @@ -48,8 +48,7 @@ public class LogFileWebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @Conditional(LogFileCondition.class) - public LogFileWebEndpoint logFileWebEndpoint(Environment environment, - LogFileWebEndpointProperties properties) { + public LogFileWebEndpoint logFileWebEndpoint(Environment environment, LogFileWebEndpointProperties properties) { return new LogFileWebEndpoint(environment, properties.getExternalFile()); } @@ -57,33 +56,25 @@ public class LogFileWebEndpointAutoConfiguration { @SuppressWarnings("deprecation") @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); - String config = getLogFileConfig(environment, LogFile.FILE_NAME_PROPERTY, - LogFile.FILE_PROPERTY); + String config = getLogFileConfig(environment, LogFile.FILE_NAME_PROPERTY, LogFile.FILE_PROPERTY); ConditionMessage.Builder message = ConditionMessage.forCondition("Log File"); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found(LogFile.FILE_NAME_PROPERTY).items(config)); + return ConditionOutcome.match(message.found(LogFile.FILE_NAME_PROPERTY).items(config)); } - config = getLogFileConfig(environment, LogFile.FILE_PATH_PROPERTY, - LogFile.PATH_PROPERTY); + config = getLogFileConfig(environment, LogFile.FILE_PATH_PROPERTY, LogFile.PATH_PROPERTY); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found(LogFile.FILE_PATH_PROPERTY).items(config)); + return ConditionOutcome.match(message.found(LogFile.FILE_PATH_PROPERTY).items(config)); } config = environment.getProperty("management.endpoint.logfile.external-file"); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found("management.endpoint.logfile.external-file") - .items(config)); + return ConditionOutcome.match(message.found("management.endpoint.logfile.external-file").items(config)); } return ConditionOutcome.noMatch(message.didNotFind("logging file").atAll()); } - private String getLogFileConfig(Environment environment, String configName, - String deprecatedConfigName) { + private String getLogFileConfig(Environment environment, String configName, String deprecatedConfigName) { String config = environment.resolvePlaceholders("${" + configName + ":}"); if (StringUtils.hasText(config)) { return config; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java index bd0bf70aff1..0b370d54959 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java @@ -52,14 +52,12 @@ public class LoggersEndpointAutoConfiguration { static class OnEnabledLoggingSystemCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Logging System"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Logging System"); String loggingSystem = System.getProperty(LoggingSystem.SYSTEM_PROPERTY); if (LoggingSystem.NONE.equals(loggingSystem)) { - return ConditionOutcome.noMatch(message.because("system property " - + LoggingSystem.SYSTEM_PROPERTY + " is set to none")); + return ConditionOutcome.noMatch( + message.because("system property " + LoggingSystem.SYSTEM_PROPERTY + " is set to none")); } return ConditionOutcome.match(message.because("enabled")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfiguration.java index 7d1fb8c6881..36f0a38a87a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfiguration.java @@ -46,13 +46,12 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; @ConditionalOnEnabledHealthIndicator("mail") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(MailSenderAutoConfiguration.class) -public class MailHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class MailHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "mailHealthIndicator") - public HealthIndicator mailHealthIndicator( - Map mailSenders) { + public HealthIndicator mailHealthIndicator(Map mailSenders) { return createHealthIndicator(mailSenders); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/AutoTimeProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/AutoTimeProperties.java index 0af123747a1..c8f1cc27041 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/AutoTimeProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/AutoTimeProperties.java @@ -69,8 +69,7 @@ public final class AutoTimeProperties implements AutoTimer { @Override public void apply(Builder builder) { - builder.publishPercentileHistogram(this.percentilesHistogram) - .publishPercentiles(this.percentiles); + builder.publishPercentileHistogram(this.percentilesHistogram).publishPercentiles(this.percentiles); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfiguration.java index c0899b37863..f9452356de9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfiguration.java @@ -31,8 +31,7 @@ import org.springframework.context.annotation.Import; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@Import({ NoOpMeterRegistryConfiguration.class, - CompositeMeterRegistryConfiguration.class }) +@Import({ NoOpMeterRegistryConfiguration.class, CompositeMeterRegistryConfiguration.class }) @ConditionalOnClass(CompositeMeterRegistry.class) public class CompositeMeterRegistryAutoConfiguration { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryConfiguration.java index 0fb47839ca5..c3bf00a3c51 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryConfiguration.java @@ -42,8 +42,7 @@ class CompositeMeterRegistryConfiguration { @Bean @Primary - public CompositeMeterRegistry compositeMeterRegistry(Clock clock, - List registries) { + public CompositeMeterRegistry compositeMeterRegistry(Clock clock, List registries) { return new CompositeMeterRegistry(clock, registries); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java index 1bbe00256f8..b70fb3deee4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java @@ -57,21 +57,19 @@ public class Log4J2MetricsAutoConfiguration { static class Log4JCoreLoggerContextCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { LoggerContext loggerContext = LogManager.getContext(false); try { - if (Class.forName("org.apache.logging.log4j.core.LoggerContext") - .isInstance(loggerContext)) { - return ConditionOutcome.match( - "LoggerContext was an instance of org.apache.logging.log4j.core.LoggerContext"); + if (Class.forName("org.apache.logging.log4j.core.LoggerContext").isInstance(loggerContext)) { + return ConditionOutcome + .match("LoggerContext was an instance of org.apache.logging.log4j.core.LoggerContext"); } } catch (Throwable ex) { // Continue with no match } - return ConditionOutcome.noMatch( - "Logger context was not an instance of org.apache.logging.log4j.core.LoggerContext"); + return ConditionOutcome + .noMatch("Logger context was not an instance of org.apache.logging.log4j.core.LoggerContext"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfiguration.java index 83bbbbe6b36..29402da029a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfiguration.java @@ -59,18 +59,14 @@ public class LogbackMetricsAutoConfiguration { static class LogbackLoggingCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); - ConditionMessage.Builder message = ConditionMessage - .forCondition("LogbackLoggingCondition"); + ConditionMessage.Builder message = ConditionMessage.forCondition("LogbackLoggingCondition"); if (loggerFactory instanceof LoggerContext) { - return ConditionOutcome.match( - message.because("ILoggerFactory is a Logback LoggerContext")); + return ConditionOutcome.match(message.because("ILoggerFactory is a Logback LoggerContext")); } - return ConditionOutcome - .noMatch(message.because("ILoggerFactory is an instance of " - + loggerFactory.getClass().getCanonicalName())); + return ConditionOutcome.noMatch( + message.because("ILoggerFactory is an instance of " + loggerFactory.getClass().getCanonicalName())); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java index 96752e02eb6..3cbe4a451db 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java @@ -48,9 +48,8 @@ class MeterRegistryConfigurer { private final boolean hasCompositeMeterRegistry; - MeterRegistryConfigurer(ObjectProvider> customizers, - ObjectProvider filters, ObjectProvider binders, - boolean addToGlobalRegistry, boolean hasCompositeMeterRegistry) { + MeterRegistryConfigurer(ObjectProvider> customizers, ObjectProvider filters, + ObjectProvider binders, boolean addToGlobalRegistry, boolean hasCompositeMeterRegistry) { this.customizers = customizers; this.filters = filters; this.binders = binders; @@ -63,8 +62,7 @@ class MeterRegistryConfigurer { // tags or alter timer or summary configuration. customize(registry); addFilters(registry); - if (!this.hasCompositeMeterRegistry - || registry instanceof CompositeMeterRegistry) { + if (!this.hasCompositeMeterRegistry || registry instanceof CompositeMeterRegistry) { addBinders(registry); } if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) { @@ -74,11 +72,8 @@ class MeterRegistryConfigurer { @SuppressWarnings("unchecked") private void customize(MeterRegistry registry) { - LambdaSafe - .callbacks(MeterRegistryCustomizer.class, asOrderedList(this.customizers), - registry) - .withLogger(MeterRegistryConfigurer.class) - .invoke((customizer) -> customizer.customize(registry)); + LambdaSafe.callbacks(MeterRegistryCustomizer.class, asOrderedList(this.customizers), registry) + .withLogger(MeterRegistryConfigurer.class).invoke((customizer) -> customizer.customize(registry)); } private void addFilters(MeterRegistry registry) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java index 6e491e30970..76561d9b51a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java @@ -48,11 +48,9 @@ class MeterRegistryPostProcessor implements BeanPostProcessor { private final ApplicationContext applicationContext; - MeterRegistryPostProcessor(ObjectProvider meterBinders, - ObjectProvider meterFilters, + MeterRegistryPostProcessor(ObjectProvider meterBinders, ObjectProvider meterFilters, ObjectProvider> meterRegistryCustomizers, - ObjectProvider metricsProperties, - ApplicationContext applicationContext) { + ObjectProvider metricsProperties, ApplicationContext applicationContext) { this.meterBinders = meterBinders; this.meterFilters = meterFilters; this.meterRegistryCustomizers = meterRegistryCustomizers; @@ -61,8 +59,7 @@ class MeterRegistryPostProcessor implements BeanPostProcessor { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof MeterRegistry) { getConfigurer().configure((MeterRegistry) bean); } @@ -72,11 +69,9 @@ class MeterRegistryPostProcessor implements BeanPostProcessor { private MeterRegistryConfigurer getConfigurer() { if (this.configurer == null) { boolean hasCompositeMeterRegistry = this.applicationContext - .getBeanNamesForType(CompositeMeterRegistry.class, false, - false).length != 0; - this.configurer = new MeterRegistryConfigurer(this.meterRegistryCustomizers, - this.meterFilters, this.meterBinders, - this.metricsProperties.getObject().isUseGlobalRegistry(), + .getBeanNamesForType(CompositeMeterRegistry.class, false, false).length != 0; + this.configurer = new MeterRegistryConfigurer(this.meterRegistryCustomizers, this.meterFilters, + this.meterBinders, this.metricsProperties.getObject().isUseGlobalRegistry(), hasCompositeMeterRegistry); } return this.configurer; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java index 87ee714045b..476b74e1355 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java @@ -52,14 +52,12 @@ public class MetricsAutoConfiguration { } @Bean - public static MeterRegistryPostProcessor meterRegistryPostProcessor( - ObjectProvider meterBinders, + public static MeterRegistryPostProcessor meterRegistryPostProcessor(ObjectProvider meterBinders, ObjectProvider meterFilters, ObjectProvider> meterRegistryCustomizers, - ObjectProvider metricsProperties, - ApplicationContext applicationContext) { - return new MeterRegistryPostProcessor(meterBinders, meterFilters, - meterRegistryCustomizers, metricsProperties, applicationContext); + ObjectProvider metricsProperties, ApplicationContext applicationContext) { + return new MeterRegistryPostProcessor(meterBinders, meterFilters, meterRegistryCustomizers, metricsProperties, + applicationContext); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.java index dc7035f71bc..3c55e1844fd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.java @@ -38,8 +38,7 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Timed.class) @ConditionalOnAvailableEndpoint(endpoint = MetricsEndpoint.class) -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - CompositeMeterRegistryAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class }) public class MetricsEndpointAutoConfiguration { @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsProperties.java index add171327a0..de701cd6bdf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsProperties.java @@ -116,8 +116,7 @@ public class MetricsProperties { * @deprecated since 2.2.0 in favor of {@link ClientRequest#getMetricName()} */ @Deprecated - @DeprecatedConfigurationProperty( - replacement = "management.metrics.web.client.request.metric-name") + @DeprecatedConfigurationProperty(replacement = "management.metrics.web.client.request.metric-name") public String getRequestsMetricName() { return this.request.getMetricName(); } @@ -190,8 +189,7 @@ public class MetricsProperties { * @return {@code true} if server request should be automatically timed * @deprecated since 2.2.0 in favor of {@link AutoTimeProperties#isEnabled()} */ - @DeprecatedConfigurationProperty( - replacement = "management.metrics.web.server.request.autotime.enabled") + @DeprecatedConfigurationProperty(replacement = "management.metrics.web.server.request.autotime.enabled") @Deprecated public boolean isAutoTimeRequests() { return this.request.getAutotime().isEnabled(); @@ -213,8 +211,7 @@ public class MetricsProperties { * @return request metric name * @deprecated since 2.2.0 in favor of {@link ServerRequest#getMetricName()} */ - @DeprecatedConfigurationProperty( - replacement = "management.metrics.web.server.request.metric-name") + @DeprecatedConfigurationProperty(replacement = "management.metrics.web.server.request.metric-name") @Deprecated public String getRequestsMetricName() { return this.request.getMetricName(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzer.java index 2e805947b75..597461dcd45 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ class MissingRequiredConfigurationFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - MissingRequiredConfigurationException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, MissingRequiredConfigurationException cause) { StringBuilder description = new StringBuilder(); description.append(cause.getMessage()); if (!cause.getMessage().endsWith(".")) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/OnlyOnceLoggingDenyMeterFilter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/OnlyOnceLoggingDenyMeterFilter.java index 6b16d1522db..92b4625aba7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/OnlyOnceLoggingDenyMeterFilter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/OnlyOnceLoggingDenyMeterFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.springframework.util.Assert; */ public final class OnlyOnceLoggingDenyMeterFilter implements MeterFilter { - private static final Log logger = LogFactory - .getLog(OnlyOnceLoggingDenyMeterFilter.class); + private static final Log logger = LogFactory.getLog(OnlyOnceLoggingDenyMeterFilter.class); private final AtomicBoolean alreadyWarned = new AtomicBoolean(false); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java index bfc9d4d12f8..bf50bb63cc4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,7 @@ public class PropertiesMeterFilter implements MeterFilter { return new MeterFilter() { }; } - Tags commonTags = Tags.of(tags.entrySet().stream() - .map((entry) -> Tag.of(entry.getKey(), entry.getValue())) + Tags commonTags = Tags.of(tags.entrySet().stream().map((entry) -> Tag.of(entry.getKey(), entry.getValue())) .collect(Collectors.toList())); return MeterFilter.commonTags(commonTags); } @@ -79,19 +78,16 @@ public class PropertiesMeterFilter implements MeterFilter { } @Override - public DistributionStatisticConfig configure(Meter.Id id, - DistributionStatisticConfig config) { + public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { Distribution distribution = this.properties.getDistribution(); return DistributionStatisticConfig.builder() - .percentilesHistogram(lookupWithFallbackToAll( - distribution.getPercentilesHistogram(), id, null)) - .percentiles( - lookupWithFallbackToAll(distribution.getPercentiles(), id, null)) + .percentilesHistogram(lookupWithFallbackToAll(distribution.getPercentilesHistogram(), id, null)) + .percentiles(lookupWithFallbackToAll(distribution.getPercentiles(), id, null)) .sla(convertSla(id.getType(), lookup(distribution.getSla(), id, null))) - .minimumExpectedValue(convertMeterValue(id.getType(), - lookup(distribution.getMinimumExpectedValue(), id, null))) - .maximumExpectedValue(convertMeterValue(id.getType(), - lookup(distribution.getMaximumExpectedValue(), id, null))) + .minimumExpectedValue( + convertMeterValue(id.getType(), lookup(distribution.getMinimumExpectedValue(), id, null))) + .maximumExpectedValue( + convertMeterValue(id.getType(), lookup(distribution.getMaximumExpectedValue(), id, null))) .build().merge(config); } @@ -99,9 +95,8 @@ public class PropertiesMeterFilter implements MeterFilter { if (sla == null) { return null; } - long[] converted = Arrays.stream(sla) - .map((candidate) -> candidate.getValue(meterType)) - .filter(Objects::nonNull).mapToLong(Long::longValue).toArray(); + long[] converted = Arrays.stream(sla).map((candidate) -> candidate.getValue(meterType)).filter(Objects::nonNull) + .mapToLong(Long::longValue).toArray(); return (converted.length != 0) ? converted : null; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java index 4770ca0c4c5..075ccfdd6e0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,19 +50,16 @@ class RabbitConnectionFactoryMetricsPostProcessor implements BeanPostProcessor, @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof AbstractConnectionFactory) { - bindConnectionFactoryToRegistry(getMeterRegistry(), beanName, - (AbstractConnectionFactory) bean); + bindConnectionFactoryToRegistry(getMeterRegistry(), beanName, (AbstractConnectionFactory) bean); } return bean; } private void bindConnectionFactoryToRegistry(MeterRegistry registry, String beanName, AbstractConnectionFactory connectionFactory) { - ConnectionFactory rabbitConnectionFactory = connectionFactory - .getRabbitConnectionFactory(); + ConnectionFactory rabbitConnectionFactory = connectionFactory.getRabbitConnectionFactory(); String connectionFactoryName = getConnectionFactoryName(beanName); - new RabbitMetrics(rabbitConnectionFactory, Tags.of("name", connectionFactoryName)) - .bindTo(registry); + new RabbitMetrics(rabbitConnectionFactory, Tags.of("name", connectionFactoryName)).bindTo(registry); } /** @@ -73,8 +70,7 @@ class RabbitConnectionFactoryMetricsPostProcessor implements BeanPostProcessor, private String getConnectionFactoryName(String beanName) { if (beanName.length() > CONNECTION_FACTORY_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, CONNECTION_FACTORY_SUFFIX)) { - return beanName.substring(0, - beanName.length() - CONNECTION_FACTORY_SUFFIX.length()); + return beanName.substring(0, beanName.length() - CONNECTION_FACTORY_SUFFIX.length()); } return beanName; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMeterBinderProvidersConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMeterBinderProvidersConfiguration.java index b837f40b9ef..e33aad63953 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMeterBinderProvidersConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMeterBinderProvidersConfiguration.java @@ -43,8 +43,7 @@ import org.springframework.context.annotation.Configuration; class CacheMeterBinderProvidersConfiguration { @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ CaffeineCache.class, - com.github.benmanes.caffeine.cache.Cache.class }) + @ConditionalOnClass({ CaffeineCache.class, com.github.benmanes.caffeine.cache.Cache.class }) static class CaffeineCacheMeterBinderProviderConfiguration { @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfiguration.java index b9bda2a60c0..4f40002f78d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfiguration.java @@ -36,8 +36,7 @@ import org.springframework.context.annotation.Import; @Configuration(proxyBeanMethods = false) @AutoConfigureAfter({ MetricsAutoConfiguration.class, CacheAutoConfiguration.class }) @ConditionalOnBean(CacheManager.class) -@Import({ CacheMeterBinderProvidersConfiguration.class, - CacheMetricsRegistrarConfiguration.class }) +@Import({ CacheMeterBinderProvidersConfiguration.class, CacheMetricsRegistrarConfiguration.class }) public class CacheMetricsAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java index 048eb4f116d..ab0b1f2734c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java @@ -51,13 +51,11 @@ class CacheMetricsRegistrarConfiguration { private final Map cacheManagers; - CacheMetricsRegistrarConfiguration(MeterRegistry registry, - Collection> binderProviders, + CacheMetricsRegistrarConfiguration(MeterRegistry registry, Collection> binderProviders, Map cacheManagers) { this.registry = registry; this.cacheManagers = cacheManagers; - this.cacheMetricsRegistrar = new CacheMetricsRegistrar(this.registry, - binderProviders); + this.cacheMetricsRegistrar = new CacheMetricsRegistrar(this.registry, binderProviders); } @Bean @@ -71,8 +69,8 @@ class CacheMetricsRegistrarConfiguration { } private void bindCacheManagerToRegistry(String beanName, CacheManager cacheManager) { - cacheManager.getCacheNames().forEach((cacheName) -> bindCacheToRegistry(beanName, - cacheManager.getCache(cacheName))); + cacheManager.getCacheNames() + .forEach((cacheName) -> bindCacheToRegistry(beanName, cacheManager.getCache(cacheName))); } private void bindCacheToRegistry(String beanName, Cache cache) { @@ -88,8 +86,7 @@ class CacheMetricsRegistrarConfiguration { private String getCacheManagerName(String beanName) { if (beanName.length() > CACHE_MANAGER_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, CACHE_MANAGER_SUFFIX)) { - return beanName.substring(0, - beanName.length() - CACHE_MANAGER_SUFFIX.length()); + return beanName.substring(0, beanName.length() - CACHE_MANAGER_SUFFIX.length()); } return beanName; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java index c264c68a2e3..c89429d32d6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java @@ -43,13 +43,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(AppOpticsMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.appoptics", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.appoptics", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(AppOpticsProperties.class) public class AppOpticsMetricsExportAutoConfiguration { @@ -67,12 +66,9 @@ public class AppOpticsMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public AppOpticsMeterRegistry appOpticsMeterRegistry(AppOpticsConfig config, - Clock clock) { - return AppOpticsMeterRegistry.builder(config).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + public AppOpticsMeterRegistry appOpticsMeterRegistry(AppOpticsConfig config, Clock clock) { + return AppOpticsMeterRegistry.builder(config).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapter.java index 47e7ac24adb..88ebb38e8f7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * * @author Stephane Nicoll */ -class AppOpticsPropertiesConfigAdapter - extends StepRegistryPropertiesConfigAdapter +class AppOpticsPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter implements AppOpticsConfig { AppOpticsPropertiesConfigAdapter(AppOpticsProperties properties) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfiguration.java index c8f7147fe45..42ad1b01c95 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfiguration.java @@ -42,13 +42,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(AtlasMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.atlas", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.atlas", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(AtlasProperties.class) public class AtlasMetricsExportAutoConfiguration { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapter.java index b7546e1a258..a79323f1174 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @author Phillip Webb */ -class AtlasPropertiesConfigAdapter extends PropertiesConfigAdapter - implements AtlasConfig { +class AtlasPropertiesConfigAdapter extends PropertiesConfigAdapter implements AtlasConfig { AtlasPropertiesConfigAdapter(AtlasProperties properties) { super(properties); @@ -87,8 +86,7 @@ class AtlasPropertiesConfigAdapter extends PropertiesConfigAdapter implements DatadogConfig { +class DatadogPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter + implements DatadogConfig { DatadogPropertiesConfigAdapter(DatadogProperties properties) { super(properties); @@ -40,8 +40,7 @@ class DatadogPropertiesConfigAdapter extends @Override public String applicationKey() { - return get(DatadogProperties::getApplicationKey, - DatadogConfig.super::applicationKey); + return get(DatadogProperties::getApplicationKey, DatadogConfig.super::applicationKey); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java index 16aede4a089..d8ba18d21c6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java @@ -43,13 +43,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(DynatraceMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.dynatrace", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.dynatrace", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(DynatraceProperties.class) public class DynatraceMetricsExportAutoConfiguration { @@ -67,12 +66,9 @@ public class DynatraceMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public DynatraceMeterRegistry dynatraceMeterRegistry(DynatraceConfig dynatraceConfig, - Clock clock) { - return DynatraceMeterRegistry.builder(dynatraceConfig).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + public DynatraceMeterRegistry dynatraceMeterRegistry(DynatraceConfig dynatraceConfig, Clock clock) { + return DynatraceMeterRegistry.builder(dynatraceConfig).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapter.java index d10ff615214..f097e6ddad2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapter.java @@ -25,8 +25,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * * @author Andy Wilkinson */ -class DynatracePropertiesConfigAdapter - extends StepRegistryPropertiesConfigAdapter +class DynatracePropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter implements DynatraceConfig { DynatracePropertiesConfigAdapter(DynatraceProperties properties) { @@ -45,8 +44,7 @@ class DynatracePropertiesConfigAdapter @Override public String technologyType() { - return get(DynatraceProperties::getTechnologyType, - DynatraceConfig.super::technologyType); + return get(DynatraceProperties::getTechnologyType, DynatraceConfig.super::technologyType); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java index 71718396c8b..1c90122ece4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java @@ -43,13 +43,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(ElasticMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.elastic", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.elastic", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(ElasticProperties.class) public class ElasticMetricsExportAutoConfiguration { @@ -67,12 +66,9 @@ public class ElasticMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public ElasticMeterRegistry elasticMeterRegistry(ElasticConfig elasticConfig, - Clock clock) { - return ElasticMeterRegistry.builder(elasticConfig).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + public ElasticMeterRegistry elasticMeterRegistry(ElasticConfig elasticConfig, Clock clock) { + return ElasticMeterRegistry.builder(elasticConfig).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapter.java index 8b2a26b8036..8d41ebe2523 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * * @author Andy Wilkinson */ -class ElasticPropertiesConfigAdapter extends - StepRegistryPropertiesConfigAdapter implements ElasticConfig { +class ElasticPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter + implements ElasticConfig { ElasticPropertiesConfigAdapter(ElasticProperties properties) { super(properties); @@ -44,20 +44,17 @@ class ElasticPropertiesConfigAdapter extends @Override public String indexDateFormat() { - return get(ElasticProperties::getIndexDateFormat, - ElasticConfig.super::indexDateFormat); + return get(ElasticProperties::getIndexDateFormat, ElasticConfig.super::indexDateFormat); } @Override public String timestampFieldName() { - return get(ElasticProperties::getTimestampFieldName, - ElasticConfig.super::timestampFieldName); + return get(ElasticProperties::getTimestampFieldName, ElasticConfig.super::timestampFieldName); } @Override public boolean autoCreateIndex() { - return get(ElasticProperties::isAutoCreateIndex, - ElasticConfig.super::autoCreateIndex); + return get(ElasticProperties::isAutoCreateIndex, ElasticConfig.super::autoCreateIndex); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.java index 3a50cf905f6..1dca5c5705f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.java @@ -41,13 +41,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(GangliaMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.ganglia", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.ganglia", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(GangliaProperties.class) public class GangliaMetricsExportAutoConfiguration { @@ -59,8 +58,7 @@ public class GangliaMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public GangliaMeterRegistry gangliaMeterRegistry(GangliaConfig gangliaConfig, - Clock clock) { + public GangliaMeterRegistry gangliaMeterRegistry(GangliaConfig gangliaConfig, Clock clock) { return new GangliaMeterRegistry(gangliaConfig, clock); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapter.java index 0e1a25d02aa..4ce050bd912 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @author Phillip Webb */ -class GangliaPropertiesConfigAdapter extends PropertiesConfigAdapter - implements GangliaConfig { +class GangliaPropertiesConfigAdapter extends PropertiesConfigAdapter implements GangliaConfig { GangliaPropertiesConfigAdapter(GangliaProperties properties) { super(properties); @@ -59,20 +58,17 @@ class GangliaPropertiesConfigAdapter extends PropertiesConfigAdapter - implements GraphiteConfig { +class GraphitePropertiesConfigAdapter extends PropertiesConfigAdapter implements GraphiteConfig { GraphitePropertiesConfigAdapter(GraphiteProperties properties) { super(properties); @@ -59,8 +58,7 @@ class GraphitePropertiesConfigAdapter extends PropertiesConfigAdapter implements HumioConfig { +class HumioPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter implements HumioConfig { HumioPropertiesConfigAdapter(HumioProperties properties) { super(properties); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java index c5f96f098b7..21d91189074 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java @@ -43,13 +43,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(InfluxMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.influx", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.influx", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(InfluxProperties.class) public class InfluxMetricsExportAutoConfiguration { @@ -69,10 +68,8 @@ public class InfluxMetricsExportAutoConfiguration { @ConditionalOnMissingBean public InfluxMeterRegistry influxMeterRegistry(InfluxConfig influxConfig, Clock clock, InfluxProperties influxProperties) { - return InfluxMeterRegistry.builder(influxConfig).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + return InfluxMeterRegistry.builder(influxConfig).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesConfigAdapter.java index 7d0320f14ee..ecff99f822c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @author Phillip Webb */ -class InfluxPropertiesConfigAdapter extends - StepRegistryPropertiesConfigAdapter implements InfluxConfig { +class InfluxPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter + implements InfluxConfig { InfluxPropertiesConfigAdapter(InfluxProperties properties) { super(properties); @@ -56,26 +56,22 @@ class InfluxPropertiesConfigAdapter extends @Override public String retentionPolicy() { - return get(InfluxProperties::getRetentionPolicy, - InfluxConfig.super::retentionPolicy); + return get(InfluxProperties::getRetentionPolicy, InfluxConfig.super::retentionPolicy); } @Override public Integer retentionReplicationFactor() { - return get(InfluxProperties::getRetentionReplicationFactor, - InfluxConfig.super::retentionReplicationFactor); + return get(InfluxProperties::getRetentionReplicationFactor, InfluxConfig.super::retentionReplicationFactor); } @Override public String retentionDuration() { - return get(InfluxProperties::getRetentionDuration, - InfluxConfig.super::retentionDuration); + return get(InfluxProperties::getRetentionDuration, InfluxConfig.super::retentionDuration); } @Override public String retentionShardDuration() { - return get(InfluxProperties::getRetentionShardDuration, - InfluxConfig.super::retentionShardDuration); + return get(InfluxProperties::getRetentionShardDuration, InfluxConfig.super::retentionShardDuration); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfiguration.java index ec12050a981..eef339e00f1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfiguration.java @@ -41,13 +41,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(JmxMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.jmx", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.jmx", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(JmxProperties.class) public class JmxMetricsExportAutoConfiguration { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesConfigAdapter.java index 42554326227..a38d98135f9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @author Stephane Nicoll */ -class JmxPropertiesConfigAdapter extends PropertiesConfigAdapter - implements JmxConfig { +class JmxPropertiesConfigAdapter extends PropertiesConfigAdapter implements JmxConfig { JmxPropertiesConfigAdapter(JmxProperties properties) { super(properties); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java index 3ecbce56803..3e9430ae6ca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java @@ -43,13 +43,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(KairosMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.kairos", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.kairos", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(KairosProperties.class) public class KairosMetricsExportAutoConfiguration { @@ -67,12 +66,9 @@ public class KairosMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public KairosMeterRegistry kairosMeterRegistry(KairosConfig kairosConfig, - Clock clock) { - return KairosMeterRegistry.builder(kairosConfig).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + public KairosMeterRegistry kairosMeterRegistry(KairosConfig kairosConfig, Clock clock) { + return KairosMeterRegistry.builder(kairosConfig).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapter.java index e14c71cfaf1..1b753108d06 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * * @author Stephane Nicoll */ -class KairosPropertiesConfigAdapter extends - StepRegistryPropertiesConfigAdapter implements KairosConfig { +class KairosPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter + implements KairosConfig { KairosPropertiesConfigAdapter(KairosProperties properties) { super(properties); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java index 8f416ca0b26..a666810ef22 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java @@ -44,13 +44,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(NewRelicMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.newrelic", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.newrelic", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(NewRelicProperties.class) public class NewRelicMetricsExportAutoConfiguration { @@ -68,12 +67,9 @@ public class NewRelicMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, - Clock clock) { - return NewRelicMeterRegistry.builder(newRelicConfig).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, Clock clock) { + return NewRelicMeterRegistry.builder(newRelicConfig).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesConfigAdapter.java index 6f814d50bc8..55f03a12d16 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @since 2.0.0 */ -public class NewRelicPropertiesConfigAdapter - extends StepRegistryPropertiesConfigAdapter +public class NewRelicPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter implements NewRelicConfig { public NewRelicPropertiesConfigAdapter(NewRelicProperties properties) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java index 2b97e543ca8..b6d18db0dcf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java @@ -57,13 +57,12 @@ import org.springframework.core.log.LogMessage; * @author David J. M. Karlsen */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(PrometheusMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.prometheus", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.prometheus", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(PrometheusProperties.class) public class PrometheusMetricsExportAutoConfiguration { @@ -75,9 +74,8 @@ public class PrometheusMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public PrometheusMeterRegistry prometheusMeterRegistry( - PrometheusConfig prometheusConfig, CollectorRegistry collectorRegistry, - Clock clock) { + public PrometheusMeterRegistry prometheusMeterRegistry(PrometheusConfig prometheusConfig, + CollectorRegistry collectorRegistry, Clock clock) { return new PrometheusMeterRegistry(prometheusConfig, collectorRegistry, clock); } @@ -93,8 +91,7 @@ public class PrometheusMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public PrometheusScrapeEndpoint prometheusEndpoint( - CollectorRegistry collectorRegistry) { + public PrometheusScrapeEndpoint prometheusEndpoint(CollectorRegistry collectorRegistry) { return new PrometheusScrapeEndpoint(collectorRegistry); } @@ -106,12 +103,10 @@ public class PrometheusMetricsExportAutoConfiguration { */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(PushGateway.class) - @ConditionalOnProperty(prefix = "management.metrics.export.prometheus.pushgateway", - name = "enabled") + @ConditionalOnProperty(prefix = "management.metrics.export.prometheus.pushgateway", name = "enabled") public static class PrometheusPushGatewayConfiguration { - private static final Log logger = LogFactory - .getLog(PrometheusPushGatewayConfiguration.class); + private static final Log logger = LogFactory.getLog(PrometheusPushGatewayConfiguration.class); /** * The fallback job name. We use 'spring' since there's a history of Prometheus @@ -122,18 +117,15 @@ public class PrometheusMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public PrometheusPushGatewayManager prometheusPushGatewayManager( - CollectorRegistry collectorRegistry, + public PrometheusPushGatewayManager prometheusPushGatewayManager(CollectorRegistry collectorRegistry, PrometheusProperties prometheusProperties, Environment environment) { - PrometheusProperties.Pushgateway properties = prometheusProperties - .getPushgateway(); + PrometheusProperties.Pushgateway properties = prometheusProperties.getPushgateway(); Duration pushRate = properties.getPushRate(); String job = getJob(properties, environment); Map groupingKey = properties.getGroupingKey(); ShutdownOperation shutdownOperation = properties.getShutdownOperation(); - return new PrometheusPushGatewayManager( - getPushGateway(properties.getBaseUrl()), collectorRegistry, pushRate, - job, groupingKey, shutdownOperation); + return new PrometheusPushGatewayManager(getPushGateway(properties.getBaseUrl()), collectorRegistry, + pushRate, job, groupingKey, shutdownOperation); } private PushGateway getPushGateway(String url) { @@ -141,18 +133,15 @@ public class PrometheusMetricsExportAutoConfiguration { return new PushGateway(new URL(url)); } catch (MalformedURLException ex) { - logger.warn(LogMessage.format( - "Invalid PushGateway base url '%s': update your configuration to a valid URL", - url)); + logger.warn(LogMessage + .format("Invalid PushGateway base url '%s': update your configuration to a valid URL", url)); return new PushGateway(url); } } - private String getJob(PrometheusProperties.Pushgateway properties, - Environment environment) { + private String getJob(PrometheusProperties.Pushgateway properties, Environment environment) { String job = properties.getJob(); - job = (job != null) ? job - : environment.getProperty("spring.application.name"); + job = (job != null) ? job : environment.getProperty("spring.application.name"); return (job != null) ? job : FALLBACK_JOB; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapter.java index 33d92f2ce75..0a4ff1204e8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @author Phillip Webb */ -class PrometheusPropertiesConfigAdapter extends - PropertiesConfigAdapter implements PrometheusConfig { +class PrometheusPropertiesConfigAdapter extends PropertiesConfigAdapter + implements PrometheusConfig { PrometheusPropertiesConfigAdapter(PrometheusProperties properties) { super(properties); @@ -42,8 +42,7 @@ class PrometheusPropertiesConfigAdapter extends @Override public boolean descriptions() { - return get(PrometheusProperties::isDescriptions, - PrometheusConfig.super::descriptions); + return get(PrometheusProperties::isDescriptions, PrometheusConfig.super::descriptions); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfiguration.java index 015f919a438..abedae96d86 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfiguration.java @@ -42,13 +42,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(SignalFxMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.signalfx", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.signalfx", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(SignalFxProperties.class) public class SignalFxMetricsExportAutoConfiguration { @@ -60,8 +59,7 @@ public class SignalFxMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public SignalFxMeterRegistry signalFxMeterRegistry(SignalFxConfig config, - Clock clock) { + public SignalFxMeterRegistry signalFxMeterRegistry(SignalFxConfig config, Clock clock) { return new SignalFxMeterRegistry(config, clock); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesConfigAdapter.java index 12d048dd652..379f7793e70 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @since 2.0.0 */ -public class SignalFxPropertiesConfigAdapter - extends StepRegistryPropertiesConfigAdapter +public class SignalFxPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter implements SignalFxConfig { public SignalFxPropertiesConfigAdapter(SignalFxProperties properties) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfiguration.java index 57e4cd38db6..e4075d4dc82 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfiguration.java @@ -47,8 +47,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnBean(Clock.class) @EnableConfigurationProperties(SimpleProperties.class) @ConditionalOnMissingBean(MeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.simple", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.simple", name = "enabled", havingValue = "true", + matchIfMissing = true) public class SimpleMetricsExportAutoConfiguration { @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesConfigAdapter.java index 1c726c0b4e6..498a387ff54 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @since 2.0.0 */ -public class SimplePropertiesConfigAdapter - extends PropertiesConfigAdapter implements SimpleConfig { +public class SimplePropertiesConfigAdapter extends PropertiesConfigAdapter implements SimpleConfig { public SimplePropertiesConfigAdapter(SimpleProperties properties) { super(properties); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfiguration.java index 9928ad6236b..b692e032f68 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfiguration.java @@ -42,13 +42,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(StatsdMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.statsd", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.statsd", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(StatsdProperties.class) public class StatsdMetricsExportAutoConfiguration { @@ -60,8 +59,7 @@ public class StatsdMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public StatsdMeterRegistry statsdMeterRegistry(StatsdConfig statsdConfig, - Clock clock) { + public StatsdMeterRegistry statsdMeterRegistry(StatsdConfig statsdConfig, Clock clock) { return new StatsdMeterRegistry(statsdConfig, clock); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapter.java index 41808be32c5..aa764b3a93c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @since 2.0.0 */ -public class StatsdPropertiesConfigAdapter - extends PropertiesConfigAdapter implements StatsdConfig { +public class StatsdPropertiesConfigAdapter extends PropertiesConfigAdapter implements StatsdConfig { public StatsdPropertiesConfigAdapter(StatsdProperties properties) { super(properties); @@ -63,20 +62,17 @@ public class StatsdPropertiesConfigAdapter @Override public int maxPacketLength() { - return get(StatsdProperties::getMaxPacketLength, - StatsdConfig.super::maxPacketLength); + return get(StatsdProperties::getMaxPacketLength, StatsdConfig.super::maxPacketLength); } @Override public Duration pollingFrequency() { - return get(StatsdProperties::getPollingFrequency, - StatsdConfig.super::pollingFrequency); + return get(StatsdProperties::getPollingFrequency, StatsdConfig.super::pollingFrequency); } @Override public boolean publishUnchangedMeters() { - return get(StatsdProperties::isPublishUnchangedMeters, - StatsdConfig.super::publishUnchangedMeters); + return get(StatsdProperties::isPublishUnchangedMeters, StatsdConfig.super::publishUnchangedMeters); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfiguration.java index e033bfeb7cd..3137dc2ed6a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfiguration.java @@ -43,13 +43,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(WavefrontMeterRegistry.class) -@ConditionalOnProperty(prefix = "management.metrics.export.wavefront", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.metrics.export.wavefront", name = "enabled", havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(WavefrontProperties.class) public class WavefrontMetricsExportAutoConfiguration { @@ -67,12 +66,9 @@ public class WavefrontMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public WavefrontMeterRegistry wavefrontMeterRegistry(WavefrontConfig wavefrontConfig, - Clock clock) { - return WavefrontMeterRegistry.builder(wavefrontConfig).clock(clock) - .httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), - this.properties.getReadTimeout())) + public WavefrontMeterRegistry wavefrontMeterRegistry(WavefrontConfig wavefrontConfig, Clock clock) { + return WavefrontMeterRegistry.builder(wavefrontConfig).clock(clock).httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapter.java index 3f96683f07a..d7b0221a345 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties. * @author Jon Schneider * @since 2.0.0 */ -public class WavefrontPropertiesConfigAdapter - extends StepRegistryPropertiesConfigAdapter +public class WavefrontPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter implements WavefrontConfig { public WavefrontPropertiesConfigAdapter(WavefrontProperties properties) { @@ -56,8 +55,7 @@ public class WavefrontPropertiesConfigAdapter @Override public String globalPrefix() { - return get(WavefrontProperties::getGlobalPrefix, - WavefrontConfig.super::globalPrefix); + return get(WavefrontProperties::getGlobalPrefix, WavefrontConfig.super::globalPrefix); } private String getUriAsString(WavefrontProperties properties) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java index 8bee39e8422..d240a3455e8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java @@ -66,21 +66,19 @@ public class DataSourcePoolMetricsAutoConfiguration { private static final String DATASOURCE_SUFFIX = "dataSource"; @Autowired - public void bindDataSourcesToRegistry(Map dataSources, - MeterRegistry registry, + public void bindDataSourcesToRegistry(Map dataSources, MeterRegistry registry, ObjectProvider metadataProviders) { - List metadataProvidersList = metadataProviders - .stream().collect(Collectors.toList()); - dataSources.forEach((name, dataSource) -> bindDataSourceToRegistry(name, - dataSource, metadataProvidersList, registry)); + List metadataProvidersList = metadataProviders.stream() + .collect(Collectors.toList()); + dataSources.forEach( + (name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); } private void bindDataSourceToRegistry(String beanName, DataSource dataSource, - Collection metadataProviders, - MeterRegistry registry) { + Collection metadataProviders, MeterRegistry registry) { String dataSourceName = getDataSourceName(beanName); - new DataSourcePoolMetrics(dataSource, metadataProviders, dataSourceName, - Collections.emptyList()).bindTo(registry); + new DataSourcePoolMetrics(dataSource, metadataProviders, dataSourceName, Collections.emptyList()) + .bindTo(registry); } /** @@ -91,8 +89,7 @@ public class DataSourcePoolMetricsAutoConfiguration { private String getDataSourceName(String beanName) { if (beanName.length() > DATASOURCE_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, DATASOURCE_SUFFIX)) { - return beanName.substring(0, - beanName.length() - DATASOURCE_SUFFIX.length()); + return beanName.substring(0, beanName.length() - DATASOURCE_SUFFIX.length()); } return beanName; } @@ -103,8 +100,7 @@ public class DataSourcePoolMetricsAutoConfiguration { @ConditionalOnClass(HikariDataSource.class) static class HikariDataSourceMetricsConfiguration { - private static final Log logger = LogFactory - .getLog(HikariDataSourceMetricsConfiguration.class); + private static final Log logger = LogFactory.getLog(HikariDataSourceMetricsConfiguration.class); private final MeterRegistry registry; @@ -113,11 +109,9 @@ public class DataSourcePoolMetricsAutoConfiguration { } @Autowired - public void bindMetricsRegistryToHikariDataSources( - Collection dataSources) { + public void bindMetricsRegistryToHikariDataSources(Collection dataSources) { for (DataSource dataSource : dataSources) { - HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, - HikariDataSource.class); + HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class); if (hikariDataSource != null) { bindMetricsRegistryToHikariDataSource(hikariDataSource); } @@ -125,11 +119,9 @@ public class DataSourcePoolMetricsAutoConfiguration { } private void bindMetricsRegistryToHikariDataSource(HikariDataSource hikari) { - if (hikari.getMetricRegistry() == null - && hikari.getMetricsTrackerFactory() == null) { + if (hikari.getMetricRegistry() == null && hikari.getMetricsTrackerFactory() == null) { try { - hikari.setMetricsTrackerFactory( - new MicrometerMetricsTrackerFactory(this.registry)); + hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry)); } catch (Exception ex) { logger.warn("Failed to bind Hikari metrics: " + ex.getMessage()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfiguration.java index d657e0a5d09..22efda9b4d3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfiguration.java @@ -54,8 +54,7 @@ import org.springframework.core.annotation.Order; * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass({ ResourceConfig.class, MetricsApplicationEventListener.class }) @ConditionalOnBean({ MeterRegistry.class, ResourceConfig.class }) @@ -75,24 +74,22 @@ public class JerseyServerMetricsAutoConfiguration { } @Bean - public ResourceConfigCustomizer jerseyServerMetricsResourceConfigCustomizer( - MeterRegistry meterRegistry, JerseyTagsProvider tagsProvider) { + public ResourceConfigCustomizer jerseyServerMetricsResourceConfigCustomizer(MeterRegistry meterRegistry, + JerseyTagsProvider tagsProvider) { Server server = this.properties.getWeb().getServer(); - return (config) -> config.register(new MetricsApplicationEventListener( - meterRegistry, tagsProvider, server.getRequest().getMetricName(), - server.getRequest().getAutotime().isEnabled(), - new AnnotationUtilsAnnotationFinder())); + return (config) -> config.register( + new MetricsApplicationEventListener(meterRegistry, tagsProvider, server.getRequest().getMetricName(), + server.getRequest().getAutotime().isEnabled(), new AnnotationUtilsAnnotationFinder())); } @Bean @Order(0) public MeterFilter jerseyMetricsUriTagFilter() { - String metricName = this.properties.getWeb().getServer().getRequest() - .getMetricName(); - MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter(() -> String - .format("Reached the maximum number of URI tags for '%s'.", metricName)); - return MeterFilter.maximumAllowableTags(metricName, "uri", - this.properties.getWeb().getServer().getMaxUriTags(), filter); + String metricName = this.properties.getWeb().getServer().getRequest().getMetricName(); + MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter( + () -> String.format("Reached the maximum number of URI tags for '%s'.", metricName)); + return MeterFilter.maximumAllowableTags(metricName, "uri", this.properties.getWeb().getServer().getMaxUriTags(), + filter); } /** @@ -101,8 +98,7 @@ public class JerseyServerMetricsAutoConfiguration { private static class AnnotationUtilsAnnotationFinder implements AnnotationFinder { @Override - public A findAnnotation(AnnotatedElement annotatedElement, - Class annotationType) { + public A findAnnotation(AnnotatedElement annotatedElement, Class annotationType) { return AnnotationUtils.findAnnotation(annotatedElement, annotationType); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java index 20465aeb458..fa111f2b21c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java @@ -48,27 +48,24 @@ import org.springframework.util.StringUtils; @Configuration(proxyBeanMethods = false) @AutoConfigureAfter({ MetricsAutoConfiguration.class, HibernateJpaAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) -@ConditionalOnClass({ EntityManagerFactory.class, SessionFactory.class, - MeterRegistry.class }) +@ConditionalOnClass({ EntityManagerFactory.class, SessionFactory.class, MeterRegistry.class }) @ConditionalOnBean({ EntityManagerFactory.class, MeterRegistry.class }) public class HibernateMetricsAutoConfiguration { private static final String ENTITY_MANAGER_FACTORY_SUFFIX = "entityManagerFactory"; @Autowired - public void bindEntityManagerFactoriesToRegistry( - Map entityManagerFactories, + public void bindEntityManagerFactoriesToRegistry(Map entityManagerFactories, MeterRegistry registry) { - entityManagerFactories.forEach((name, - factory) -> bindEntityManagerFactoryToRegistry(name, factory, registry)); + entityManagerFactories.forEach((name, factory) -> bindEntityManagerFactoryToRegistry(name, factory, registry)); } - private void bindEntityManagerFactoryToRegistry(String beanName, - EntityManagerFactory entityManagerFactory, MeterRegistry registry) { + private void bindEntityManagerFactoryToRegistry(String beanName, EntityManagerFactory entityManagerFactory, + MeterRegistry registry) { String entityManagerFactoryName = getEntityManagerFactoryName(beanName); try { - new HibernateMetrics(entityManagerFactory.unwrap(SessionFactory.class), - entityManagerFactoryName, Collections.emptyList()).bindTo(registry); + new HibernateMetrics(entityManagerFactory.unwrap(SessionFactory.class), entityManagerFactoryName, + Collections.emptyList()).bindTo(registry); } catch (PersistenceException ex) { // Continue @@ -81,10 +78,9 @@ public class HibernateMetricsAutoConfiguration { * @return a name for the given entity manager factory */ private String getEntityManagerFactoryName(String beanName) { - if (beanName.length() > ENTITY_MANAGER_FACTORY_SUFFIX.length() && StringUtils - .endsWithIgnoreCase(beanName, ENTITY_MANAGER_FACTORY_SUFFIX)) { - return beanName.substring(0, - beanName.length() - ENTITY_MANAGER_FACTORY_SUFFIX.length()); + if (beanName.length() > ENTITY_MANAGER_FACTORY_SUFFIX.length() + && StringUtils.endsWithIgnoreCase(beanName, ENTITY_MANAGER_FACTORY_SUFFIX)) { + return beanName.substring(0, beanName.length() - ENTITY_MANAGER_FACTORY_SUFFIX.length()); } return beanName; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java index 6fdb0a8ad0b..4742306534c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java @@ -43,8 +43,8 @@ import org.springframework.core.annotation.Order; * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, RestTemplateAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class, + RestTemplateAutoConfiguration.class }) @ConditionalOnClass(MeterRegistry.class) @ConditionalOnBean(MeterRegistry.class) @Import({ RestTemplateMetricsConfiguration.class, WebClientMetricsConfiguration.class }) @@ -54,11 +54,10 @@ public class HttpClientMetricsAutoConfiguration { @Order(0) public MeterFilter metricsHttpClientUriTagFilter(MetricsProperties properties) { String metricName = properties.getWeb().getClient().getRequest().getMetricName(); - MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter(() -> String - .format("Reached the maximum number of URI tags for '%s'. Are you using " - + "'uriVariables'?", metricName)); - return MeterFilter.maximumAllowableTags(metricName, "uri", - properties.getWeb().getClient().getMaxUriTags(), denyFilter); + MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter(() -> String.format( + "Reached the maximum number of URI tags for '%s'. Are you using " + "'uriVariables'?", metricName)); + return MeterFilter.maximumAllowableTags(metricName, "uri", properties.getWeb().getClient().getMaxUriTags(), + denyFilter); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfiguration.java index 037fe32b8f3..83872865661 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfiguration.java @@ -50,14 +50,11 @@ class RestTemplateMetricsConfiguration { } @Bean - public MetricsRestTemplateCustomizer metricsRestTemplateCustomizer( - MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider restTemplateExchangeTagsProvider, - MetricsProperties properties) { + public MetricsRestTemplateCustomizer metricsRestTemplateCustomizer(MeterRegistry meterRegistry, + RestTemplateExchangeTagsProvider restTemplateExchangeTagsProvider, MetricsProperties properties) { ClientRequest request = properties.getWeb().getClient().getRequest(); - return new MetricsRestTemplateCustomizer(meterRegistry, - restTemplateExchangeTagsProvider, request.getMetricName(), - request.getAutotime()); + return new MetricsRestTemplateCustomizer(meterRegistry, restTemplateExchangeTagsProvider, + request.getMetricName(), request.getAutotime()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfiguration.java index 689772f0e0b..bbb527d7c00 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfiguration.java @@ -46,12 +46,11 @@ class WebClientMetricsConfiguration { } @Bean - public MetricsWebClientCustomizer metricsWebClientCustomizer( - MeterRegistry meterRegistry, WebClientExchangeTagsProvider tagsProvider, - MetricsProperties properties) { + public MetricsWebClientCustomizer metricsWebClientCustomizer(MeterRegistry meterRegistry, + WebClientExchangeTagsProvider tagsProvider, MetricsProperties properties) { ClientRequest request = properties.getWeb().getClient().getRequest(); - return new MetricsWebClientCustomizer(meterRegistry, tagsProvider, - request.getMetricName(), request.getAutotime()); + return new MetricsWebClientCustomizer(meterRegistry, tagsProvider, request.getMetricName(), + request.getAutotime()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfiguration.java index d5337d205f7..474636736e1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfiguration.java @@ -42,10 +42,8 @@ public class JettyMetricsAutoConfiguration { @Bean @ConditionalOnBean(MeterRegistry.class) - @ConditionalOnMissingBean({ JettyServerThreadPoolMetrics.class, - JettyServerThreadPoolMetricsBinder.class }) - public JettyServerThreadPoolMetricsBinder jettyServerThreadPoolMetricsBinder( - MeterRegistry meterRegistry) { + @ConditionalOnMissingBean({ JettyServerThreadPoolMetrics.class, JettyServerThreadPoolMetricsBinder.class }) + public JettyServerThreadPoolMetricsBinder jettyServerThreadPoolMetricsBinder(MeterRegistry meterRegistry) { return new JettyServerThreadPoolMetricsBinder(meterRegistry); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfiguration.java index fc9327ee325..670e896d162 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfiguration.java @@ -45,8 +45,7 @@ import org.springframework.core.annotation.Order; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @ConditionalOnBean(MeterRegistry.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) public class WebFluxMetricsAutoConfiguration { @@ -64,22 +63,19 @@ public class WebFluxMetricsAutoConfiguration { } @Bean - public MetricsWebFilter webfluxMetrics(MeterRegistry registry, - WebFluxTagsProvider tagConfigurer) { + public MetricsWebFilter webfluxMetrics(MeterRegistry registry, WebFluxTagsProvider tagConfigurer) { ServerRequest request = this.properties.getWeb().getServer().getRequest(); - return new MetricsWebFilter(registry, tagConfigurer, request.getMetricName(), - request.getAutotime()); + return new MetricsWebFilter(registry, tagConfigurer, request.getMetricName(), request.getAutotime()); } @Bean @Order(0) public MeterFilter metricsHttpServerUriTagFilter() { - String metricName = this.properties.getWeb().getServer().getRequest() - .getMetricName(); - MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter(() -> String - .format("Reached the maximum number of URI tags for '%s'.", metricName)); - return MeterFilter.maximumAllowableTags(metricName, "uri", - this.properties.getWeb().getServer().getMaxUriTags(), filter); + String metricName = this.properties.getWeb().getServer().getRequest().getMetricName(); + MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter( + () -> String.format("Reached the maximum number of URI tags for '%s'.", metricName)); + return MeterFilter.maximumAllowableTags(metricName, "uri", this.properties.getWeb().getServer().getMaxUriTags(), + filter); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.java index 7f20381eadd..7b81bf89729 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.java @@ -55,8 +55,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @ConditionalOnBean(MeterRegistry.class) @@ -76,13 +75,12 @@ public class WebMvcMetricsAutoConfiguration { } @Bean - public FilterRegistrationBean webMvcMetricsFilter( - MeterRegistry registry, WebMvcTagsProvider tagsProvider) { + public FilterRegistrationBean webMvcMetricsFilter(MeterRegistry registry, + WebMvcTagsProvider tagsProvider) { ServerRequest request = this.properties.getWeb().getServer().getRequest(); - WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, - request.getMetricName(), request.getAutotime()); - FilterRegistrationBean registration = new FilterRegistrationBean<>( - filter); + WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, request.getMetricName(), + request.getAutotime()); + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC); return registration; @@ -91,12 +89,11 @@ public class WebMvcMetricsAutoConfiguration { @Bean @Order(0) public MeterFilter metricsHttpServerUriTagFilter() { - String metricName = this.properties.getWeb().getServer().getRequest() - .getMetricName(); - MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter(() -> String - .format("Reached the maximum number of URI tags for '%s'.", metricName)); - return MeterFilter.maximumAllowableTags(metricName, "uri", - this.properties.getWeb().getServer().getMaxUriTags(), filter); + String metricName = this.properties.getWeb().getServer().getRequest().getMetricName(); + MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter( + () -> String.format("Reached the maximum number of URI tags for '%s'.", metricName)); + return MeterFilter.maximumAllowableTags(metricName, "uri", this.properties.getWeb().getServer().getMaxUriTags(), + filter); } @Bean @@ -114,16 +111,14 @@ public class WebMvcMetricsAutoConfiguration { private final WebMvcTagsProvider tagsProvider; - MetricsWebMvcConfigurer(MeterRegistry meterRegistry, - WebMvcTagsProvider tagsProvider) { + MetricsWebMvcConfigurer(MeterRegistry meterRegistry, WebMvcTagsProvider tagsProvider) { this.meterRegistry = meterRegistry; this.tagsProvider = tagsProvider; } @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new LongTaskTimingHandlerInterceptor( - this.meterRegistry, this.tagsProvider)); + registry.addInterceptor(new LongTaskTimingHandlerInterceptor(this.meterRegistry, this.tagsProvider)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfiguration.java index 969f70e7fd1..7ab9dd47b3d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfiguration.java @@ -48,13 +48,12 @@ import org.springframework.data.mongodb.core.MongoTemplate; @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter({ MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoReactiveHealthIndicatorAutoConfiguration.class }) -public class MongoHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class MongoHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "mongoHealthIndicator") - public HealthIndicator mongoHealthIndicator( - Map mongoTemplates) { + public HealthIndicator mongoHealthIndicator(Map mongoTemplates) { return createHealthIndicator(mongoTemplates); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfiguration.java index 98b9f065f89..4ce6351e064 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfiguration.java @@ -49,13 +49,12 @@ import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @ConditionalOnEnabledHealthIndicator("mongo") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(MongoReactiveDataAutoConfiguration.class) -public class MongoReactiveHealthIndicatorAutoConfiguration extends - CompositeReactiveHealthIndicatorConfiguration { +public class MongoReactiveHealthIndicatorAutoConfiguration + extends CompositeReactiveHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "mongoHealthIndicator") - public ReactiveHealthIndicator mongoHealthIndicator( - Map reactiveMongoTemplates) { + public ReactiveHealthIndicator mongoHealthIndicator(Map reactiveMongoTemplates) { return createHealthIndicator(reactiveMongoTemplates); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfiguration.java index 9a419ffa515..2780e5f64b5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfiguration.java @@ -48,13 +48,12 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnEnabledHealthIndicator("neo4j") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(Neo4jDataAutoConfiguration.class) -public class Neo4jHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class Neo4jHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "neo4jHealthIndicator") - public HealthIndicator neo4jHealthIndicator( - Map sessionFactories) { + public HealthIndicator neo4jHealthIndicator(Map sessionFactories) { return createHealthIndicator(sessionFactories); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfiguration.java index b52f3af03d0..e1dd321628c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfiguration.java @@ -48,15 +48,13 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; @ConditionalOnBean(RedisConnectionFactory.class) @ConditionalOnEnabledHealthIndicator("redis") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) -@AutoConfigureAfter({ RedisAutoConfiguration.class, - RedisReactiveHealthIndicatorAutoConfiguration.class }) -public class RedisHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +@AutoConfigureAfter({ RedisAutoConfiguration.class, RedisReactiveHealthIndicatorAutoConfiguration.class }) +public class RedisHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { @Bean @ConditionalOnMissingBean(name = "redisHealthIndicator") - public HealthIndicator redisHealthIndicator( - Map redisConnectionFactories) { + public HealthIndicator redisHealthIndicator(Map redisConnectionFactories) { return createHealthIndicator(redisConnectionFactories); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfiguration.java index a370fbcfd1f..e577d6da3fe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfiguration.java @@ -39,10 +39,8 @@ public class ScheduledTasksEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public ScheduledTasksEndpoint scheduledTasksEndpoint( - ObjectProvider holders) { - return new ScheduledTasksEndpoint( - holders.orderedStream().collect(Collectors.toList())); + public ScheduledTasksEndpoint scheduledTasksEndpoint(ObjectProvider holders) { + return new ScheduledTasksEndpoint(holders.orderedStream().collect(Collectors.toList())); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java index 010f54a31a0..05ced303ebf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java @@ -56,8 +56,7 @@ import org.springframework.web.server.ServerWebExchange; */ public final class EndpointRequest { - private static final ServerWebExchangeMatcher EMPTY_MATCHER = (request) -> MatchResult - .notMatch(); + private static final ServerWebExchangeMatcher EMPTY_MATCHER = (request) -> MatchResult.notMatch(); private EndpointRequest() { } @@ -135,20 +134,15 @@ public final class EndpointRequest { this(Collections.emptyList(), Collections.emptyList(), includeLinks); } - private EndpointServerWebExchangeMatcher(Class[] endpoints, - boolean includeLinks) { - this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), - includeLinks); + private EndpointServerWebExchangeMatcher(Class[] endpoints, boolean includeLinks) { + this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), includeLinks); } - private EndpointServerWebExchangeMatcher(String[] endpoints, - boolean includeLinks) { - this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), - includeLinks); + private EndpointServerWebExchangeMatcher(String[] endpoints, boolean includeLinks) { + this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), includeLinks); } - private EndpointServerWebExchangeMatcher(List includes, - List excludes, boolean includeLinks) { + private EndpointServerWebExchangeMatcher(List includes, List excludes, boolean includeLinks) { super(PathMappedEndpoints.class); this.includes = includes; this.excludes = excludes; @@ -158,20 +152,17 @@ public final class EndpointRequest { public EndpointServerWebExchangeMatcher excluding(Class... endpoints) { List excludes = new ArrayList<>(this.excludes); excludes.addAll(Arrays.asList((Object[]) endpoints)); - return new EndpointServerWebExchangeMatcher(this.includes, excludes, - this.includeLinks); + return new EndpointServerWebExchangeMatcher(this.includes, excludes, this.includeLinks); } public EndpointServerWebExchangeMatcher excluding(String... endpoints) { List excludes = new ArrayList<>(this.excludes); excludes.addAll(Arrays.asList((Object[]) endpoints)); - return new EndpointServerWebExchangeMatcher(this.includes, excludes, - this.includeLinks); + return new EndpointServerWebExchangeMatcher(this.includes, excludes, this.includeLinks); } public EndpointServerWebExchangeMatcher excludingLinks() { - return new EndpointServerWebExchangeMatcher(this.includes, this.excludes, - false); + return new EndpointServerWebExchangeMatcher(this.includes, this.excludes, false); } @Override @@ -179,8 +170,7 @@ public final class EndpointRequest { this.delegate = createDelegate(pathMappedEndpoints); } - private ServerWebExchangeMatcher createDelegate( - Supplier pathMappedEndpoints) { + private ServerWebExchangeMatcher createDelegate(Supplier pathMappedEndpoints) { try { return createDelegate(pathMappedEndpoints.get()); } @@ -189,8 +179,7 @@ public final class EndpointRequest { } } - private ServerWebExchangeMatcher createDelegate( - PathMappedEndpoints pathMappedEndpoints) { + private ServerWebExchangeMatcher createDelegate(PathMappedEndpoints pathMappedEndpoints) { Set paths = new LinkedHashSet<>(); if (this.includes.isEmpty()) { paths.addAll(pathMappedEndpoints.getAllPaths()); @@ -198,18 +187,14 @@ public final class EndpointRequest { streamPaths(this.includes, pathMappedEndpoints).forEach(paths::add); streamPaths(this.excludes, pathMappedEndpoints).forEach(paths::remove); List delegateMatchers = getDelegateMatchers(paths); - if (this.includeLinks - && StringUtils.hasText(pathMappedEndpoints.getBasePath())) { - delegateMatchers.add(new PathPatternParserServerWebExchangeMatcher( - pathMappedEndpoints.getBasePath())); + if (this.includeLinks && StringUtils.hasText(pathMappedEndpoints.getBasePath())) { + delegateMatchers.add(new PathPatternParserServerWebExchangeMatcher(pathMappedEndpoints.getBasePath())); } return new OrServerWebExchangeMatcher(delegateMatchers); } - private Stream streamPaths(List source, - PathMappedEndpoints pathMappedEndpoints) { - return source.stream().filter(Objects::nonNull).map(this::getEndpointId) - .map(pathMappedEndpoints::getPath); + private Stream streamPaths(List source, PathMappedEndpoints pathMappedEndpoints) { + return source.stream().filter(Objects::nonNull).map(this::getEndpointId).map(pathMappedEndpoints::getPath); } private EndpointId getEndpointId(Object source) { @@ -226,22 +211,18 @@ public final class EndpointRequest { } private EndpointId getEndpointId(Class source) { - MergedAnnotation annotation = MergedAnnotations.from(source) - .get(Endpoint.class); - Assert.state(annotation.isPresent(), - () -> "Class " + source + " is not annotated with @Endpoint"); + MergedAnnotation annotation = MergedAnnotations.from(source).get(Endpoint.class); + Assert.state(annotation.isPresent(), () -> "Class " + source + " is not annotated with @Endpoint"); return EndpointId.of(annotation.getString("id")); } private List getDelegateMatchers(Set paths) { - return paths.stream().map( - (path) -> new PathPatternParserServerWebExchangeMatcher(path + "/**")) + return paths.stream().map((path) -> new PathPatternParserServerWebExchangeMatcher(path + "/**")) .collect(Collectors.toList()); } @Override - protected Mono matches(ServerWebExchange exchange, - Supplier context) { + protected Mono matches(ServerWebExchange exchange, Supplier context) { if (!isManagementContext(exchange)) { return MatchResult.notMatch(); } @@ -250,13 +231,11 @@ public final class EndpointRequest { static boolean isManagementContext(ServerWebExchange exchange) { ApplicationContext applicationContext = exchange.getApplicationContext(); - if (ManagementPortType.get(applicationContext - .getEnvironment()) == ManagementPortType.DIFFERENT) { + if (ManagementPortType.get(applicationContext.getEnvironment()) == ManagementPortType.DIFFERENT) { if (applicationContext.getParent() == null) { return false; } - String managementContextId = applicationContext.getParent().getId() - + ":management"; + String managementContextId = applicationContext.getParent().getId() + ":management"; if (!managementContextId.equals(applicationContext.getId())) { return false; } @@ -283,18 +262,15 @@ public final class EndpointRequest { this.delegate = createDelegate(properties.get()); } - private ServerWebExchangeMatcher createDelegate( - WebEndpointProperties properties) { + private ServerWebExchangeMatcher createDelegate(WebEndpointProperties properties) { if (StringUtils.hasText(properties.getBasePath())) { - return new PathPatternParserServerWebExchangeMatcher( - properties.getBasePath()); + return new PathPatternParserServerWebExchangeMatcher(properties.getBasePath()); } return EMPTY_MATCHER; } @Override - protected Mono matches(ServerWebExchange exchange, - Supplier context) { + protected Mono matches(ServerWebExchange exchange, Supplier context) { if (!EndpointServerWebExchangeMatcher.isManagementContext(exchange)) { return MatchResult.notMatch(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.java index f97bc2ed6c9..ef0c3273735 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.java @@ -50,18 +50,15 @@ import org.springframework.security.web.server.WebFilterChainProxy; @ConditionalOnMissingBean({ SecurityWebFilterChain.class, WebFilterChainProxy.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @AutoConfigureBefore(ReactiveSecurityAutoConfiguration.class) -@AutoConfigureAfter({ HealthEndpointAutoConfiguration.class, - InfoEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ReactiveOAuth2ClientAutoConfiguration.class, +@AutoConfigureAfter({ HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ReactiveOAuth2ClientAutoConfiguration.class, ReactiveOAuth2ResourceServerAutoConfiguration.class }) public class ReactiveManagementWebSecurityAutoConfiguration { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - return http.authorizeExchange() - .matchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)) - .permitAll().anyExchange().authenticated().and().httpBasic().and() - .formLogin().and().build(); + return http.authorizeExchange().matchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)) + .permitAll().anyExchange().authenticated().and().httpBasic().and().formLogin().and().build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java index 5cf22323b1c..bfc66d536f1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java @@ -134,17 +134,14 @@ public final class EndpointRequest { } @Override - protected final boolean matches(HttpServletRequest request, - Supplier context) { + protected final boolean matches(HttpServletRequest request, Supplier context) { WebApplicationContext applicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getServletContext()); - if (ManagementPortType.get(applicationContext - .getEnvironment()) == ManagementPortType.DIFFERENT) { + if (ManagementPortType.get(applicationContext.getEnvironment()) == ManagementPortType.DIFFERENT) { if (applicationContext.getParent() == null) { return false; } - String managementContextId = applicationContext.getParent().getId() - + ":management"; + String managementContextId = applicationContext.getParent().getId() + ":management"; if (!managementContextId.equals(applicationContext.getId())) { return false; } @@ -164,18 +161,15 @@ public final class EndpointRequest { protected abstract RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory); - protected List getLinksMatchers( - RequestMatcherFactory requestMatcherFactory, + protected List getLinksMatchers(RequestMatcherFactory requestMatcherFactory, RequestMatcherProvider matcherProvider, String basePath) { List linksMatchers = new ArrayList<>(); linksMatchers.add(requestMatcherFactory.antPath(matcherProvider, basePath)); - linksMatchers - .add(requestMatcherFactory.antPath(matcherProvider, basePath, "/")); + linksMatchers.add(requestMatcherFactory.antPath(matcherProvider, basePath, "/")); return linksMatchers; } - protected RequestMatcherProvider getRequestMatcherProvider( - WebApplicationContext context) { + protected RequestMatcherProvider getRequestMatcherProvider(WebApplicationContext context) { try { return context.getBean(RequestMatcherProvider.class); } @@ -202,17 +196,14 @@ public final class EndpointRequest { } private EndpointRequestMatcher(Class[] endpoints, boolean includeLinks) { - this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), - includeLinks); + this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), includeLinks); } private EndpointRequestMatcher(String[] endpoints, boolean includeLinks) { - this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), - includeLinks); + this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), includeLinks); } - private EndpointRequestMatcher(List includes, List excludes, - boolean includeLinks) { + private EndpointRequestMatcher(List includes, List excludes, boolean includeLinks) { this.includes = includes; this.excludes = excludes; this.includeLinks = includeLinks; @@ -237,8 +228,7 @@ public final class EndpointRequest { @Override protected RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory) { - PathMappedEndpoints pathMappedEndpoints = context - .getBean(PathMappedEndpoints.class); + PathMappedEndpoints pathMappedEndpoints = context.getBean(PathMappedEndpoints.class); RequestMatcherProvider matcherProvider = getRequestMatcherProvider(context); Set paths = new LinkedHashSet<>(); if (this.includes.isEmpty()) { @@ -246,20 +236,16 @@ public final class EndpointRequest { } streamPaths(this.includes, pathMappedEndpoints).forEach(paths::add); streamPaths(this.excludes, pathMappedEndpoints).forEach(paths::remove); - List delegateMatchers = getDelegateMatchers( - requestMatcherFactory, matcherProvider, paths); + List delegateMatchers = getDelegateMatchers(requestMatcherFactory, matcherProvider, paths); String basePath = pathMappedEndpoints.getBasePath(); if (this.includeLinks && StringUtils.hasText(basePath)) { - delegateMatchers.addAll(getLinksMatchers(requestMatcherFactory, - matcherProvider, basePath)); + delegateMatchers.addAll(getLinksMatchers(requestMatcherFactory, matcherProvider, basePath)); } return new OrRequestMatcher(delegateMatchers); } - private Stream streamPaths(List source, - PathMappedEndpoints pathMappedEndpoints) { - return source.stream().filter(Objects::nonNull).map(this::getEndpointId) - .map(pathMappedEndpoints::getPath); + private Stream streamPaths(List source, PathMappedEndpoints pathMappedEndpoints) { + return source.stream().filter(Objects::nonNull).map(this::getEndpointId).map(pathMappedEndpoints::getPath); } private EndpointId getEndpointId(Object source) { @@ -276,18 +262,14 @@ public final class EndpointRequest { } private EndpointId getEndpointId(Class source) { - MergedAnnotation annotation = MergedAnnotations.from(source) - .get(Endpoint.class); - Assert.state(annotation.isPresent(), - () -> "Class " + source + " is not annotated with @Endpoint"); + MergedAnnotation annotation = MergedAnnotations.from(source).get(Endpoint.class); + Assert.state(annotation.isPresent(), () -> "Class " + source + " is not annotated with @Endpoint"); return EndpointId.of(annotation.getString("id")); } - private List getDelegateMatchers( - RequestMatcherFactory requestMatcherFactory, + private List getDelegateMatchers(RequestMatcherFactory requestMatcherFactory, RequestMatcherProvider matcherProvider, Set paths) { - return paths.stream().map( - (path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**")) + return paths.stream().map((path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**")) .collect(Collectors.toList()); } @@ -301,12 +283,11 @@ public final class EndpointRequest { @Override protected RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory) { - WebEndpointProperties properties = context - .getBean(WebEndpointProperties.class); + WebEndpointProperties properties = context.getBean(WebEndpointProperties.class); String basePath = properties.getBasePath(); if (StringUtils.hasText(basePath)) { - return new OrRequestMatcher(getLinksMatchers(requestMatcherFactory, - getRequestMatcherProvider(context), basePath)); + return new OrRequestMatcher( + getLinksMatchers(requestMatcherFactory, getRequestMatcherProvider(context), basePath)); } return EMPTY_MATCHER; } @@ -318,8 +299,7 @@ public final class EndpointRequest { */ private static class RequestMatcherFactory { - public RequestMatcher antPath(RequestMatcherProvider matcherProvider, - String... parts) { + public RequestMatcher antPath(RequestMatcherProvider matcherProvider, String... parts) { StringBuilder pattern = new StringBuilder(); for (String part : parts) { pattern.append(part); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfiguration.java index b10ae3f2b4c..ed95e05b3b1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfiguration.java @@ -46,12 +46,10 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @ConditionalOnMissingBean(WebSecurityConfigurerAdapter.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @AutoConfigureBefore(SecurityAutoConfiguration.class) -@AutoConfigureAfter({ HealthEndpointAutoConfiguration.class, - InfoEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - OAuth2ClientAutoConfiguration.class, +@AutoConfigureAfter({ HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, OAuth2ClientAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class }) -@Import({ ManagementWebSecurityConfigurerAdapter.class, - WebSecurityEnablerConfiguration.class }) +@Import({ ManagementWebSecurityConfigurerAdapter.class, WebSecurityEnablerConfiguration.class }) public class ManagementWebSecurityAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityConfigurerAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityConfigurerAdapter.java index 76bbdb9813b..8018688baad 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityConfigurerAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityConfigurerAdapter.java @@ -39,11 +39,8 @@ class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapte @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .requestMatchers( - EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)) - .permitAll().anyRequest().authenticated().and().formLogin().and() - .httpBasic(); + http.authorizeRequests().requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)) + .permitAll().anyRequest().authenticated().and().formLogin().and().httpBasic(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.java index 1e216f2d376..57f8d0a547f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.java @@ -44,8 +44,7 @@ public class SessionsEndpointAutoConfiguration { @Bean @ConditionalOnBean(FindByIndexNameSessionRepository.class) @ConditionalOnMissingBean - public SessionsEndpoint sessionEndpoint( - FindByIndexNameSessionRepository sessionRepository) { + public SessionsEndpoint sessionEndpoint(FindByIndexNameSessionRepository sessionRepository) { return new SessionsEndpoint(sessionRepository); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfiguration.java index 910520ed541..6f3efdbeb53 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfiguration.java @@ -40,10 +40,8 @@ public class DiskSpaceHealthIndicatorAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "diskSpaceHealthIndicator") - public DiskSpaceHealthIndicator diskSpaceHealthIndicator( - DiskSpaceHealthIndicatorProperties properties) { - return new DiskSpaceHealthIndicator(properties.getPath(), - properties.getThreshold()); + public DiskSpaceHealthIndicator diskSpaceHealthIndicator(DiskSpaceHealthIndicatorProperties properties) { + return new DiskSpaceHealthIndicator(properties.getPath(), properties.getThreshold()); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorProperties.java index c9a4960fedd..75a79304f39 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,7 @@ public class DiskSpaceHealthIndicatorProperties { } public void setThreshold(DataSize threshold) { - Assert.isTrue(!threshold.isNegative(), - "threshold must be greater than or equal to 0"); + Assert.isTrue(!threshold.isNegative(), "threshold must be greater than or equal to 0"); this.threshold = threshold; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration.java index 97c2e4e70b6..b94e10bc645 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration.java @@ -38,8 +38,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication -@ConditionalOnProperty(prefix = "management.trace.http", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.trace.http", name = "enabled", matchIfMissing = true) @ConditionalOnBean(HttpTraceRepository.class) @EnableConfigurationProperties(HttpTraceProperties.class) public class HttpTraceAutoConfiguration { @@ -56,8 +55,7 @@ public class HttpTraceAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpTraceFilter httpTraceFilter(HttpTraceRepository repository, - HttpExchangeTracer tracer) { + public HttpTraceFilter httpTraceFilter(HttpTraceRepository repository, HttpExchangeTracer tracer) { return new HttpTraceFilter(repository, tracer); } @@ -69,10 +67,9 @@ public class HttpTraceAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpTraceWebFilter httpTraceWebFilter(HttpTraceRepository repository, - HttpExchangeTracer tracer, HttpTraceProperties traceProperties) { - return new HttpTraceWebFilter(repository, tracer, - traceProperties.getInclude()); + public HttpTraceWebFilter httpTraceWebFilter(HttpTraceRepository repository, HttpExchangeTracer tracer, + HttpTraceProperties traceProperties) { + return new HttpTraceWebFilter(repository, tracer, traceProperties.getInclude()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java index bff04e2014d..d1a9bc8a7e3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ public interface ManagementContextFactory { * @param configurationClasses the configuration classes * @return a configured application context */ - ConfigurableWebServerApplicationContext createManagementContext( - ApplicationContext parent, Class... configurationClasses); + ConfigurableWebServerApplicationContext createManagementContext(ApplicationContext parent, + Class... configurationClasses); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementContextConfiguration.java index 199b87aa21a..186c417d758 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementContextConfiguration.java @@ -41,11 +41,9 @@ class JerseyManagementContextConfiguration { } @Bean - public ResourceConfig resourceConfig( - ObjectProvider resourceConfigCustomizers) { + public ResourceConfig resourceConfig(ObjectProvider resourceConfigCustomizers) { ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfigCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(resourceConfig)); + resourceConfigCustomizers.orderedStream().forEach((customizer) -> customizer.customize(resourceConfig)); return resourceConfig; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfiguration.java index bfbc0e82672..1d481524f18 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfiguration.java @@ -47,8 +47,7 @@ public class JerseySameManagementContextConfiguration { @Bean @ConditionalOnMissingBean(JerseyApplicationPath.class) - public JerseyApplicationPath jerseyApplicationPath(JerseyProperties properties, - ResourceConfig config) { + public JerseyApplicationPath jerseyApplicationPath(JerseyProperties properties, ResourceConfig config) { return new DefaultJerseyApplicationPath(properties.getApplicationPath(), config); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfiguration.java index 57b2434199b..cce375620dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfiguration.java @@ -50,8 +50,7 @@ public class MappingsEndpointAutoConfiguration { @ConditionalOnAvailableEndpoint public MappingsEndpoint mappingsEndpoint(ApplicationContext applicationContext, ObjectProvider descriptionProviders) { - return new MappingsEndpoint( - descriptionProviders.orderedStream().collect(Collectors.toList()), + return new MappingsEndpoint(descriptionProviders.orderedStream().collect(Collectors.toList()), applicationContext); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfiguration.java index 492a2c48304..c9e95420d22 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfiguration.java @@ -60,16 +60,13 @@ public class ReactiveManagementChildContextConfiguration { return WebHttpHandlerBuilder.applicationContext(applicationContext).build(); } - class ReactiveManagementWebServerFactoryCustomizer extends - ManagementWebServerFactoryCustomizer { + class ReactiveManagementWebServerFactoryCustomizer + extends ManagementWebServerFactoryCustomizer { ReactiveManagementWebServerFactoryCustomizer(ListableBeanFactory beanFactory) { - super(beanFactory, ReactiveWebServerFactoryCustomizer.class, - TomcatWebServerFactoryCustomizer.class, - TomcatReactiveWebServerFactoryCustomizer.class, - JettyWebServerFactoryCustomizer.class, - UndertowWebServerFactoryCustomizer.class, - NettyWebServerFactoryCustomizer.class); + super(beanFactory, ReactiveWebServerFactoryCustomizer.class, TomcatWebServerFactoryCustomizer.class, + TomcatReactiveWebServerFactoryCustomizer.class, JettyWebServerFactoryCustomizer.class, + UndertowWebServerFactoryCustomizer.class, NettyWebServerFactoryCustomizer.class); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java index 7a5cc1b087c..142de44aba9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ import org.springframework.util.ObjectUtils; class ReactiveManagementContextFactory implements ManagementContextFactory { @Override - public ConfigurableWebServerApplicationContext createManagementContext( - ApplicationContext parent, Class... configClasses) { + public ConfigurableWebServerApplicationContext createManagementContext(ApplicationContext parent, + Class... configClasses) { AnnotationConfigReactiveWebServerApplicationContext child = new AnnotationConfigReactiveWebServerApplicationContext(); child.setParent(parent); Class[] combinedClasses = ObjectUtils.addObjectToArray(configClasses, @@ -57,8 +57,7 @@ class ReactiveManagementContextFactory implements ManagementContextFactory { if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition("ReactiveWebServerFactory", - new RootBeanDefinition( - determineReactiveWebServerFactoryClass(parent))); + new RootBeanDefinition(determineReactiveWebServerFactoryClass(parent))); } } catch (NoSuchBeanDefinitionException ex) { @@ -70,9 +69,8 @@ class ReactiveManagementContextFactory implements ManagementContextFactory { throws NoSuchBeanDefinitionException { Class factoryClass = parent.getBean(ReactiveWebServerFactory.class).getClass(); if (cannotBeInstantiated(factoryClass)) { - throw new FatalBeanException("ReactiveWebServerFactory implementation " - + factoryClass.getName() + " cannot be instantiated. " - + "To allow a separate management port to be used, a top-level class " + throw new FatalBeanException("ReactiveWebServerFactory implementation " + factoryClass.getName() + + " cannot be instantiated. " + "To allow a separate management port to be used, a top-level class " + "or static inner class should be used instead"); } return factoryClass; @@ -80,8 +78,7 @@ class ReactiveManagementContextFactory implements ManagementContextFactory { private boolean cannotBeInstantiated(Class factoryClass) { return factoryClass.isLocalClass() - || (factoryClass.isMemberClass() - && !Modifier.isStatic(factoryClass.getModifiers())) + || (factoryClass.isMemberClass() && !Modifier.isStatic(factoryClass.getModifiers())) || factoryClass.isAnonymousClass(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java index 0347f7333d9..01e5213e101 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Value; * @author Stephane Nicoll * @since 2.0.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Value("${local.management.port}") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java index 15396075af8..7e83ab11ed1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java @@ -57,14 +57,12 @@ import org.springframework.util.Assert; */ @Configuration(proxyBeanMethods = false) @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) -@EnableConfigurationProperties({ WebEndpointProperties.class, - ManagementServerProperties.class }) +@EnableConfigurationProperties({ WebEndpointProperties.class, ManagementServerProperties.class }) public class ManagementContextAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnManagementPort(ManagementPortType.SAME) - static class SameManagementContextConfiguration - implements SmartInitializingSingleton { + static class SameManagementContextConfiguration implements SmartInitializingSingleton { private final Environment environment; @@ -76,17 +74,14 @@ public class ManagementContextAutoConfiguration { public void afterSingletonsInstantiated() { verifySslConfiguration(); if (this.environment instanceof ConfigurableEnvironment) { - addLocalManagementPortPropertyAlias( - (ConfigurableEnvironment) this.environment); + addLocalManagementPortPropertyAlias((ConfigurableEnvironment) this.environment); } } private void verifySslConfiguration() { - Boolean enabled = this.environment - .getProperty("management.server.ssl.enabled", Boolean.class, false); - Assert.state(!enabled, - "Management-specific SSL cannot be configured as the management " - + "server is not listening on a separate port"); + Boolean enabled = this.environment.getProperty("management.server.ssl.enabled", Boolean.class, false); + Assert.state(!enabled, "Management-specific SSL cannot be configured as the management " + + "server is not listening on a separate port"); } /** @@ -94,20 +89,18 @@ public class ManagementContextAutoConfiguration { * 'local.server.port'. * @param environment the environment */ - private void addLocalManagementPortPropertyAlias( - ConfigurableEnvironment environment) { - environment.getPropertySources() - .addLast(new PropertySource("Management Server") { + private void addLocalManagementPortPropertyAlias(ConfigurableEnvironment environment) { + environment.getPropertySources().addLast(new PropertySource("Management Server") { - @Override - public Object getProperty(String name) { - if ("local.management.port".equals(name)) { - return environment.getProperty("local.server.port"); - } - return null; - } + @Override + public Object getProperty(String name) { + if ("local.management.port".equals(name)) { + return environment.getProperty("local.server.port"); + } + return null; + } - }); + }); } @Configuration(proxyBeanMethods = false) @@ -120,8 +113,7 @@ public class ManagementContextAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) - static class DifferentManagementContextConfiguration - implements ApplicationListener { + static class DifferentManagementContextConfiguration implements ApplicationListener { private final ApplicationContext applicationContext; @@ -141,30 +133,25 @@ public class ManagementContextAutoConfiguration { EnableChildManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class); if (isLazyInitialization()) { - managementContext.addBeanFactoryPostProcessor( - new LazyInitializationBeanFactoryPostProcessor()); + managementContext.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } managementContext.setServerNamespace("management"); managementContext.setId(this.applicationContext.getId() + ":management"); setClassLoaderIfPossible(managementContext); - CloseManagementContextListener.addIfPossible(this.applicationContext, - managementContext); + CloseManagementContextListener.addIfPossible(this.applicationContext, managementContext); managementContext.refresh(); } } protected boolean isLazyInitialization() { AbstractApplicationContext context = (AbstractApplicationContext) this.applicationContext; - List postProcessors = context - .getBeanFactoryPostProcessors(); - return postProcessors.stream().anyMatch( - LazyInitializationBeanFactoryPostProcessor.class::isInstance); + List postProcessors = context.getBeanFactoryPostProcessors(); + return postProcessors.stream().anyMatch(LazyInitializationBeanFactoryPostProcessor.class::isInstance); } private void setClassLoaderIfPossible(ConfigurableApplicationContext child) { if (child instanceof DefaultResourceLoader) { - ((DefaultResourceLoader) child) - .setClassLoader(this.applicationContext.getClassLoader()); + ((DefaultResourceLoader) child).setClassLoader(this.applicationContext.getClassLoader()); } } @@ -174,15 +161,13 @@ public class ManagementContextAutoConfiguration { * {@link ApplicationListener} to propagate the {@link ContextClosedEvent} and * {@link ApplicationFailedEvent} from a parent to a child. */ - private static class CloseManagementContextListener - implements ApplicationListener { + private static class CloseManagementContextListener implements ApplicationListener { private final ApplicationContext parentContext; private final ConfigurableApplicationContext childContext; - CloseManagementContextListener(ApplicationContext parentContext, - ConfigurableApplicationContext childContext) { + CloseManagementContextListener(ApplicationContext parentContext, ConfigurableApplicationContext childContext) { this.parentContext = parentContext; this.childContext = childContext; } @@ -220,8 +205,7 @@ public class ManagementContextAutoConfiguration { private static void add(ConfigurableApplicationContext parentContext, ConfigurableApplicationContext childContext) { - parentContext.addApplicationListener( - new CloseManagementContextListener(parentContext, childContext)); + parentContext.addApplicationListener(new CloseManagementContextListener(parentContext, childContext)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java index 51af7667957..7d888e124db 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,16 +46,14 @@ import org.springframework.util.StringUtils; * @see ManagementContextConfiguration */ @Order(Ordered.LOWEST_PRECEDENCE) -class ManagementContextConfigurationImportSelector - implements DeferredImportSelector, BeanClassLoaderAware { +class ManagementContextConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware { private ClassLoader classLoader; @Override public String[] selectImports(AnnotationMetadata metadata) { ManagementContextType contextType = (ManagementContextType) metadata - .getAnnotationAttributes(EnableManagementContext.class.getName()) - .get("value"); + .getAnnotationAttributes(EnableManagementContext.class.getName()).get("value"); // Find all management context configuration classes, filtering duplicates List configurations = getConfigurations(); OrderComparator.sort(configurations); @@ -70,8 +68,7 @@ class ManagementContextConfigurationImportSelector } private List getConfigurations() { - SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory( - this.classLoader); + SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(this.classLoader); List configurations = new ArrayList<>(); for (String className : loadFactoryNames()) { addConfiguration(readerFactory, configurations, className); @@ -86,14 +83,12 @@ class ManagementContextConfigurationImportSelector configurations.add(new ManagementConfiguration(metadataReader)); } catch (IOException ex) { - throw new RuntimeException( - "Failed to read annotation metadata for '" + className + "'", ex); + throw new RuntimeException("Failed to read annotation metadata for '" + className + "'", ex); } } protected List loadFactoryNames() { - return SpringFactoriesLoader - .loadFactoryNames(ManagementContextConfiguration.class, this.classLoader); + return SpringFactoriesLoader.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader); } @Override @@ -113,28 +108,22 @@ class ManagementContextConfigurationImportSelector private final ManagementContextType contextType; ManagementConfiguration(MetadataReader metadataReader) { - AnnotationMetadata annotationMetadata = metadataReader - .getAnnotationMetadata(); + AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); this.order = readOrder(annotationMetadata); this.className = metadataReader.getClassMetadata().getClassName(); this.contextType = readContextType(annotationMetadata); } - private ManagementContextType readContextType( - AnnotationMetadata annotationMetadata) { + private ManagementContextType readContextType(AnnotationMetadata annotationMetadata) { Map annotationAttributes = annotationMetadata - .getAnnotationAttributes( - ManagementContextConfiguration.class.getName()); - return (annotationAttributes != null) - ? (ManagementContextType) annotationAttributes.get("value") + .getAnnotationAttributes(ManagementContextConfiguration.class.getName()); + return (annotationAttributes != null) ? (ManagementContextType) annotationAttributes.get("value") : ManagementContextType.ANY; } private int readOrder(AnnotationMetadata annotationMetadata) { - Map attributes = annotationMetadata - .getAnnotationAttributes(Order.class.getName()); - Integer order = (attributes != null) ? (Integer) attributes.get("value") - : null; + Map attributes = annotationMetadata.getAnnotationAttributes(Order.class.getName()); + Integer order = (attributes != null) ? (Integer) attributes.get("value") : null; return (order != null) ? order : Ordered.LOWEST_PRECEDENCE; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementPortType.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementPortType.java index 5899f240a86..ac0cf6adfc7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementPortType.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementPortType.java @@ -56,10 +56,8 @@ public enum ManagementPortType { return DISABLED; } Integer serverPort = getPortProperty(environment, "server."); - return ((managementPort == null - || (serverPort == null && managementPort.equals(8080)) - || (managementPort != 0 && managementPort.equals(serverPort))) ? SAME - : DIFFERENT); + return ((managementPort == null || (serverPort == null && managementPort.equals(8080)) + || (managementPort != 0 && managementPort.equals(serverPort))) ? SAME : DIFFERENT); } private static Integer getPortProperty(Environment environment, String prefix) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java index 05c1e437ad7..e6f96014d74 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,22 +64,20 @@ public abstract class ManagementWebServerFactoryCustomizer> customizers = Arrays - .stream(this.customizerClasses).map(this::getCustomizer) + List> customizers = Arrays.stream(this.customizerClasses).map(this::getCustomizer) .filter(Objects::nonNull).collect(Collectors.toList()); invokeCustomizers(factory, customizers); } @@ -87,8 +85,7 @@ public abstract class ManagementWebServerFactoryCustomizer getCustomizer( Class> customizerClass) { try { - return BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory, - customizerClass); + return BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory, customizerClass); } catch (NoSuchBeanDefinitionException ex) { return null; @@ -96,14 +93,12 @@ public abstract class ManagementWebServerFactoryCustomizer> customizers) { + private void invokeCustomizers(T factory, List> customizers) { LambdaSafe.callbacks(WebServerFactoryCustomizer.class, customizers, factory) .invoke((customizer) -> customizer.customize(factory)); } - protected void customize(T factory, - ManagementServerProperties managementServerProperties, + protected void customize(T factory, ManagementServerProperties managementServerProperties, ServerProperties serverProperties) { factory.setPort(managementServerProperties.getPort()); Ssl ssl = managementServerProperties.getSsl(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java index 1fde60545a2..077a6b9ee6c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,24 +39,20 @@ class OnManagementPortCondition extends SpringBootCondition { private static final String CLASS_NAME_WEB_APPLICATION_CONTEXT = "org.springframework.web.context.WebApplicationContext"; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Management Port"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Management Port"); if (!isWebApplicationContext(context)) { - return ConditionOutcome - .noMatch(message.because("non web application context")); + return ConditionOutcome.noMatch(message.because("non web application context")); } - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnManagementPort.class.getName()); + Map attributes = metadata.getAnnotationAttributes(ConditionalOnManagementPort.class.getName()); ManagementPortType requiredType = (ManagementPortType) attributes.get("value"); ManagementPortType actualType = ManagementPortType.get(context.getEnvironment()); if (actualType == requiredType) { - return ConditionOutcome.match(message.because( - "actual port type (" + actualType + ") matched required type")); + return ConditionOutcome + .match(message.because("actual port type (" + actualType + ") matched required type")); } - return ConditionOutcome.noMatch(message.because("actual port type (" + actualType - + ") did not match required type (" + requiredType + ")")); + return ConditionOutcome.noMatch(message + .because("actual port type (" + actualType + ") did not match required type (" + requiredType + ")")); } private boolean isWebApplicationContext(ConditionContext context) { @@ -64,8 +60,7 @@ class OnManagementPortCondition extends SpringBootCondition { if (resourceLoader instanceof ConfigurableReactiveWebApplicationContext) { return true; } - if (!ClassUtils.isPresent(CLASS_NAME_WEB_APPLICATION_CONTEXT, - context.getClassLoader())) { + if (!ClassUtils.isPresent(CLASS_NAME_WEB_APPLICATION_CONTEXT, context.getClassLoader())) { return false; } return resourceLoader instanceof WebApplicationContext; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerAdapter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerAdapter.java index 738a64d39c8..9918ca55f9b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerAdapter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,8 @@ class CompositeHandlerAdapter implements HandlerAdapter { } @Override - public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, - Object handler) throws Exception { + public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { Optional adapter = getAdapter(handler); if (adapter.isPresent()) { return adapter.get().handle(request, response, handler); @@ -63,9 +63,7 @@ class CompositeHandlerAdapter implements HandlerAdapter { @Override public long getLastModified(HttpServletRequest request, Object handler) { Optional adapter = getAdapter(handler); - return adapter - .map((handlerAdapter) -> handlerAdapter.getLastModified(request, handler)) - .orElse(0L); + return adapter.map((handlerAdapter) -> handlerAdapter.getLastModified(request, handler)).orElse(0L); } private Optional getAdapter(Object handler) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolver.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolver.java index 6d68a6a627e..adff968d14f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolver.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,20 +45,18 @@ class CompositeHandlerExceptionResolver implements HandlerExceptionResolver { private List resolvers; @Override - public ModelAndView resolveException(HttpServletRequest request, - HttpServletResponse response, Object handler, Exception ex) { + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) { if (this.resolvers == null) { this.resolvers = extractResolvers(); } - return this.resolvers.stream().map( - (resolver) -> resolver.resolveException(request, response, handler, ex)) + return this.resolvers.stream().map((resolver) -> resolver.resolveException(request, response, handler, ex)) .filter(Objects::nonNull).findFirst().orElse(null); } private List extractResolvers() { List list = new ArrayList<>(); - list.addAll( - this.beanFactory.getBeansOfType(HandlerExceptionResolver.class).values()); + list.addAll(this.beanFactory.getBeansOfType(HandlerExceptionResolver.class).values()); list.remove(this); AnnotationAwareOrderComparator.sort(list); if (list.isEmpty()) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java index 21e513766fc..0e08b767464 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java @@ -98,8 +98,7 @@ class ServletManagementChildContextConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ EnableWebSecurity.class, Filter.class }) - @ConditionalOnBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN, - search = SearchStrategy.ANCESTORS) + @ConditionalOnBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN, search = SearchStrategy.ANCESTORS) static class ServletManagementContextSecurityConfiguration { @Bean @@ -110,25 +109,20 @@ class ServletManagementChildContextConfiguration { } - static class ServletManagementWebServerFactoryCustomizer extends - ManagementWebServerFactoryCustomizer { + static class ServletManagementWebServerFactoryCustomizer + extends ManagementWebServerFactoryCustomizer { ServletManagementWebServerFactoryCustomizer(ListableBeanFactory beanFactory) { - super(beanFactory, ServletWebServerFactoryCustomizer.class, - TomcatServletWebServerFactoryCustomizer.class, - TomcatWebServerFactoryCustomizer.class, - JettyWebServerFactoryCustomizer.class, + super(beanFactory, ServletWebServerFactoryCustomizer.class, TomcatServletWebServerFactoryCustomizer.class, + TomcatWebServerFactoryCustomizer.class, JettyWebServerFactoryCustomizer.class, UndertowWebServerFactoryCustomizer.class); } @Override protected void customize(ConfigurableServletWebServerFactory webServerFactory, - ManagementServerProperties managementServerProperties, - ServerProperties serverProperties) { - super.customize(webServerFactory, managementServerProperties, - serverProperties); - webServerFactory.setContextPath( - managementServerProperties.getServlet().getContextPath()); + ManagementServerProperties managementServerProperties, ServerProperties serverProperties) { + super.customize(webServerFactory, managementServerProperties, serverProperties); + webServerFactory.setContextPath(managementServerProperties.getServlet().getContextPath()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextAutoConfiguration.java index d99f2fd0ada..f7a7fc2616d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextAutoConfiguration.java @@ -47,21 +47,18 @@ public class ServletManagementContextAutoConfiguration { } @Bean - public ManagementServletContext managementServletContext( - WebEndpointProperties properties) { + public ManagementServletContext managementServletContext(WebEndpointProperties properties) { return properties::getBasePath; } // Put Servlets and Filters in their own nested class so they don't force early // instantiation of ManagementServerProperties. @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "management.server", - name = "add-application-context-header", havingValue = "true") + @ConditionalOnProperty(prefix = "management.server", name = "add-application-context-header", havingValue = "true") protected static class ApplicationContextFilterConfiguration { @Bean - public ApplicationContextHeaderFilter applicationContextIdFilter( - ApplicationContext context) { + public ApplicationContextHeaderFilter applicationContextIdFilter(ApplicationContext context) { return new ApplicationContextHeaderFilter(context); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java index ce0f7fe675a..aa66ec2c4e2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ import org.springframework.util.ClassUtils; class ServletManagementContextFactory implements ManagementContextFactory { @Override - public ConfigurableWebServerApplicationContext createManagementContext( - ApplicationContext parent, Class... configClasses) { + public ConfigurableWebServerApplicationContext createManagementContext(ApplicationContext parent, + Class... configClasses) { AnnotationConfigServletWebServerApplicationContext child = new AnnotationConfigServletWebServerApplicationContext(); child.setParent(parent); List> combinedClasses = new ArrayList<>(Arrays.asList(configClasses)); @@ -60,8 +60,7 @@ class ServletManagementContextFactory implements ManagementContextFactory { if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition("ServletWebServerFactory", - new RootBeanDefinition( - determineServletWebServerFactoryClass(parent))); + new RootBeanDefinition(determineServletWebServerFactoryClass(parent))); } } catch (NoSuchBeanDefinitionException ex) { @@ -73,9 +72,8 @@ class ServletManagementContextFactory implements ManagementContextFactory { throws NoSuchBeanDefinitionException { Class factoryClass = parent.getBean(ServletWebServerFactory.class).getClass(); if (cannotBeInstantiated(factoryClass)) { - throw new FatalBeanException("ServletWebServerFactory implementation " - + factoryClass.getName() + " cannot be instantiated. " - + "To allow a separate management port to be used, a top-level class " + throw new FatalBeanException("ServletWebServerFactory implementation " + factoryClass.getName() + + " cannot be instantiated. " + "To allow a separate management port to be used, a top-level class " + "or static inner class should be used instead"); } return factoryClass; @@ -83,8 +81,7 @@ class ServletManagementContextFactory implements ManagementContextFactory { private boolean cannotBeInstantiated(Class factoryClass) { return factoryClass.isLocalClass() - || (factoryClass.isMemberClass() - && !Modifier.isStatic(factoryClass.getModifiers())) + || (factoryClass.isMemberClass() && !Modifier.isStatic(factoryClass.getModifiers())) || factoryClass.isAnonymousClass(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfiguration.java index ff9f8fd1a61..9d8b4cf3961 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfiguration.java @@ -72,8 +72,7 @@ class WebMvcEndpointChildContextConfiguration { } @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) - public DispatcherServletRegistrationBean dispatcherServletRegistrationBean( - DispatcherServlet dispatcherServlet) { + public DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) { return new DispatcherServletRegistrationBean(dispatcherServlet, "/"); } @@ -83,8 +82,7 @@ class WebMvcEndpointChildContextConfiguration { } @Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME) - public CompositeHandlerAdapter compositeHandlerAdapter( - ListableBeanFactory beanFactory) { + public CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) { return new CompositeHandlerAdapter(beanFactory); } @@ -94,8 +92,7 @@ class WebMvcEndpointChildContextConfiguration { } @Bean - @ConditionalOnMissingBean({ RequestContextListener.class, - RequestContextFilter.class }) + @ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class }) public RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java index 3a393b49abf..f9b41a7e397 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java @@ -54,38 +54,36 @@ public class SpringApplicationHierarchyTests { public void testParent() { SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class); builder.parent(Parent.class); - this.context = builder.run("--server.port=0", - "--management.metrics.use-global-registry=false"); + this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false"); } @Test public void testChild() { SpringApplicationBuilder builder = new SpringApplicationBuilder(Parent.class); builder.child(Child.class); - this.context = builder.run("--server.port=0", - "--management.metrics.use-global-registry=false"); + this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false"); } - @EnableAutoConfiguration(exclude = { ElasticsearchDataAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, - MongoDataAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, - Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, - RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, - FlywayAutoConfiguration.class, MetricsAutoConfiguration.class }, + @EnableAutoConfiguration( + exclude = { ElasticsearchDataAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, + CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, + MongoDataAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, + RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, + FlywayAutoConfiguration.class, MetricsAutoConfiguration.class }, excludeName = { "org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration" }) public static class Child { } - @EnableAutoConfiguration(exclude = { ElasticsearchDataAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, - MongoDataAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, - Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, - RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, - FlywayAutoConfiguration.class, MetricsAutoConfiguration.class }, + @EnableAutoConfiguration( + exclude = { ElasticsearchDataAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, + CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, + MongoDataAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, + RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, + FlywayAutoConfiguration.class, MetricsAutoConfiguration.class }, excludeName = { "org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration" }) public static class Parent { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java index 997eebf4b87..1d171fdb553 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java @@ -36,21 +36,18 @@ public class RabbitHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, - RabbitHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + RabbitHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(RabbitHealthIndicator.class) + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RabbitHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(RabbitHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java index a5d75e608b3..c67b40eabe0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java @@ -51,49 +51,37 @@ public class AuditAutoConfigurationTests { @Test public void autoConfigurationIsDisabledByDefault() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(AuditAutoConfiguration.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditAutoConfiguration.class)); } @Test public void autoConfigurationIsEnabledWhenAuditEventRepositoryBeanPresent() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .run((context) -> { - assertThat(context.getBean(AuditEventRepository.class)).isNotNull(); - assertThat(context.getBean(AuthenticationAuditListener.class)) - .isNotNull(); - assertThat(context.getBean(AuthorizationAuditListener.class)) - .isNotNull(); - }); + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class).run((context) -> { + assertThat(context.getBean(AuditEventRepository.class)).isNotNull(); + assertThat(context.getBean(AuthenticationAuditListener.class)).isNotNull(); + assertThat(context.getBean(AuthorizationAuditListener.class)).isNotNull(); + }); } @Test public void ownAuthenticationAuditListener() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration( - CustomAuthenticationAuditListenerConfiguration.class) - .run((context) -> assertThat( - context.getBean(AbstractAuthenticationAuditListener.class)) - .isInstanceOf(TestAuthenticationAuditListener.class)); + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) + .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) + .isInstanceOf(TestAuthenticationAuditListener.class)); } @Test public void ownAuthorizationAuditListener() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration( - CustomAuthorizationAuditListenerConfiguration.class) - .run((context) -> assertThat( - context.getBean(AbstractAuthorizationAuditListener.class)) - .isInstanceOf(TestAuthorizationAuditListener.class)); + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) + .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) + .isInstanceOf(TestAuthorizationAuditListener.class)); } @Test public void ownAuditListener() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withUserConfiguration(CustomAuditListenerConfiguration.class) .run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) .isInstanceOf(TestAuditListener.class)); @@ -101,8 +89,7 @@ public class AuditAutoConfigurationTests { @Test public void backsOffWhenDisabled() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withPropertyValues("management.auditevents.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) .doesNotHaveBean(AuthenticationAuditListener.class) @@ -133,8 +120,7 @@ public class AuditAutoConfigurationTests { } - protected static class TestAuthenticationAuditListener - extends AbstractAuthenticationAuditListener { + protected static class TestAuthenticationAuditListener extends AbstractAuthenticationAuditListener { @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { @@ -156,8 +142,7 @@ public class AuditAutoConfigurationTests { } - protected static class TestAuthorizationAuditListener - extends AbstractAuthorizationAuditListener { + protected static class TestAuthorizationAuditListener extends AbstractAuthorizationAuditListener { @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java index c6f00ae0d0f..68d2bc210ca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java @@ -36,43 +36,33 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class AuditEventsEndpointAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class, - AuditEventsEndpointAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(AuditAutoConfiguration.class, AuditEventsEndpointAutoConfiguration.class)); @Test public void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues( - "management.endpoints.web.exposure.include=auditevents") - .run((context) -> assertThat(context) - .hasSingleBean(AuditEventsEndpoint.class)); + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) + .withPropertyValues("management.endpoints.web.exposure.include=auditevents") + .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); } @Test public void endpointBacksOffWhenRepositoryNotAvailable() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.exposure.include=auditevents") - .run((context) -> assertThat(context) - .doesNotHaveBean(AuditEventsEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=auditevents") + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(AuditEventsEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { - this.contextRunner - .withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) + this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withPropertyValues("management.endpoint.auditevents.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context) - .doesNotHaveBean(AuditEventsEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java index d06964a2530..565e3bbda16 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java @@ -32,28 +32,24 @@ import static org.assertj.core.api.Assertions.assertThat; public class BeansEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=beans") + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=beans") .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context) - .doesNotHaveBean(BeansEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java index 98b3335443e..15c5f1f21e6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java @@ -35,30 +35,25 @@ import static org.mockito.Mockito.mock; public class CachesEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) .withPropertyValues("management.endpoints.web.exposure.include=caches") - .run((context) -> assertThat(context) - .hasSingleBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test public void runWithoutCacheManagerShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=caches") - .run((context) -> assertThat(context) - .hasSingleBean(CachesEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches") + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test @@ -66,8 +61,7 @@ public class CachesEndpointAutoConfigurationTests { this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") .withBean(CacheManager.class, () -> mock(CacheManager.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java index 5c8c8efcba6..ce89d84f093 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java @@ -40,21 +40,18 @@ public class CassandraHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class, - CassandraHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + CassandraHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(CassandraHealthIndicator.class) + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(CassandraHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(CassandraHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java index eb280ed0038..dab6f68778c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java @@ -38,25 +38,20 @@ import static org.mockito.Mockito.mock; public class CassandraReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(ReactiveCassandraOperations.class, - () -> mock(ReactiveCassandraOperations.class)) - .withConfiguration(AutoConfigurations.of( - CassandraReactiveHealthIndicatorAutoConfiguration.class, + .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) + .withConfiguration(AutoConfigurations.of(CassandraReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(CassandraReactiveHealthIndicator.class) - .doesNotHaveBean(CassandraHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraReactiveHealthIndicator.class) + .doesNotHaveBean(CassandraHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(CassandraReactiveHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(CassandraReactiveHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java index 05aa0e42a91..2976bcf1054 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java @@ -32,50 +32,43 @@ public class CloudFoundryAuthorizationExceptionTests { @Test public void statusCodeForInvalidTokenReasonShouldBe401() { - assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForInvalidIssuerReasonShouldBe401() { - assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForInvalidAudienceReasonShouldBe401() { - assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForInvalidSignatureReasonShouldBe401() { - assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForMissingAuthorizationReasonShouldBe401() { - assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() { - assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM) - .getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - } - - @Test - public void statusCodeForTokenExpiredReasonShouldBe401() { - assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()) + assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode()) .isEqualTo(HttpStatus.UNAUTHORIZED); } + @Test + public void statusCodeForTokenExpiredReasonShouldBe401() { + assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + } + @Test public void statusCodeForAccessDeniedReasonShouldBe403() { - assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()) - .isEqualTo(HttpStatus.FORBIDDEN); + assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java index 82c344c3950..bb51b9f216a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java @@ -36,16 +36,14 @@ public class CloudFoundryEndpointFilterTests { @Test public void matchIfDiscovererCloudFoundryShouldReturnFalse() { DiscoveredEndpoint endpoint = mock(DiscoveredEndpoint.class); - given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)) - .willReturn(true); + given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(true); assertThat(this.filter.match(endpoint)).isTrue(); } @Test public void matchIfDiscovererNotCloudFoundryShouldReturnFalse() { DiscoveredEndpoint endpoint = mock(DiscoveredEndpoint.class); - given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)) - .willReturn(false); + given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(false); assertThat(this.filter.match(endpoint)).isFalse(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java index f4d468b3f22..d01247aa808 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java @@ -60,8 +60,8 @@ public class CloudFoundryWebEndpointDiscovererTests { for (ExposableWebEndpoint endpoint : endpoints) { if (endpoint.getEndpointId().equals(EndpointId.of("health"))) { WebOperation operation = findMainReadOperation(endpoint); - assertThat(operation.invoke(new InvocationContext( - mock(SecurityContext.class), Collections.emptyMap()))) + assertThat(operation + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap()))) .isEqualTo("cf"); } } @@ -74,30 +74,23 @@ public class CloudFoundryWebEndpointDiscovererTests { return operation; } } - throw new IllegalStateException( - "No main read operation found from " + endpoint.getOperations()); + throw new IllegalStateException("No main read operation found from " + endpoint.getOperations()); } - private void load(Class configuration, - Consumer consumer) { + private void load(Class configuration, Consumer consumer) { this.load((id) -> null, EndpointId::toString, configuration, consumer); } - private void load(Function timeToLive, - PathMapper endpointPathMapper, Class configuration, + private void load(Function timeToLive, PathMapper endpointPathMapper, Class configuration, Consumer consumer) { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - configuration)) { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { ConversionServiceParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - EndpointMediaTypes mediaTypes = new EndpointMediaTypes( - Collections.singletonList("application/json"), + EndpointMediaTypes mediaTypes = new EndpointMediaTypes(Collections.singletonList("application/json"), Collections.singletonList("application/json")); - CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer( - context, parameterMapper, mediaTypes, - Collections.singletonList(endpointPathMapper), - Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), - Collections.emptyList()); + CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer(context, + parameterMapper, mediaTypes, Collections.singletonList(endpointPathMapper), + Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), Collections.emptyList()); consumer.accept(discoverer); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java index 30d272da265..2de8cd82f8a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java @@ -35,8 +35,7 @@ public class TokenTests { @Test public void invalidJwtShouldThrowException() { - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token("invalid-token")) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token("invalid-token")) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -45,8 +44,8 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) - + "." + Base64Utils.encodeToString(claims.getBytes()))) + .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + "." + + Base64Utils.encodeToString(claims.getBytes()))) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -55,8 +54,8 @@ public class TokenTests { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) - + "." + Base64Utils.encodeToString(claims.getBytes()))) + .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + "." + + Base64Utils.encodeToString(claims.getBytes()))) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -64,8 +63,7 @@ public class TokenTests { public void emptyJwtSignatureShouldThrowException() { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(token)) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token(token)) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -82,8 +80,7 @@ public class TokenTests { assertThat(token.getSignatureAlgorithm()).isEqualTo("RS256"); assertThat(token.getKeyId()).isEqualTo("key-id"); assertThat(token.getContent()).isEqualTo(content.getBytes()); - assertThat(token.getSignature()) - .isEqualTo(Base64Utils.decodeFromString(signature)); + assertThat(token.getSignature()).isEqualTo(Base64Utils.decodeFromString(signature)); } @Test @@ -91,8 +88,7 @@ public class TokenTests { String header = "{\"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(token::getSignatureAlgorithm) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getSignatureAlgorithm) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -101,8 +97,7 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(token::getIssuer) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getIssuer) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -111,8 +106,7 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(token::getKeyId) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getKeyId) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -121,20 +115,18 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"" + "}"; Token token = createToken(header, claims); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(token::getExpiry) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getExpiry) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } private Token createToken(String header, String claims) { - Token token = new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes()) + "." - + Base64Utils.encodeToString("signature".getBytes())); + Token token = new Token( + Base64Utils.encodeToString(header.getBytes()) + "." + Base64Utils.encodeToString(claims.getBytes()) + + "." + Base64Utils.encodeToString("signature".getBytes())); return token; } - private Consumer reasonRequirement( - Reason reason) { + private Consumer reasonRequirement(Reason reason) { return (ex) -> assertThat(ex.getReason()).isEqualTo(reason); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java index 4bf9573f7f9..53a91f548f5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java @@ -46,18 +46,14 @@ public class CloudFoundryReactiveHealthEndpointWebExtensionTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of( - ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, - WebFluxAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfigurationTests.WebClientCustomizerConfig.class, - WebClientAutoConfiguration.class, - ManagementContextAutoConfiguration.class, + WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, + HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); @Test @@ -65,8 +61,7 @@ public class CloudFoundryReactiveHealthEndpointWebExtensionTests { this.contextRunner.run((context) -> { CloudFoundryReactiveHealthEndpointWebExtension extension = context .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); - assertThat(extension.health().block(Duration.ofSeconds(30)).getBody() - .getDetails()).isNotEmpty(); + assertThat(extension.health().block(Duration.ofSeconds(30)).getBody().getDetails()).isNotEmpty(); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java index 16fee052f04..80c140e241d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java @@ -70,109 +70,88 @@ import static org.mockito.Mockito.mock; */ public class CloudFoundryWebFluxEndpointIntegrationTests { - private static ReactiveTokenValidator tokenValidator = mock( - ReactiveTokenValidator.class); + private static ReactiveTokenValidator tokenValidator = mock(ReactiveTokenValidator.class); private static ReactiveCloudFoundrySecurityService securityService = mock( ReactiveCloudFoundrySecurityService.class); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(TestEndpointConfiguration.class) - .withPropertyValues("server.port=0"); + .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, + HttpHandlerAutoConfiguration.class, ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(TestEndpointConfiguration.class).withPropertyValues("server.port=0"); @Test public void operationWithSecurityInterceptorForbidden() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(Mono.just(AccessLevel.RESTRICTED)); - this.contextRunner.run(withWebTestClient((client) -> client.get() - .uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); + this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() .expectStatus().isEqualTo(HttpStatus.FORBIDDEN))); } @Test public void operationWithSecurityInterceptorSuccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(Mono.just(AccessLevel.FULL)); - this.contextRunner.run(withWebTestClient((client) -> client.get() - .uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); + this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() .expectStatus().isEqualTo(HttpStatus.OK))); } @Test public void responseToOptionsRequestIncludesCorsHeaders() { - this.contextRunner.run(withWebTestClient((client) -> client.options() - .uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST") - .header("Origin", "https://example.com").exchange().expectStatus().isOk() - .expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com") - .expectHeader().valueEquals("Access-Control-Allow-Methods", "GET,POST"))); + this.contextRunner.run(withWebTestClient((client) -> client.options().uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON).header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com").exchange().expectStatus().isOk().expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST"))); } @Test public void linksToOtherEndpointsWithFullAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(Mono.just(AccessLevel.FULL)); - this.contextRunner.run(withWebTestClient((client) -> client.get() - .uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isOk().expectBody().jsonPath("_links.length()") - .isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false) - .jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false) - .jsonPath("_links.env.href").isNotEmpty().jsonPath("_links.env.templated") - .isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false) - .jsonPath("_links.test-part.href").isNotEmpty() - .jsonPath("_links.test-part.templated").isEqualTo(true))); + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); + this.contextRunner + .run(withWebTestClient((client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() + .expectBody().jsonPath("_links.length()").isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() + .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() + .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env.href").isNotEmpty() + .jsonPath("_links.env.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() + .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") + .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true))); } @Test public void linksToOtherEndpointsForbidden() { - CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException( - Reason.INVALID_TOKEN, "invalid-token"); + CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, + "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); - this.contextRunner.run(withWebTestClient((client) -> client.get() - .uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() + this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() .expectStatus().isUnauthorized())); } @Test public void linksToOtherEndpointsWithRestrictedAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(Mono.just(AccessLevel.RESTRICTED)); - this.contextRunner.run(withWebTestClient((client) -> client.get() - .uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isOk().expectBody().jsonPath("_links.length()") - .isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false) - .jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env") - .doesNotExist().jsonPath("_links.test").doesNotExist() - .jsonPath("_links.test-part").doesNotExist())); + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); + this.contextRunner + .run(withWebTestClient((client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() + .expectBody().jsonPath("_links.length()").isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() + .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() + .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env").doesNotExist() + .jsonPath("_links.test").doesNotExist().jsonPath("_links.test-part").doesNotExist())); } private ContextConsumer withWebTestClient( Consumer clientConsumer) { return (context) -> { - int port = ((AnnotationConfigReactiveWebServerApplicationContext) context - .getSourceApplicationContext()).getWebServer().getPort(); - clientConsumer.accept(WebTestClient.bindToServer() - .baseUrl("http://localhost:" + port).build()); + int port = ((AnnotationConfigReactiveWebServerApplicationContext) context.getSourceApplicationContext()) + .getWebServer().getPort(); + clientConsumer.accept(WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build()); }; } @@ -187,8 +166,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { @Bean public CloudFoundrySecurityInterceptor interceptor() { - return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, - "app-id"); + return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, "app-id"); } @Bean @@ -199,28 +177,23 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { @Bean public CloudFoundryWebFluxEndpointHandlerMapping cloudFoundryWebEndpointServletHandlerMapping( - WebEndpointDiscoverer webEndpointDiscoverer, - EndpointMediaTypes endpointMediaTypes, + WebEndpointDiscoverer webEndpointDiscoverer, EndpointMediaTypes endpointMediaTypes, CloudFoundrySecurityInterceptor interceptor) { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedOrigins(Arrays.asList("https://example.com")); corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST")); - return new CloudFoundryWebFluxEndpointHandlerMapping( - new EndpointMapping("/cfApplication"), - webEndpointDiscoverer.getEndpoints(), endpointMediaTypes, - corsConfiguration, interceptor, + return new CloudFoundryWebFluxEndpointHandlerMapping(new EndpointMapping("/cfApplication"), + webEndpointDiscoverer.getEndpoints(), endpointMediaTypes, corsConfiguration, interceptor, new EndpointLinksResolver(webEndpointDiscoverer.getEndpoints())); } @Bean - public WebEndpointDiscoverer webEndpointDiscoverer( - ApplicationContext applicationContext, + public WebEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext, EndpointMediaTypes endpointMediaTypes) { ParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - return new WebEndpointDiscoverer(applicationContext, parameterMapper, - endpointMediaTypes, null, Collections.emptyList(), - Collections.emptyList()); + return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes, null, + Collections.emptyList(), Collections.emptyList()); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java index 15ae66c1a74..ece5cdecbec 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java @@ -81,21 +81,15 @@ import static org.mockito.Mockito.mock; public class ReactiveCloudFoundryActuatorAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, - WebFluxAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - WebClientCustomizerConfig.class, WebClientAutoConfiguration.class, - ManagementContextAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, WebClientCustomizerConfig.class, + WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, - InfoContributorAutoConfiguration.class, - InfoEndpointAutoConfiguration.class, - ProjectInfoAutoConfiguration.class, - ReactiveCloudFoundryActuatorAutoConfiguration.class)); + HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + ProjectInfoAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); @AfterEach public void close() { @@ -104,90 +98,67 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test public void cloudFoundryPlatformActive() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils - .getField(handlerMapping, "endpointMapping"); - assertThat(endpointMapping.getPath()) - .isEqualTo("/cloudfoundryapplication"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, + "endpointMapping"); + assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils .getField(handlerMapping, "corsConfiguration"); assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()).containsAll( - Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); assertThat(corsConfiguration.getAllowedHeaders()) - .containsAll(Arrays.asList("Authorization", - "X-Cf-App-Instance", "Content-Type")); + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); }); } @Test public void cloudfoundryapplicationProducesActuatorMediaType() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - WebTestClient webTestClient = WebTestClient - .bindToApplicationContext(context).build(); - webTestClient.get().uri("/cloudfoundryapplication").header( - "Content-Type", ActuatorMediaType.V2_JSON + ";charset=UTF-8"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); + webTestClient.get().uri("/cloudfoundryapplication").header("Content-Type", + ActuatorMediaType.V2_JSON + ";charset=UTF-8"); }); } @Test public void cloudFoundryPlatformActiveSetsApplicationId() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils - .getField(interceptor, "applicationId"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); assertThat(applicationId).isEqualTo("my-app-id"); }); } @Test public void cloudFoundryPlatformActiveSetsCloudControllerUrl() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(interceptor, "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils - .getField(interceptorSecurityService, "cloudControllerUrl"); - assertThat(cloudControllerUrl) - .isEqualTo("https://my-cloud-controller.com"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); + assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); }); } @Test public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context - .getBean("cloudFoundryWebFluxEndpointHandlerMapping", - CloudFoundryWebFluxEndpointHandlerMapping.class); - Object securityInterceptor = ReflectionTestUtils - .getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(securityInterceptor, "cloudFoundrySecurityService"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( + "cloudFoundryWebFluxEndpointHandlerMapping", + CloudFoundryWebFluxEndpointHandlerMapping.class); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); assertThat(interceptorSecurityService).isNull(); }); } @@ -195,28 +166,22 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test @SuppressWarnings("unchecked") public void cloudFoundryPathsIgnoredBySpringSecurity() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - WebFilterChainProxy chainProxy = context - .getBean(WebFilterChainProxy.class); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); List filters = (List) ReflectionTestUtils .getField(chainProxy, "filters"); Boolean cfRequestMatches = filters.get(0) - .matches(MockServerWebExchange.from(MockServerHttpRequest - .get("/cloudfoundryapplication/my-path").build())) + .matches(MockServerWebExchange + .from(MockServerHttpRequest.get("/cloudfoundryapplication/my-path").build())) .block(Duration.ofSeconds(30)); Boolean otherRequestMatches = filters.get(0) - .matches(MockServerWebExchange.from(MockServerHttpRequest - .get("/some-other-path").build())) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) .block(Duration.ofSeconds(30)); assertThat(cfRequestMatches).isTrue(); assertThat(otherRequestMatches).isFalse(); otherRequestMatches = filters.get(1) - .matches(MockServerWebExchange.from(MockServerHttpRequest - .get("/some-other-path").build())) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) .block(Duration.ofSeconds(30)); assertThat(otherRequestMatches).isTrue(); }); @@ -225,34 +190,24 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test public void cloudFoundryPlatformInactive() { - this.contextRunner.run((context) -> assertThat( - context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")) - .isFalse()); + this.contextRunner.run( + (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test public void cloudFoundryManagementEndpointsDisabled() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION=---", - "management.cloudfoundry.enabled:false") - .run((context) -> assertThat( - context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")) - .isFalse()); + this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false").run( + (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test public void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", + "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - Collection endpoints = handlerMapping - .getEndpoints(); - List endpointIds = endpoints.stream() - .map(ExposableEndpoint::getEndpointId) + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + List endpointIds = endpoints.stream().map(ExposableEndpoint::getEndpointId) .collect(Collectors.toList()); assertThat(endpointIds).contains(EndpointId.of("test")); }); @@ -260,46 +215,33 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test public void endpointPathCustomizationIsNotApplied() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", + "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - Collection endpoints = handlerMapping - .getEndpoints(); + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); ExposableWebEndpoint endpoint = endpoints.stream() - .filter((candidate) -> EndpointId.of("test") - .equals(candidate.getEndpointId())) - .findFirst().get(); + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst() + .get(); assertThat(endpoint.getOperations()).hasSize(1); WebOperation operation = endpoint.getOperations().iterator().next(); - assertThat(operation.getRequestPredicate().getPath()) - .isEqualTo("test"); + assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); }); } @Test public void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", + this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { - Collection endpoints = getHandlerMapping( - context).getEndpoints(); + Collection endpoints = getHandlerMapping(context).getEndpoints(); ExposableWebEndpoint endpoint = endpoints.iterator().next(); assertThat(endpoint.getOperations()).hasSize(3); - WebOperation webOperation = findOperationWithRequestPath(endpoint, - "health"); - Object invoker = ReflectionTestUtils.getField(webOperation, - "invoker"); + WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); + Object invoker = ReflectionTestUtils.getField(webOperation, "invoker"); assertThat(ReflectionTestUtils.getField(invoker, "target")) - .isInstanceOf( - CloudFoundryReactiveHealthEndpointWebExtension.class); + .isInstanceOf(CloudFoundryReactiveHealthEndpointWebExtension.class); }); } @@ -317,67 +259,52 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test public void skipSslValidation() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", + this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com", "management.cloudfoundry.skip-ssl-validation:true") .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(interceptor, "cloudFoundrySecurityService"); - WebClient webClient = (WebClient) ReflectionTestUtils - .getField(interceptorSecurityService, "webClient"); - webClient.get().uri("https://self-signed.badssl.com/").exchange() - .block(Duration.ofSeconds(30)); + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, + "webClient"); + webClient.get().uri("https://self-signed.badssl.com/").exchange().block(Duration.ofSeconds(30)); }); } @Test public void sslValidationNotSkippedByDefault() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", + this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(interceptor, "cloudFoundrySecurityService"); - WebClient webClient = (WebClient) ReflectionTestUtils - .getField(interceptorSecurityService, "webClient"); - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> webClient.get() - .uri("https://self-signed.badssl.com/").exchange() - .block(Duration.ofSeconds(30))) + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, + "webClient"); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> webClient.get() + .uri("https://self-signed.badssl.com/").exchange().block(Duration.ofSeconds(30))) .withCauseInstanceOf(SSLException.class); }); } - private CloudFoundryWebFluxEndpointHandlerMapping getHandlerMapping( - ApplicationContext context) { + private CloudFoundryWebFluxEndpointHandlerMapping getHandlerMapping(ApplicationContext context) { return context.getBean("cloudFoundryWebFluxEndpointHandlerMapping", CloudFoundryWebFluxEndpointHandlerMapping.class); } - private WebOperation findOperationWithRequestPath(ExposableWebEndpoint endpoint, - String requestPath) { + private WebOperation findOperationWithRequestPath(ExposableWebEndpoint endpoint, String requestPath) { for (WebOperation operation : endpoint.getOperations()) { if (operation.getRequestPredicate().getPath().equals(requestPath)) { return operation; } } - throw new IllegalStateException("No operation found with request path " - + requestPath + " from " + endpoint.getOperations()); + throw new IllegalStateException( + "No operation found with request path " + requestPath + " from " + endpoint.getOperations()); } @Endpoint(id = "test") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java index 9a5961504da..9ffe2ed2d6b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java @@ -54,62 +54,54 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, - this.securityService, "my-app-id"); + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, "my-app-id"); } @Test public void preHandleWhenRequestIsPreFlightShouldBeOk() { - MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest - .options("/a").header(HttpHeaders.ORIGIN, "https://example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(HttpStatus.OK)) + MockServerWebExchange request = MockServerWebExchange + .from(MockServerHttpRequest.options("/a").header(HttpHeaders.ORIGIN, "https://example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(HttpStatus.OK)) .verifyComplete(); } @Test public void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() { - MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a").build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith((response) -> assertThat(response.getStatus()) - .isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) + MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a").build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) .verifyComplete(); } @Test public void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() { - MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest - .get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith((response) -> assertThat(response.getStatus()) - .isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) + MockServerWebExchange request = MockServerWebExchange + .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) .verifyComplete(); } @Test public void preHandleWhenApplicationIdIsNullShouldReturnError() { - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, - this.securityService, null); - MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) - .build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeErrorWith( - (ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); + MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) .isEqualTo(Reason.SERVICE_UNAVAILABLE)) .verify(); } @Test public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() { - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, - "my-app-id"); - MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest - .get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeErrorWith( - (ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); + MockServerWebExchange request = MockServerWebExchange + .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) .isEqualTo(Reason.SERVICE_UNAVAILABLE)) .verify(); } @@ -119,33 +111,25 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { given(this.securityService.getAccessLevel(mockAccessToken(), "my-app-id")) .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); - MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) - .build()); + MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith((response) -> assertThat(response.getStatus()) - .isEqualTo(Reason.ACCESS_DENIED.getStatus())) + .consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus())) .verifyComplete(); } @Test public void preHandleSuccessfulWithFullAccess() { String accessToken = mockAccessToken(); - given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(Mono.just(AccessLevel.FULL)); + given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(Mono.just(AccessLevel.FULL)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) - .build()); - StepVerifier.create(this.interceptor.preHandle(exchange, "/a")) - .consumeNextWith((response) -> { - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); - assertThat((AccessLevel) exchange - .getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.FULL); - }).verifyComplete(); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/a") + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(exchange, "/a")).consumeNextWith((response) -> { + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); + assertThat((AccessLevel) exchange.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL); + }).verifyComplete(); } @Test @@ -154,17 +138,13 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { given(this.securityService.getAccessLevel(accessToken, "my-app-id")) .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/info") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) - .build()); - StepVerifier.create(this.interceptor.preHandle(exchange, "info")) - .consumeNextWith((response) -> { - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); - assertThat((AccessLevel) exchange - .getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.RESTRICTED); - }).verifyComplete(); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/info") + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(exchange, "info")).consumeNextWith((response) -> { + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); + assertThat((AccessLevel) exchange.getAttribute("cloudFoundryAccessLevel")) + .isEqualTo(AccessLevel.RESTRICTED); + }).verifyComplete(); } private String mockAccessToken() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java index 8a6573ddb86..f82f3777ac3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java @@ -43,8 +43,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { private static final String CLOUD_CONTROLLER = "/my-cloud-controller.com"; - private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER - + "/v2/apps/my-app-id/permissions"; + private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER + "/v2/apps/my-app-id/permissions"; private static final String UAA_URL = "https://my-cloud-controller.com/uaa"; @@ -58,8 +57,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { public void setup() { this.server = new MockWebServer(); this.builder = WebClient.builder().baseUrl(this.server.url("/").toString()); - this.securityService = new ReactiveCloudFoundrySecurityService(this.builder, - CLOUD_CONTROLLER, false); + this.securityService = new ReactiveCloudFoundrySecurityService(this.builder, CLOUD_CONTROLLER, false); } @AfterEach @@ -70,36 +68,25 @@ public class ReactiveCloudFoundrySecurityServiceTests { @Test public void getAccessLevelWhenSpaceDeveloperShouldReturnFull() throws Exception { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; - prepareResponse((response) -> response.setBody(responseBody) - .setHeader("Content-Type", "application/json")); - StepVerifier - .create(this.securityService.getAccessLevel("my-access-token", - "my-app-id")) - .consumeNextWith((accessLevel) -> assertThat(accessLevel) - .isEqualTo(AccessLevel.FULL)) - .expectComplete().verify(); + prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); + StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.FULL)).expectComplete() + .verify(); expectRequest((request) -> { - assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)) - .isEqualTo("bearer my-access-token"); + assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); }); } @Test - public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() - throws Exception { + public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; - prepareResponse((response) -> response.setBody(responseBody) - .setHeader("Content-Type", "application/json")); - StepVerifier - .create(this.securityService.getAccessLevel("my-access-token", - "my-app-id")) - .consumeNextWith((accessLevel) -> assertThat(accessLevel) - .isEqualTo(AccessLevel.RESTRICTED)) + prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); + StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED)) .expectComplete().verify(); expectRequest((request) -> { - assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)) - .isEqualTo("bearer my-access-token"); + assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); }); } @@ -107,18 +94,14 @@ public class ReactiveCloudFoundrySecurityServiceTests { @Test public void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(401)); - StepVerifier.create( - this.securityService.getAccessLevel("my-access-token", "my-app-id")) + StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) .consumeErrorWith((throwable) -> { - assertThat(throwable) - .isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat( - ((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.INVALID_TOKEN); + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.INVALID_TOKEN); }).verify(); expectRequest((request) -> { - assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)) - .isEqualTo("bearer my-access-token"); + assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); }); } @@ -126,45 +109,35 @@ public class ReactiveCloudFoundrySecurityServiceTests { @Test public void getAccessLevelWhenForbiddenShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(403)); - StepVerifier.create( - this.securityService.getAccessLevel("my-access-token", "my-app-id")) + StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) .consumeErrorWith((throwable) -> { - assertThat(throwable) - .isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat( - ((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.ACCESS_DENIED); + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.ACCESS_DENIED); }).verify(); expectRequest((request) -> { - assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)) - .isEqualTo("bearer my-access-token"); + assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); }); } @Test - public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() - throws Exception { + public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { prepareResponse((response) -> response.setResponseCode(500)); - StepVerifier.create( - this.securityService.getAccessLevel("my-access-token", "my-app-id")) + StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) .consumeErrorWith((throwable) -> { - assertThat(throwable) - .isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat( - ((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE); + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE); }).verify(); expectRequest((request) -> { - assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)) - .isEqualTo("bearer my-access-token"); + assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); }); } @Test - public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() - throws Exception { + public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() throws Exception { String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" + "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" @@ -177,20 +150,17 @@ public class ReactiveCloudFoundrySecurityServiceTests { response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}"); response.setHeader("Content-Type", "application/json"); }); - String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" - + tokenKeyValue.replace("\n", "\\n") + "\"} ]}"; + String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" + tokenKeyValue.replace("\n", "\\n") + + "\"} ]}"; prepareResponse((response) -> { response.setBody(responseBody); response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeNextWith((tokenKeys) -> assertThat(tokenKeys.get("test-key")) - .isEqualTo(tokenKeyValue)) + .consumeNextWith((tokenKeys) -> assertThat(tokenKeys.get("test-key")).isEqualTo(tokenKeyValue)) .expectComplete().verify(); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo("/my-cloud-controller.com/info")); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo("/my-uaa.com/token_keys")); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @Test @@ -205,12 +175,9 @@ public class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeNextWith((tokenKeys) -> assertThat(tokenKeys).hasSize(0)) - .expectComplete().verify(); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo("/my-cloud-controller.com/info")); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo("/my-uaa.com/token_keys")); + .consumeNextWith((tokenKeys) -> assertThat(tokenKeys).hasSize(0)).expectComplete().verify(); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @Test @@ -221,14 +188,12 @@ public class ReactiveCloudFoundrySecurityServiceTests { }); prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeErrorWith((throwable) -> assertThat( - ((CloudFoundryAuthorizationException) throwable).getReason()) + .consumeErrorWith( + (throwable) -> assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) .isEqualTo(Reason.SERVICE_UNAVAILABLE)) .verify(); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo("/my-cloud-controller.com/info")); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo("/my-uaa.com/token_keys")); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @Test @@ -238,29 +203,22 @@ public class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.getUaaUrl()) - .consumeNextWith((uaaUrl) -> assertThat(uaaUrl).isEqualTo(UAA_URL)) - .expectComplete().verify(); + .consumeNextWith((uaaUrl) -> assertThat(uaaUrl).isEqualTo(UAA_URL)).expectComplete().verify(); // this.securityService.getUaaUrl().block(); //FIXME subscribe again to check that // it isn't called again - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo(CLOUD_CONTROLLER + "/info")); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER + "/info")); expectRequestCount(1); } @Test - public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() - throws Exception { + public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(500)); - StepVerifier.create(this.securityService.getUaaUrl()) - .consumeErrorWith((throwable) -> { - assertThat(throwable) - .isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat( - ((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE); - }).verify(); - expectRequest((request) -> assertThat(request.getPath()) - .isEqualTo(CLOUD_CONTROLLER + "/info")); + StepVerifier.create(this.securityService.getUaaUrl()).consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE); + }).verify(); + expectRequest((request) -> assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER + "/info")); } private void prepareResponse(Consumer consumer) { @@ -269,8 +227,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { this.server.enqueue(response); } - private void expectRequest(Consumer consumer) - throws InterruptedException { + private void expectRequest(Consumer consumer) throws InterruptedException { consumer.accept(this.server.takeRequest()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java index 9003eebd65d..a47392410b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java @@ -92,90 +92,66 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() - throws Exception { - PublisherProbe> fetchTokenKeys = PublisherProbe - .of(Mono.just(VALID_KEYS)); + public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { + PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{\"alg\": \"RS256\", \"kid\": \"invalid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_KEY_ID); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); }).verify(); - assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", - VALID_KEYS); + assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @Test - public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() - throws Exception { - PublisherProbe> fetchTokenKeys = PublisherProbe - .of(Mono.just(VALID_KEYS)); - ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", - INVALID_KEYS); + public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { + PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); + ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .verifyComplete(); - assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", - VALID_KEYS); + assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @Test public void validateTokenWhenCacheIsEmptyShouldFetchTokenKeys() throws Exception { - PublisherProbe> fetchTokenKeys = PublisherProbe - .of(Mono.just(VALID_KEYS)); + PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .verifyComplete(); - assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", - VALID_KEYS); + assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @Test - public void validateTokenWhenCacheEmptyAndInvalidKeyShouldThrowException() - throws Exception { - PublisherProbe> fetchTokenKeys = PublisherProbe - .of(Mono.just(VALID_KEYS)); + public void validateTokenWhenCacheEmptyAndInvalidKeyShouldThrowException() throws Exception { + PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{\"alg\": \"RS256\", \"kid\": \"invalid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_KEY_ID); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); }).verify(); - assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", - VALID_KEYS); + assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -184,13 +160,11 @@ public class ReactiveTokenValidatorTests { PublisherProbe> fetchTokenKeys = PublisherProbe.empty(); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .verifyComplete(); fetchTokenKeys.assertWasNotSubscribed(); } @@ -199,35 +173,28 @@ public class ReactiveTokenValidatorTests { public void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { Map KEYS = Collections.singletonMap("valid-key", INVALID_KEY); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(KEYS)); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); assertThat(((CloudFoundryAuthorizationException) ex).getReason()) .isEqualTo(Reason.INVALID_SIGNATURE); }).verify(); } @Test - public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() - throws Exception { + public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"HS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); assertThat(((CloudFoundryAuthorizationException) ex).getReason()) .isEqualTo(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM); }).verify(); @@ -236,53 +203,41 @@ public class ReactiveTokenValidatorTests { @Test public void validateTokenWhenExpiredShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.TOKEN_EXPIRED); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.TOKEN_EXPIRED); }).verify(); } @Test public void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("https://other-uaa.com")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("https://other-uaa.com")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_ISSUER); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_ISSUER); }).verify(); } @Test - public void validateTokenWhenAudienceIsNotValidShouldThrowException() - throws Exception { + public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); - given(this.securityService.getUaaUrl()) - .willReturn(Mono.just("http://localhost:8080/uaa")); + given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; StepVerifier - .create(this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf( - CloudFoundryAuthorizationException.class); + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); assertThat(((CloudFoundryAuthorizationException) ex).getReason()) .isEqualTo(Reason.INVALID_AUDIENCE); }).verify(); @@ -292,17 +247,15 @@ public class ReactiveTokenValidatorTests { PrivateKey privateKey = getPrivateKey(); Signature signature = Signature.getInstance("SHA256WithRSA"); signature.initSign(privateKey); - byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), - Base64Utils.encode(claims)); + byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims)); signature.update(content); byte[] crypto = signature.sign(); - byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), - Base64Utils.encodeUrlSafe(claims), Base64Utils.encodeUrlSafe(crypto)); + byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims), + Base64Utils.encodeUrlSafe(crypto)); return new String(token, StandardCharsets.UTF_8); } - private PrivateKey getPrivateKey() - throws InvalidKeySpecException, NoSuchAlgorithmException { + private PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException { String signingKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDSbn2Xa72IOcxu\n" + "tcd+qQ6ufZ1VDe98EmpwO4VQrTd37U9kZtWU0KqeSkgnyzIWmlbyWOdbB4/v4uJa\n" diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java index 610af2f6e10..51e305d1c9a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java @@ -67,107 +67,77 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class CloudFoundryActuatorAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - CloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test public void cloudFoundryPlatformActive() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils - .getField(handlerMapping, "endpointMapping"); - assertThat(endpointMapping.getPath()) - .isEqualTo("/cloudfoundryapplication"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, + "endpointMapping"); + assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils .getField(handlerMapping, "corsConfiguration"); assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()).containsAll( - Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); assertThat(corsConfiguration.getAllowedHeaders()) - .containsAll(Arrays.asList("Authorization", - "X-Cf-App-Instance", "Content-Type")); + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); }); } @Test public void cloudfoundryapplicationProducesActuatorMediaType() throws Exception { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/cloudfoundryapplication")).andExpect( - header().string("Content-Type", ActuatorMediaType.V2_JSON)); + mockMvc.perform(get("/cloudfoundryapplication")) + .andExpect(header().string("Content-Type", ActuatorMediaType.V2_JSON)); }); } @Test public void cloudFoundryPlatformActiveSetsApplicationId() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils - .getField(interceptor, "applicationId"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); assertThat(applicationId).isEqualTo("my-app-id"); }); } @Test public void cloudFoundryPlatformActiveSetsCloudControllerUrl() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(interceptor, "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils - .getField(interceptorSecurityService, "cloudControllerUrl"); - assertThat(cloudControllerUrl) - .isEqualTo("https://my-cloud-controller.com"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); + assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); }); } @Test public void skipSslValidation() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.cloudfoundry.skip-ssl-validation:true") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(interceptor, "cloudFoundrySecurityService"); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils - .getField(interceptorSecurityService, "restTemplate"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.cloudfoundry.skip-ssl-validation:true").run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService, + "restTemplate"); assertThat(restTemplate.getRequestFactory()) .isInstanceOf(SkipSslVerificationHttpRequestFactory.class); }); @@ -175,26 +145,23 @@ public class CloudFoundryActuatorAutoConfigurationTests { @Test public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - Object securityInterceptor = ReflectionTestUtils - .getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(securityInterceptor, "cloudFoundrySecurityService"); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); assertThat(interceptorSecurityService).isNull(); }); } @Test public void cloudFoundryPathsIgnoredBySpringSecurity() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id").run((context) -> { + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") + .run((context) -> { FilterChainProxy securityFilterChain = (FilterChainProxy) context .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); - SecurityFilterChain chain = securityFilterChain.getFilterChains() - .get(0); + SecurityFilterChain chain = securityFilterChain.getFilterChains().get(0); MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/cloudfoundryapplication/my-path"); assertThat(chain.getFilters()).isEmpty(); @@ -207,72 +174,54 @@ public class CloudFoundryActuatorAutoConfigurationTests { @Test public void cloudFoundryPlatformInactive() { this.contextRunner.withPropertyValues() - .run((context) -> assertThat(context - .containsBean("cloudFoundryWebEndpointServletHandlerMapping")) - .isFalse()); + .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) + .isFalse()); } @Test public void cloudFoundryManagementEndpointsDisabled() { - this.contextRunner - .withPropertyValues("VCAP_APPLICATION=---", - "management.cloudfoundry.enabled:false") - .run((context) -> assertThat( - context.containsBean("cloudFoundryEndpointHandlerMapping")) - .isFalse()); + this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") + .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); } @Test public void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", + "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - Collection endpoints = handlerMapping - .getEndpoints(); + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); assertThat(endpoints.stream() - .filter((candidate) -> EndpointId.of("test") - .equals(candidate.getEndpointId())) - .findFirst()).isNotEmpty(); + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst()) + .isNotEmpty(); }); } @Test public void endpointPathCustomizationIsNotApplied() { this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com", "management.endpoints.web.path-mapping.test=custom") .withBean(TestEndpoint.class, TestEndpoint::new).run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping( - context); - Collection endpoints = handlerMapping - .getEndpoints(); + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); ExposableWebEndpoint endpoint = endpoints.stream() - .filter((candidate) -> EndpointId.of("test") - .equals(candidate.getEndpointId())) - .findFirst().get(); + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst() + .get(); Collection operations = endpoint.getOperations(); assertThat(operations).hasSize(1); - assertThat( - operations.iterator().next().getRequestPredicate().getPath()) - .isEqualTo("test"); + assertThat(operations.iterator().next().getRequestPredicate().getPath()).isEqualTo("test"); }); } @Test public void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .withConfiguration( - AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class)) .run((context) -> { Collection endpoints = context .getBean("cloudFoundryWebEndpointServletHandlerMapping", @@ -280,30 +229,26 @@ public class CloudFoundryActuatorAutoConfigurationTests { .getEndpoints(); ExposableWebEndpoint endpoint = endpoints.iterator().next(); assertThat(endpoint.getOperations()).hasSize(3); - WebOperation webOperation = findOperationWithRequestPath(endpoint, - "health"); - Object invoker = ReflectionTestUtils.getField(webOperation, - "invoker"); + WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); + Object invoker = ReflectionTestUtils.getField(webOperation, "invoker"); assertThat(ReflectionTestUtils.getField(invoker, "target")) .isInstanceOf(CloudFoundryHealthEndpointWebExtension.class); }); } - private CloudFoundryWebEndpointServletHandlerMapping getHandlerMapping( - ApplicationContext context) { + private CloudFoundryWebEndpointServletHandlerMapping getHandlerMapping(ApplicationContext context) { return context.getBean("cloudFoundryWebEndpointServletHandlerMapping", CloudFoundryWebEndpointServletHandlerMapping.class); } - private WebOperation findOperationWithRequestPath(ExposableWebEndpoint endpoint, - String requestPath) { + private WebOperation findOperationWithRequestPath(ExposableWebEndpoint endpoint, String requestPath) { for (WebOperation operation : endpoint.getOperations()) { if (operation.getRequestPredicate().getPath().equals(requestPath)) { return operation; } } - throw new IllegalStateException("No operation found with request path " - + requestPath + " from " + endpoint.getOperations()); + throw new IllegalStateException( + "No operation found with request path " + requestPath + " from " + endpoint.getOperations()); } @Endpoint(id = "test") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java index dfb4569b079..a1c0c4d0c5e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java @@ -45,18 +45,13 @@ public class CloudFoundryHealthEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, - CloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test public void healthDetailsAlwaysPresent() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java index ce2d38ef0c9..ab5de36220c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java @@ -50,32 +50,23 @@ public class CloudFoundryInfoEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ProjectInfoAutoConfiguration.class, - InfoContributorAutoConfiguration.class, - InfoEndpointAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, - CloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ProjectInfoAutoConfiguration.class, + InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") public void gitFullDetailsAlwaysPresent() { - this.contextRunner - .withInitializer( - new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) + this.contextRunner.withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) .run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context .getBean(CloudFoundryInfoEndpointWebExtension.class); - Map git = (Map) extension.info() - .get("git"); + Map git = (Map) extension.info().get("git"); Map commit = (Map) git.get("commit"); assertThat(commit).hasSize(4); }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java index 8d6c44c0991..9ab6d8e4d5d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java @@ -67,92 +67,74 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { private static TokenValidator tokenValidator = mock(TokenValidator.class); - private static CloudFoundrySecurityService securityService = mock( - CloudFoundrySecurityService.class); + private static CloudFoundrySecurityService securityService = mock(CloudFoundrySecurityService.class); @Test public void operationWithSecurityInterceptorForbidden() { - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(AccessLevel.RESTRICTED); + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isEqualTo(HttpStatus.FORBIDDEN)); + (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() + .isEqualTo(HttpStatus.FORBIDDEN)); } @Test public void operationWithSecurityInterceptorSuccess() { - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(AccessLevel.FULL); + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isEqualTo(HttpStatus.OK)); + (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() + .isEqualTo(HttpStatus.OK)); } @Test public void responseToOptionsRequestIncludesCorsHeaders() { - load(TestEndpointConfiguration.class, (client) -> client.options() - .uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST") - .header("Origin", "https://example.com").exchange().expectStatus().isOk() - .expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com") - .expectHeader().valueEquals("Access-Control-Allow-Methods", "GET,POST")); + load(TestEndpointConfiguration.class, + (client) -> client.options().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") + .exchange().expectStatus().isOk().expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test public void linksToOtherEndpointsWithFullAccess() { - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(AccessLevel.FULL); - load(TestEndpointConfiguration.class, (client) -> client.get() - .uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isOk().expectBody().jsonPath("_links.length()") - .isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false) - .jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false) - .jsonPath("_links.env.href").isNotEmpty().jsonPath("_links.env.templated") - .isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false) - .jsonPath("_links.test-part.href").isNotEmpty() - .jsonPath("_links.test-part.templated").isEqualTo(true)); + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); + load(TestEndpointConfiguration.class, + (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() + .expectBody().jsonPath("_links.length()").isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() + .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() + .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env.href").isNotEmpty() + .jsonPath("_links.env.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() + .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") + .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true)); } @Test public void linksToOtherEndpointsForbidden() { - CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException( - Reason.INVALID_TOKEN, "invalid-token"); + CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, + "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication") - .accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isUnauthorized()); + (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() + .isUnauthorized()); } @Test public void linksToOtherEndpointsWithRestrictedAccess() { - given(securityService.getAccessLevel(any(), eq("app-id"))) - .willReturn(AccessLevel.RESTRICTED); + given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication") - .accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isOk().expectBody().jsonPath("_links.length()") - .isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false) - .jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false) - .jsonPath("_links.env").doesNotExist().jsonPath("_links.test") - .doesNotExist().jsonPath("_links.test-part").doesNotExist()); + (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() + .expectBody().jsonPath("_links.length()").isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() + .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() + .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env").doesNotExist() + .jsonPath("_links.test").doesNotExist().jsonPath("_links.test-part").doesNotExist()); } - private AnnotationConfigServletWebServerApplicationContext createApplicationContext( - Class... config) { + private AnnotationConfigServletWebServerApplicationContext createApplicationContext(Class... config) { return new AnnotationConfigServletWebServerApplicationContext(config); } @@ -161,12 +143,11 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } private void load(Class configuration, Consumer clientConsumer) { - BiConsumer consumer = (context, - client) -> clientConsumer.accept(client); - try (AnnotationConfigServletWebServerApplicationContext context = createApplicationContext( - configuration, CloudFoundryMvcConfiguration.class)) { - consumer.accept(context, WebTestClient.bindToServer() - .baseUrl("http://localhost:" + getPort(context)).build()); + BiConsumer consumer = (context, client) -> clientConsumer.accept(client); + try (AnnotationConfigServletWebServerApplicationContext context = createApplicationContext(configuration, + CloudFoundryMvcConfiguration.class)) { + consumer.accept(context, + WebTestClient.bindToServer().baseUrl("http://localhost:" + getPort(context)).build()); } } @@ -182,8 +163,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { @Bean public CloudFoundrySecurityInterceptor interceptor() { - return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, - "app-id"); + return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, "app-id"); } @Bean @@ -194,28 +174,23 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { @Bean public CloudFoundryWebEndpointServletHandlerMapping cloudFoundryWebEndpointServletHandlerMapping( - WebEndpointDiscoverer webEndpointDiscoverer, - EndpointMediaTypes endpointMediaTypes, + WebEndpointDiscoverer webEndpointDiscoverer, EndpointMediaTypes endpointMediaTypes, CloudFoundrySecurityInterceptor interceptor) { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedOrigins(Arrays.asList("https://example.com")); corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST")); - return new CloudFoundryWebEndpointServletHandlerMapping( - new EndpointMapping("/cfApplication"), - webEndpointDiscoverer.getEndpoints(), endpointMediaTypes, - corsConfiguration, interceptor, + return new CloudFoundryWebEndpointServletHandlerMapping(new EndpointMapping("/cfApplication"), + webEndpointDiscoverer.getEndpoints(), endpointMediaTypes, corsConfiguration, interceptor, new EndpointLinksResolver(webEndpointDiscoverer.getEndpoints())); } @Bean - public WebEndpointDiscoverer webEndpointDiscoverer( - ApplicationContext applicationContext, + public WebEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext, EndpointMediaTypes endpointMediaTypes) { ParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - return new WebEndpointDiscoverer(applicationContext, parameterMapper, - endpointMediaTypes, null, Collections.emptyList(), - Collections.emptyList()); + return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes, null, + Collections.emptyList(), Collections.emptyList()); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java index 57a6cfdceda..04811785c6b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java @@ -56,8 +56,7 @@ public class CloudFoundrySecurityInterceptorTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, - this.securityService, "my-app-id"); + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, "my-app-id"); this.request = new MockHttpServletRequest(); } @@ -66,58 +65,45 @@ public class CloudFoundrySecurityInterceptorTests { this.request.setMethod("OPTIONS"); this.request.addHeader(HttpHeaders.ORIGIN, "https://example.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); } @Test public void preHandleWhenTokenIsMissingShouldReturnFalse() { - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); - assertThat(response.getStatus()) - .isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); + assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); } @Test public void preHandleWhenTokenIsNotBearerShouldReturnFalse() { this.request.addHeader("Authorization", mockAccessToken()); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); - assertThat(response.getStatus()) - .isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); + assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); } @Test public void preHandleWhenApplicationIdIsNullShouldReturnFalse() { - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, - this.securityService, null); + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); this.request.addHeader("Authorization", "bearer " + mockAccessToken()); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); - assertThat(response.getStatus()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus()); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); + assertThat(response.getStatus()).isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus()); } @Test public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() { - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, - "my-app-id"); + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); this.request.addHeader("Authorization", "bearer " + mockAccessToken()); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); - assertThat(response.getStatus()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus()); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); + assertThat(response.getStatus()).isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus()); } @Test public void preHandleWhenAccessIsNotAllowedShouldReturnFalse() { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "bearer " + accessToken); - given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(AccessLevel.RESTRICTED); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); + given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus()); } @@ -125,34 +111,28 @@ public class CloudFoundrySecurityInterceptorTests { public void preHandleSuccessfulWithFullAccess() { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "Bearer " + accessToken); - given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(AccessLevel.FULL); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("test")); + given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); ArgumentCaptor tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class); verify(this.tokenValidator).validate(tokenArgumentCaptor.capture()); Token token = tokenArgumentCaptor.getValue(); assertThat(token.toString()).isEqualTo(accessToken); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); - assertThat(this.request.getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.FULL); + assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL); } @Test public void preHandleSuccessfulWithRestrictedAccess() { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "Bearer " + accessToken); - given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(AccessLevel.RESTRICTED); - SecurityResponse response = this.interceptor.preHandle(this.request, - EndpointId.of("info")); + given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); + SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("info")); ArgumentCaptor tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class); verify(this.tokenValidator).validate(tokenArgumentCaptor.capture()); Token token = tokenArgumentCaptor.getValue(); assertThat(token.toString()).isEqualTo(accessToken); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); - assertThat(this.request.getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.RESTRICTED); + assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.RESTRICTED); } private String mockAccessToken() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java index bbe846534a4..1b5611d971e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java @@ -51,8 +51,7 @@ public class CloudFoundrySecurityServiceTests { private static final String CLOUD_CONTROLLER = "https://my-cloud-controller.com"; - private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER - + "/v2/apps/my-app-id/permissions"; + private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER + "/v2/apps/my-app-id/permissions"; private static final String UAA_URL = "https://my-uaa.com"; @@ -64,31 +63,24 @@ public class CloudFoundrySecurityServiceTests { public void setup() { MockServerRestTemplateCustomizer mockServerCustomizer = new MockServerRestTemplateCustomizer(); RestTemplateBuilder builder = new RestTemplateBuilder(mockServerCustomizer); - this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, - false); + this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false); this.server = mockServerCustomizer.getServer(); } @Test public void skipSslValidationWhenTrue() { RestTemplateBuilder builder = new RestTemplateBuilder(); - this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, - true); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils - .getField(this.securityService, "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SkipSslVerificationHttpRequestFactory.class); + this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, true); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SkipSslVerificationHttpRequestFactory.class); } @Test public void doNotskipSslValidationWhenFalse() { RestTemplateBuilder builder = new RestTemplateBuilder(); - this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, - false); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils - .getField(this.securityService, "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isNotInstanceOf(SkipSslVerificationHttpRequestFactory.class); + this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isNotInstanceOf(SkipSslVerificationHttpRequestFactory.class); } @Test @@ -97,8 +89,7 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); - AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", - "my-app-id"); + AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.FULL); } @@ -109,8 +100,7 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); - AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", - "my-app-id"); + AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED); } @@ -118,10 +108,9 @@ public class CloudFoundrySecurityServiceTests { @Test public void getAccessLevelWhenTokenIsNotValidShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withUnauthorizedRequest()); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @@ -130,26 +119,24 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withStatus(HttpStatus.FORBIDDEN)); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) .satisfies(reasonRequirement(Reason.ACCESS_DENIED)); } @Test public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withServerError()); - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", - MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" + "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" @@ -158,8 +145,8 @@ public class CloudFoundrySecurityServiceTests { + "kqwIn7Glry9n9Suxygbf8g5AzpWcusZgDLIIZ7JTUldBb8qU2a0Dl4mvLZOn4wPo\n" + "jfj9Cw2QICsc5+Pwf21fP+hzf+1WSRHbnYv8uanRO0gZ8ekGaghM/2H6gqJbo2nI\n" + "JwIDAQAB\n-----END PUBLIC KEY-----"; - String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" - + tokenKeyValue.replace("\n", "\\n") + "\"} ]}"; + String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" + tokenKeyValue.replace("\n", "\\n") + + "\"} ]}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); Map tokenKeys = this.securityService.fetchTokenKeys(); @@ -169,8 +156,8 @@ public class CloudFoundrySecurityServiceTests { @Test public void fetchTokenKeysWhenNoKeysReturnedFromUAA() { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withSuccess( - "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String responseBody = "{\"keys\": []}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); @@ -181,10 +168,9 @@ public class CloudFoundrySecurityServiceTests { @Test public void fetchTokenKeysWhenUnsuccessfulShouldThrowException() { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withSuccess( - "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); - this.server.expect(requestTo(UAA_URL + "/token_keys")) - .andRespond(withServerError()); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) .isThrownBy(() -> this.securityService.fetchTokenKeys()) .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); @@ -192,8 +178,8 @@ public class CloudFoundrySecurityServiceTests { @Test public void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withSuccess( - "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String uaaUrl = this.securityService.getUaaUrl(); this.server.verify(); assertThat(uaaUrl).isEqualTo(UAA_URL); @@ -204,15 +190,13 @@ public class CloudFoundrySecurityServiceTests { @Test public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withServerError()); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) .isThrownBy(() -> this.securityService.getUaaUrl()) .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } - private Consumer reasonRequirement( - Reason reason) { + private Consumer reasonRequirement(Reason reason) { return (ex) -> assertThat(ex.getReason()).isEqualTo(reason); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java index cbe6c2d3158..18d32fadbf4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java @@ -54,8 +54,7 @@ public class SkipSslVerificationHttpRequestFactoryTests { SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); RestTemplate otherRestTemplate = new RestTemplate(); - ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, - String.class); + ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThatExceptionOfType(ResourceAccessException.class) .isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class)) @@ -65,8 +64,7 @@ public class SkipSslVerificationHttpRequestFactoryTests { private String getHttpsUrl() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0); factory.setSsl(getSsl("password", "classpath:test.jks")); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); this.webServer.start(); return "https://localhost:" + this.webServer.getPort() + "/hello"; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java index 69d53a5eff7..503c60f6a5d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java @@ -79,11 +79,9 @@ public class TokenValidatorTests { + "r3F7aM9YpErzeYLrl0GhQr9BVJxOvXcVd4kmY+XkiCcrkyS1cnghnllh+LCwQu1s\n" + "YwIDAQAB\n-----END PUBLIC KEY-----"; - private static final Map INVALID_KEYS = Collections - .singletonMap("invalid-key", INVALID_KEY); + private static final Map INVALID_KEYS = Collections.singletonMap("invalid-key", INVALID_KEY); - private static final Map VALID_KEYS = Collections - .singletonMap("valid-key", VALID_KEY); + private static final Map VALID_KEYS = Collections.singletonMap("valid-key", VALID_KEY); @BeforeEach public void setup() { @@ -92,28 +90,24 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() - throws Exception { + public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .satisfies(reasonRequirement(Reason.INVALID_KEY_ID)); } @Test - public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() - throws Exception { + public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); verify(this.securityService).fetchTokenKeys(); } @@ -123,8 +117,7 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); verify(this.securityService).fetchTokenKeys(); } @@ -134,8 +127,7 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); verify(this.securityService, Mockito.never()).fetchTokenKeys(); } @@ -146,21 +138,18 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .satisfies(reasonRequirement(Reason.INVALID_SIGNATURE)); } @Test - public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() - throws Exception { + public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .satisfies(reasonRequirement(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); } @@ -170,9 +159,8 @@ public class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .satisfies(reasonRequirement(Reason.TOKEN_EXPIRED)); } @@ -182,22 +170,19 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .satisfies(reasonRequirement(Reason.INVALID_ISSUER)); } @Test - public void validateTokenWhenAudienceIsNotValidShouldThrowException() - throws Exception { + public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) .satisfies(reasonRequirement(Reason.INVALID_AUDIENCE)); } @@ -205,17 +190,15 @@ public class TokenValidatorTests { PrivateKey privateKey = getPrivateKey(); Signature signature = Signature.getInstance("SHA256WithRSA"); signature.initSign(privateKey); - byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), - Base64Utils.encode(claims)); + byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims)); signature.update(content); byte[] crypto = signature.sign(); - byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), - Base64Utils.encodeUrlSafe(claims), Base64Utils.encodeUrlSafe(crypto)); + byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims), + Base64Utils.encodeUrlSafe(crypto)); return new String(token, StandardCharsets.UTF_8); } - private PrivateKey getPrivateKey() - throws InvalidKeySpecException, NoSuchAlgorithmException { + private PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException { String signingKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDSbn2Xa72IOcxu\n" + "tcd+qQ6ufZ1VDe98EmpwO4VQrTd37U9kZtWU0KqeSkgnyzIWmlbyWOdbB4/v4uJa\n" @@ -263,8 +246,7 @@ public class TokenValidatorTests { return result.toByteArray(); } - private Consumer reasonRequirement( - Reason reason) { + private Consumer reasonRequirement(Reason reason) { return (ex) -> assertThat(ex.getReason()).isEqualTo(reason); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java index 6c019183008..fa7fd1ef1e2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java @@ -31,30 +31,23 @@ import static org.assertj.core.api.Assertions.assertThat; public class ConditionsReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(ConditionsReportEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.exposure.include=conditions") - .run((context) -> assertThat(context) - .hasSingleBean(ConditionsReportEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=conditions") + .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ConditionsReportEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.conditions.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ConditionsReportEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.conditions.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java index 30925664115..ac1892285b9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java @@ -47,17 +47,14 @@ public class ConditionsReportEndpointTests { @Test public void invoke() { - new ApplicationContextRunner().withUserConfiguration(Config.class) - .run((context) -> { - ContextConditionEvaluation report = context - .getBean(ConditionsReportEndpoint.class) - .applicationConditionEvaluation().getContexts() - .get(context.getId()); - assertThat(report.getPositiveMatches()).isEmpty(); - assertThat(report.getNegativeMatches()).containsKey("a"); - assertThat(report.getUnconditionalClasses()).contains("b"); - assertThat(report.getExclusions()).contains("com.foo.Bar"); - }); + new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> { + ContextConditionEvaluation report = context.getBean(ConditionsReportEndpoint.class) + .applicationConditionEvaluation().getContexts().get(context.getId()); + assertThat(report.getPositiveMatches()).isEmpty(); + assertThat(report.getNegativeMatches()).containsKey("a"); + assertThat(report.getUnconditionalClasses()).contains("b"); + assertThat(report.getExclusions()).contains("com.foo.Bar"); + }); } @Configuration(proxyBeanMethods = false) @@ -72,11 +69,9 @@ public class ConditionsReportEndpointTests { @PostConstruct public void setupAutoConfigurationReport() { - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.context.getBeanFactory()); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.context.getBeanFactory()); report.recordEvaluationCandidates(Arrays.asList("a", "b")); - report.recordConditionEvaluation("a", mock(Condition.class), - mock(ConditionOutcome.class)); + report.recordConditionEvaluation("a", mock(Condition.class), mock(ConditionOutcome.class)); report.recordExclusions(Collections.singletonList("com.foo.Bar")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java index c0c043af0d5..af7838dadd7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java @@ -32,30 +32,25 @@ import static org.assertj.core.api.Assertions.assertThat; public class ShutdownEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") .withPropertyValues("management.endpoints.web.exposure.include=shutdown") - .run((context) -> assertThat(context) - .hasSingleBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ShutdownEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") - .run((context) -> assertThat(context) - .doesNotHaveBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.shutdown.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ShutdownEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java index af547ccb165..8f9761df4f2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java @@ -41,52 +41,44 @@ import static org.assertj.core.api.Assertions.assertThat; public class ConfigurationPropertiesReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues( - "management.endpoints.web.exposure.include=configprops") + .withPropertyValues("management.endpoints.web.exposure.include=configprops") .run(validateTestProperties("******", "654321")); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.configprops.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.configprops.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } @Test public void keysToSanitizeCanBeConfiguredViaTheEnvironment() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues( - "management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") - .withPropertyValues( - "management.endpoints.web.exposure.include=configprops") + this.contextRunner.withUserConfiguration(Config.class) + .withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") + .withPropertyValues("management.endpoints.web.exposure.include=configprops") .run(validateTestProperties("******", "******")); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); + this.contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } - private ContextConsumer validateTestProperties( - String dbPassword, String myTestProperty) { + private ContextConsumer validateTestProperties(String dbPassword, + String myTestProperty) { return (context) -> { - assertThat(context) - .hasSingleBean(ConfigurationPropertiesReportEndpoint.class); + assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties properties = endpoint - .configurationProperties(); - Map nestedProperties = properties.getContexts() - .get(context.getId()).getBeans().get("testProperties") - .getProperties(); + ApplicationConfigurationProperties properties = endpoint.configurationProperties(); + Map nestedProperties = properties.getContexts().get(context.getId()).getBeans() + .get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("dbPassword")).isEqualTo(dbPassword); assertThat(nestedProperties.get("myTestProperty")).isEqualTo(myTestProperty); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java index 2c35ed610b5..57f1980ccb0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java @@ -37,14 +37,12 @@ import static org.mockito.Mockito.mock; public class CouchbaseHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration( - AutoConfigurations.of(CouchbaseHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations + .of(CouchbaseHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(CouchbaseHealthIndicator.class) + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseHealthIndicator.class) .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @@ -52,8 +50,7 @@ public class CouchbaseHealthIndicatorAutoConfigurationTests { @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(CouchbaseHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java index ffeaccad1ba..218f0fb3952 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java @@ -36,24 +36,19 @@ import static org.mockito.Mockito.mock; public class CouchbaseReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(Cluster.class, () -> mock(Cluster.class)) - .withConfiguration(AutoConfigurations.of( - CouchbaseReactiveHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations.of( + CouchbaseReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(CouchbaseReactiveHealthIndicator.class) - .doesNotHaveBean(CouchbaseHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) + .doesNotHaveBean(CouchbaseHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java index 07d68a70298..15a0cb0e400 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java @@ -39,19 +39,15 @@ import static org.mockito.Mockito.mock; @Deprecated public class ElasticsearchHealthIndicatorAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchAutoConfiguration.class, - ElasticSearchClientHealthIndicatorAutoConfiguration.class, - ElasticSearchJestHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations + .of(ElasticsearchAutoConfiguration.class, ElasticSearchClientHealthIndicatorAutoConfiguration.class, + ElasticSearchJestHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner - .withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0") + this.contextRunner.withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0") .withSystemProperties("es.set.netty.runtime.available.processors=false") - .run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchHealthIndicator.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchHealthIndicator.class) .doesNotHaveBean(ElasticsearchJestHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @@ -60,18 +56,15 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests { public void runWhenUsingJestClientShouldCreateIndicator() { this.contextRunner.withBean(JestClient.class, () -> mock(JestClient.class)) .withSystemProperties("es.set.netty.runtime.available.processors=false") - .run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchJestHealthIndicator.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchJestHealthIndicator.class) .doesNotHaveBean(ElasticsearchHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { - this.contextRunner - .withPropertyValues("management.health.elasticsearch.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ElasticsearchHealthIndicator.class) + this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchHealthIndicator.class) .doesNotHaveBean(ElasticsearchJestHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java index 6db91f1038f..b9fb3a6e328 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java @@ -35,8 +35,7 @@ public class EndpointIdTimeToLivePropertyFunctionTests { private final MockEnvironment environment = new MockEnvironment(); - private final Function timeToLive = new EndpointIdTimeToLivePropertyFunction( - this.environment); + private final Function timeToLive = new EndpointIdTimeToLivePropertyFunction(this.environment); @Test public void defaultConfiguration() { @@ -46,16 +45,14 @@ public class EndpointIdTimeToLivePropertyFunctionTests { @Test public void userConfiguration() { - this.environment.setProperty("management.endpoint.test.cache.time-to-live", - "500"); + this.environment.setProperty("management.endpoint.test.cache.time-to-live", "500"); Long result = this.timeToLive.apply(EndpointId.of("test")); assertThat(result).isEqualTo(500L); } @Test public void mixedCaseUserConfiguration() { - this.environment.setProperty( - "management.endpoint.another-test.cache.time-to-live", "500"); + this.environment.setProperty("management.endpoint.another-test.cache.time-to-live", "500"); Long result = this.timeToLive.apply(EndpointId.of("anotherTest")); assertThat(result).isEqualTo(500L); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java index e801faf0228..feda448148e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java @@ -48,32 +48,28 @@ public class ExposeExcludePropertyEndpointFilterTests { @Test public void createWhenEndpointTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(null, - new MockEnvironment(), "foo")) + .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(null, new MockEnvironment(), "foo")) .withMessageContaining("EndpointType must not be null"); } @Test public void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>( - ExposableEndpoint.class, null, "foo")) + .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, null, "foo")) .withMessageContaining("Environment must not be null"); } @Test public void createWhenPrefixIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>( - ExposableEndpoint.class, new MockEnvironment(), null)) + assertThatIllegalArgumentException().isThrownBy( + () -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) .withMessageContaining("Prefix must not be empty"); } @Test public void createWhenPrefixIsEmptyShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>( - ExposableEndpoint.class, new MockEnvironment(), "")) + assertThatIllegalArgumentException().isThrownBy( + () -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) .withMessageContaining("Prefix must not be empty"); } @@ -124,8 +120,8 @@ public class ExposeExcludePropertyEndpointFilterTests { MockEnvironment environment = new MockEnvironment(); environment.setProperty("foo.include", "bar"); environment.setProperty("foo.exclude", ""); - this.filter = new ExposeExcludePropertyEndpointFilter<>( - DifferentTestExposableWebEndpoint.class, environment, "foo"); + this.filter = new ExposeExcludePropertyEndpointFilter<>(DifferentTestExposableWebEndpoint.class, environment, + "foo"); assertThat(match(EndpointId.of("baz"))).isTrue(); } @@ -155,8 +151,8 @@ public class ExposeExcludePropertyEndpointFilterTests { MockEnvironment environment = new MockEnvironment(); environment.setProperty("foo.include", include); environment.setProperty("foo.exclude", exclude); - this.filter = new ExposeExcludePropertyEndpointFilter<>( - TestExposableWebEndpoint.class, environment, "foo", "def"); + this.filter = new ExposeExcludePropertyEndpointFilter<>(TestExposableWebEndpoint.class, environment, "foo", + "def"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -166,13 +162,11 @@ public class ExposeExcludePropertyEndpointFilterTests { return ((EndpointFilter) this.filter).match(endpoint); } - private abstract static class TestExposableWebEndpoint - implements ExposableWebEndpoint { + private abstract static class TestExposableWebEndpoint implements ExposableWebEndpoint { } - private abstract static class DifferentTestExposableWebEndpoint - implements ExposableWebEndpoint { + private abstract static class DifferentTestExposableWebEndpoint implements ExposableWebEndpoint { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java index 40068d18e57..d903d635187 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java @@ -40,36 +40,30 @@ public class ConditionalOnAvailableEndpointTests { @Test public void outcomeShouldMatchDefaults() { - this.contextRunner.run((context) -> assertThat(context).hasBean("info") - .hasBean("health").doesNotHaveBean("spring").doesNotHaveBean("test") - .doesNotHaveBean("shutdown")); + this.contextRunner.run((context) -> assertThat(context).hasBean("info").hasBean("health") + .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() { - this.contextRunner - .withPropertyValues("management.endpoints.enabled-by-default=false") - .run((context) -> assertThat(context).doesNotHaveBean("info") - .doesNotHaveBean("health").doesNotHaveBean("spring") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") + .run((context) -> assertThat(context).doesNotHaveBean("info").doesNotHaveBean("health") + .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).hasBean("info").hasBean("health") - .hasBean("test").hasBean("spring").doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") + .hasBean("spring").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoint.test.enabled=false", - "management.endpoint.health.enabled=false") - .run((context) -> assertThat(context).hasBean("info") - .doesNotHaveBean("health").doesNotHaveBean("test") + "management.endpoint.test.enabled=false", "management.endpoint.health.enabled=false") + .run((context) -> assertThat(context).hasBean("info").doesNotHaveBean("health").doesNotHaveBean("test") .hasBean("spring").doesNotHaveBean("shutdown")); } @@ -78,36 +72,31 @@ public class ConditionalOnAvailableEndpointTests { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health") - .hasBean("test").hasBean("spring").hasBean("shutdown")); + .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") + .hasBean("spring").hasBean("shutdown")); } @Test public void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() { - this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.include=*") - .run((context) -> assertThat(context).hasBean("info").hasBean("health") - .doesNotHaveBean("spring").doesNotHaveBean("test") - .doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*") + .run((context) -> assertThat(context).hasBean("info").hasBean("health").doesNotHaveBean("spring") + .doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() { - this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.include=*", - "spring.jmx.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health") - .hasBean("test").hasBean("spring").doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true") + .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") + .hasBean("spring").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.include=*", - "spring.jmx.enabled=true", + .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health") - .hasBean("test").hasBean("spring").hasBean("shutdown")); + .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") + .hasBean("spring").hasBean("shutdown")); } @Test @@ -115,37 +104,31 @@ public class ConditionalOnAvailableEndpointTests { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoints.web.exposure.exclude=spring,info") - .run((context) -> assertThat(context).hasBean("health").hasBean("test") - .doesNotHaveBean("info").doesNotHaveBean("spring") - .doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("health").hasBean("test").doesNotHaveBean("info") + .doesNotHaveBean("spring").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.exposure.include=info,health,spring,test", - "management.endpoints.web.exposure.exclude=spring,info") - .run((context) -> assertThat(context).hasBean("health").hasBean("test") - .doesNotHaveBean("info").doesNotHaveBean("spring") - .doesNotHaveBean("shutdown")); + this.contextRunner + .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", + "management.endpoints.web.exposure.exclude=spring,info") + .run((context) -> assertThat(context).hasBean("health").hasBean("test").doesNotHaveBean("info") + .doesNotHaveBean("spring").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=spring") - .run((context) -> assertThat(context).hasBean("spring") - .doesNotHaveBean("health").doesNotHaveBean("info") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=spring") + .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") + .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=shutdown") - .run((context) -> assertThat(context).doesNotHaveBean("spring") - .doesNotHaveBean("health").doesNotHaveBean("info") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=shutdown") + .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") + .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test @@ -153,62 +136,50 @@ public class ConditionalOnAvailableEndpointTests { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=shutdown", "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).doesNotHaveBean("spring") - .doesNotHaveBean("health").doesNotHaveBean("info") - .doesNotHaveBean("test").hasBean("shutdown")); + .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") + .doesNotHaveBean("info").doesNotHaveBean("test").hasBean("shutdown")); } @Test public void outcomeWhenIncludeMatchesWithCaseShouldMatch() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=sPRing") - .run((context) -> assertThat(context).hasBean("spring") - .doesNotHaveBean("health").doesNotHaveBean("info") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sPRing") + .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") + .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.exposure.include=info,health,spring,test", - "management.endpoints.web.exposure.exclude=*") - .run((context) -> assertThat(context).doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("spring") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner + .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", + "management.endpoints.web.exposure.exclude=*") + .run((context) -> assertThat(context).doesNotHaveBean("health").doesNotHaveBean("info") + .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() { - this.contextRunner - .withUserConfiguration( - ComponentEnabledIfEndpointIsExposedConfiguration.class) + this.contextRunner.withUserConfiguration(ComponentEnabledIfEndpointIsExposedConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=spring") - .run((context) -> assertThat(context).hasBean("spring") - .hasBean("springComponent").hasBean("springExtension") - .doesNotHaveBean("info").doesNotHaveBean("health") + .run((context) -> assertThat(context).hasBean("spring").hasBean("springComponent") + .hasBean("springExtension").doesNotHaveBean("info").doesNotHaveBean("health") .doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test public void outcomeWithNoEndpointReferenceShouldFail() { - this.contextRunner - .withUserConfiguration( - ComponentWithNoEndpointReferenceConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> { + this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class) + .withPropertyValues("management.endpoints.web.exposure.include=*").run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause().getMessage()) - .contains( - "No endpoint is specified and the return type of the @Bean method " - + "is neither an @Endpoint, nor an @EndpointExtension"); + .contains("No endpoint is specified and the return type of the @Bean method " + + "is neither an @Endpoint, nor an @EndpointExtension"); }); } @Test public void outcomeOnCloudFoundryShouldMatchAll() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---") - .run((context) -> assertThat(context).hasBean("info").hasBean("health") - .hasBean("spring").hasBean("test")); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run( + (context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); } @Endpoint(id = "health") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java index 76296f2e2c9..8dcb3f05e07 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java @@ -43,8 +43,7 @@ public class ConditionalOnEnabledEndpointTests { @Test public void outcomeWhenEndpointEnabledPropertyIsTrueShouldMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true") - .withUserConfiguration( - FooEndpointEnabledByDefaultFalseConfiguration.class) + .withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).hasBean("foo")); } @@ -57,51 +56,40 @@ public class ConditionalOnEnabledEndpointTests { @Test public void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsTrueShouldMatch() { - this.contextRunner - .withPropertyValues("management.endpoints.enabled-by-default=true") - .withUserConfiguration( - FooEndpointEnabledByDefaultFalseConfiguration.class) + this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=true") + .withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).hasBean("foo")); } @Test public void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsFalseShouldNotMatch() { - this.contextRunner - .withPropertyValues("management.endpoints.enabled-by-default=false") + this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") .withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test public void outcomeWhenNoPropertiesAndAnnotationIsEnabledByDefaultShouldMatch() { - this.contextRunner - .withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) + this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).hasBean("foo")); } @Test public void outcomeWhenNoPropertiesAndAnnotationIsNotEnabledByDefaultShouldNotMatch() { - this.contextRunner - .withUserConfiguration( - FooEndpointEnabledByDefaultFalseConfiguration.class) + this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test public void outcomeWhenNoPropertiesAndExtensionAnnotationIsEnabledByDefaultShouldMatch() { - this.contextRunner - .withUserConfiguration( - FooEndpointAndExtensionEnabledByDefaultTrueConfiguration.class) + this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).hasBean("foo").hasBean("fooExt")); } @Test public void outcomeWhenNoPropertiesAndExtensionAnnotationIsNotEnabledByDefaultShouldNotMatch() { - this.contextRunner - .withUserConfiguration( - FooEndpointAndExtensionEnabledByDefaultFalseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo") - .doesNotHaveBean("fooExt")); + this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultFalseConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean("foo").doesNotHaveBean("fooExt")); } @Test @@ -130,31 +118,25 @@ public class ConditionalOnEnabledEndpointTests { @Test public void outcomeWithNoReferenceShouldFail() { - this.contextRunner - .withUserConfiguration( - ComponentWithNoEndpointReferenceConfiguration.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getCause().getMessage()) - .contains( - "No endpoint is specified and the return type of the @Bean method " - + "is neither an @Endpoint, nor an @EndpointExtension"); - }); + this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class).run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getCause().getMessage()) + .contains("No endpoint is specified and the return type of the @Bean method " + + "is neither an @Endpoint, nor an @EndpointExtension"); + }); } @Test public void outcomeWhenEndpointEnabledPropertyIsTrueAndMixedCaseShouldMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo-bar.enabled=true") - .withUserConfiguration( - FooBarEndpointEnabledByDefaultFalseConfiguration.class) + .withUserConfiguration(FooBarEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).hasBean("fooBar")); } @Test public void outcomeWhenEndpointEnabledPropertyIsFalseOnClassShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") - .withUserConfiguration( - FooEndpointEnabledByDefaultTrueOnConfigurationConfiguration.class) + .withUserConfiguration(FooEndpointEnabledByDefaultTrueOnConfigurationConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @@ -173,14 +155,12 @@ public class ConditionalOnEnabledEndpointTests { } - @EndpointExtension(endpoint = FooEndpointEnabledByDefaultTrue.class, - filter = TestFilter.class) + @EndpointExtension(endpoint = FooEndpointEnabledByDefaultTrue.class, filter = TestFilter.class) static class FooEndpointExtensionEnabledByDefaultTrue { } - @EndpointExtension(endpoint = FooEndpointEnabledByDefaultFalse.class, - filter = TestFilter.class) + @EndpointExtension(endpoint = FooEndpointEnabledByDefaultFalse.class, filter = TestFilter.class) static class FooEndpointExtensionEnabledByDefaultFalse { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java index 9f09d68a906..56623eacec7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java @@ -51,24 +51,20 @@ public class DefaultEndpointObjectNameFactoryTests { @Test public void generateObjectName() { ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); - assertThat(objectName.toString()) - .isEqualTo("org.springframework.boot:type=Endpoint,name=Test"); + assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test"); } @Test public void generateObjectNameWithCapitalizedId() { - ObjectName objectName = generateObjectName( - endpoint(EndpointId.of("testEndpoint"))); - assertThat(objectName.toString()) - .isEqualTo("org.springframework.boot:type=Endpoint,name=TestEndpoint"); + ObjectName objectName = generateObjectName(endpoint(EndpointId.of("testEndpoint"))); + assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=TestEndpoint"); } @Test public void generateObjectNameWithCustomDomain() { this.properties.setDomain("com.example.acme"); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); - assertThat(objectName.toString()) - .isEqualTo("com.example.acme:type=Endpoint,name=Test"); + assertThat(objectName.toString()).isEqualTo("com.example.acme:type=Endpoint,name=Test"); } @Test @@ -81,8 +77,7 @@ public class DefaultEndpointObjectNameFactoryTests { ExposableJmxEndpoint endpoint = endpoint(EndpointId.of("test")); String id = ObjectUtils.getIdentityHexString(endpoint); ObjectName objectName = generateObjectName(endpoint); - assertThat(objectName.toString()).isEqualTo( - "org.springframework.boot:type=Endpoint,name=Test,identity=" + id); + assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test,identity=" + id); } @Test @@ -92,28 +87,24 @@ public class DefaultEndpointObjectNameFactoryTests { ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); assertThat(objectName.getKeyProperty("counter")).isEqualTo("42"); assertThat(objectName.getKeyProperty("foo")).isEqualTo("bar"); - assertThat(objectName.toString()) - .startsWith("org.springframework.boot:type=Endpoint,name=Test,"); + assertThat(objectName.toString()).startsWith("org.springframework.boot:type=Endpoint,name=Test,"); } @Test public void generateObjectNameWithDuplicate() throws MalformedObjectNameException { this.contextId = "testContext"; - given(this.mBeanServer.queryNames( - new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), - null)).willReturn( - Collections.singleton(new ObjectName( - "org.springframework.boot:type=Endpoint,name=Test"))); + given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null)) + .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); - assertThat(objectName.toString()).isEqualTo( - "org.springframework.boot:type=Endpoint,name=Test,context=testContext"); + assertThat(objectName.toString()) + .isEqualTo("org.springframework.boot:type=Endpoint,name=Test,context=testContext"); } private ObjectName generateObjectName(ExposableJmxEndpoint endpoint) { try { - return new DefaultEndpointObjectNameFactory(this.properties, this.environment, - this.mBeanServer, this.contextId).getObjectName(endpoint); + return new DefaultEndpointObjectNameFactory(this.properties, this.environment, this.mBeanServer, + this.contextId).getObjectName(endpoint); } catch (MalformedObjectNameException ex) { throw new AssertionError("Invalid object name", ex); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java index 6943a8789f8..3aa20853719 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java @@ -34,34 +34,31 @@ public class MappingWebEndpointPathMapperTests { @Test public void defaultConfiguration() { - MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( - Collections.emptyMap()); - assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), - EndpointId.of("test"))).isEqualTo("test"); + MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); + assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))).isEqualTo("test"); } @Test public void userConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test", "custom")); - assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), - EndpointId.of("test"))).isEqualTo("custom"); + assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))) + .isEqualTo("custom"); } @Test public void mixedCaseDefaultConfiguration() { - MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( - Collections.emptyMap()); - assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), - EndpointId.of("testEndpoint"))).isEqualTo("testEndpoint"); + MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); + assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) + .isEqualTo("testEndpoint"); } @Test public void mixedCaseUserConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test-endpoint", "custom")); - assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), - EndpointId.of("testEndpoint"))).isEqualTo("custom"); + assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) + .isEqualTo("custom"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java index 088e21791c4..2f0c9996b69 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java @@ -52,20 +52,17 @@ public class ServletEndpointManagementContextConfigurationTests { FilteredClassLoader classLoader = new FilteredClassLoader(ResourceConfig.class); this.contextRunner.withClassLoader(classLoader).run((context) -> { assertThat(context).hasSingleBean(ServletEndpointRegistrar.class); - ServletEndpointRegistrar bean = context - .getBean(ServletEndpointRegistrar.class); + ServletEndpointRegistrar bean = context.getBean(ServletEndpointRegistrar.class); assertThat(bean).hasFieldOrPropertyWithValue("basePath", "/test/actuator"); }); } @Test public void contextWhenJerseyShouldContainServletEndpointRegistrar() { - FilteredClassLoader classLoader = new FilteredClassLoader( - DispatcherServlet.class); + FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class); this.contextRunner.withClassLoader(classLoader).run((context) -> { assertThat(context).hasSingleBean(ServletEndpointRegistrar.class); - ServletEndpointRegistrar bean = context - .getBean(ServletEndpointRegistrar.class); + ServletEndpointRegistrar bean = context.getBean(ServletEndpointRegistrar.class); assertThat(bean).hasFieldOrPropertyWithValue("basePath", "/jersey/actuator"); }); } @@ -73,8 +70,7 @@ public class ServletEndpointManagementContextConfigurationTests { @Test public void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() { new ApplicationContextRunner().withUserConfiguration(TestConfig.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(ServletEndpointRegistrar.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java index e89bb2965e4..1d7fc06910c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java @@ -51,8 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class WebEndpointAutoConfigurationTests { - private static final AutoConfigurations CONFIGURATIONS = AutoConfigurations - .of(EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class); + private static final AutoConfigurations CONFIGURATIONS = AutoConfigurations.of(EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class); private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(CONFIGURATIONS); @@ -60,22 +60,17 @@ public class WebEndpointAutoConfigurationTests { @Test public void webApplicationConfiguresEndpointMediaTypes() { this.contextRunner.run((context) -> { - EndpointMediaTypes endpointMediaTypes = context - .getBean(EndpointMediaTypes.class); - assertThat(endpointMediaTypes.getConsumed()) - .containsExactly(ActuatorMediaType.V2_JSON, "application/json"); + EndpointMediaTypes endpointMediaTypes = context.getBean(EndpointMediaTypes.class); + assertThat(endpointMediaTypes.getConsumed()).containsExactly(ActuatorMediaType.V2_JSON, "application/json"); }); } @Test public void webApplicationConfiguresPathMapper() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.path-mapping.health=healthcheck") + this.contextRunner.withPropertyValues("management.endpoints.web.path-mapping.health=healthcheck") .run((context) -> { assertThat(context).hasSingleBean(PathMapper.class); - String pathMapping = context.getBean(PathMapper.class) - .getRootPath(EndpointId.of("health")); + String pathMapping = context.getBean(PathMapper.class).getRootPath(EndpointId.of("health")); assertThat(pathMapping).isEqualTo("healthcheck"); }); } @@ -85,17 +80,13 @@ public class WebEndpointAutoConfigurationTests { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoints.web.path-mapping.testanotherone=foo") - .withUserConfiguration(TestPathMatcher.class, TestOneEndpoint.class, - TestAnotherOneEndpoint.class, TestTwoEndpoint.class) + .withUserConfiguration(TestPathMatcher.class, TestOneEndpoint.class, TestAnotherOneEndpoint.class, + TestTwoEndpoint.class) .run((context) -> { - WebEndpointDiscoverer discoverer = context - .getBean(WebEndpointDiscoverer.class); - Collection endpoints = discoverer - .getEndpoints(); - ExposableWebEndpoint[] webEndpoints = endpoints - .toArray(new ExposableWebEndpoint[0]); - List paths = Arrays.stream(webEndpoints) - .map(PathMappedEndpoint::getRootPath) + WebEndpointDiscoverer discoverer = context.getBean(WebEndpointDiscoverer.class); + Collection endpoints = discoverer.getEndpoints(); + ExposableWebEndpoint[] webEndpoints = endpoints.toArray(new ExposableWebEndpoint[0]); + List paths = Arrays.stream(webEndpoints).map(PathMappedEndpoint::getRootPath) .collect(Collectors.toList()); assertThat(paths).containsOnly("1/testone", "foo", "testtwo"); }); @@ -111,23 +102,20 @@ public class WebEndpointAutoConfigurationTests { @Test public void webApplicationConfiguresExposeExcludePropertyEndpointFilter() { - this.contextRunner.run((context) -> assertThat(context) - .getBeans(ExposeExcludePropertyEndpointFilter.class) - .containsKeys("webExposeExcludePropertyEndpointFilter", - "controllerExposeExcludePropertyEndpointFilter")); + this.contextRunner + .run((context) -> assertThat(context).getBeans(ExposeExcludePropertyEndpointFilter.class).containsKeys( + "webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); } @Test public void contextShouldConfigureServletEndpointDiscoverer() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ServletEndpointDiscoverer.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ServletEndpointDiscoverer.class)); } @Test public void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() { new ApplicationContextRunner().withConfiguration(CONFIGURATIONS) - .run((context) -> assertThat(context) - .doesNotHaveBean(ServletEndpointDiscoverer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); } @Component diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java index f7961518e25..146997da65d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java @@ -46,8 +46,7 @@ public class WebEndpointPropertiesTests { @Test public void basePathMustStartWithSlash() { WebEndpointProperties properties = new WebEndpointProperties(); - assertThatIllegalArgumentException() - .isThrownBy(() -> properties.setBasePath("admin")) + assertThatIllegalArgumentException().isThrownBy(() -> properties.setBasePath("admin")) .withMessageContaining("Base path must start with '/' or be empty"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java index 811fe3991ac..72029805e7c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java @@ -56,15 +56,12 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit * @author Andy Wilkinson */ @TestPropertySource(properties = { "spring.jackson.serialization.indent_output=true", - "management.endpoints.web.exposure.include=*", - "spring.jackson.default-property-inclusion=non_null" }) + "management.endpoints.web.exposure.include=*", "spring.jackson.default-property-inclusion=non_null" }) public abstract class AbstractEndpointDocumentationTests { protected String describeEnumValues(Class> enumType) { - return StringUtils - .collectionToDelimitedString(Stream.of(enumType.getEnumConstants()) - .map((constant) -> "`" + constant.name() + "`") - .collect(Collectors.toList()), ", "); + return StringUtils.collectionToDelimitedString(Stream.of(enumType.getEnumConstants()) + .map((constant) -> "`" + constant.name() + "`").collect(Collectors.toList()), ", "); } protected OperationPreprocessor limit(String... keys) { @@ -74,8 +71,7 @@ public abstract class AbstractEndpointDocumentationTests { @SuppressWarnings("unchecked") protected OperationPreprocessor limit(Predicate filter, String... keys) { return new ContentModifyingOperationPreprocessor((content, mediaType) -> { - ObjectMapper objectMapper = new ObjectMapper() - .enable(SerializationFeature.INDENT_OUTPUT); + ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); try { Map payload = objectMapper.readValue(content, Map.class); Object target = payload; @@ -90,12 +86,10 @@ public abstract class AbstractEndpointDocumentationTests { } } if (target instanceof Map) { - parent.put(keys[keys.length - 1], - select((Map) target, filter)); + parent.put(keys[keys.length - 1], select((Map) target, filter)); } else { - parent.put(keys[keys.length - 1], - select((List) target, filter)); + parent.put(keys[keys.length - 1], select((List) target, filter)); } return objectMapper.writeValueAsBytes(payload); } @@ -106,36 +100,30 @@ public abstract class AbstractEndpointDocumentationTests { } protected FieldDescriptor parentIdField() { - return fieldWithPath("contexts.*.parentId") - .description("Id of the parent application context, if any.").optional() - .type(JsonFieldType.STRING); + return fieldWithPath("contexts.*.parentId").description("Id of the parent application context, if any.") + .optional().type(JsonFieldType.STRING); } @SuppressWarnings("unchecked") - private Map select(Map candidates, - Predicate filter) { + private Map select(Map candidates, Predicate filter) { Map selected = new HashMap<>(); - candidates.entrySet().stream().filter((candidate) -> filter.test((T) candidate)) - .limit(3) + candidates.entrySet().stream().filter((candidate) -> filter.test((T) candidate)).limit(3) .forEach((entry) -> selected.put(entry.getKey(), entry.getValue())); return selected; } @SuppressWarnings("unchecked") private List select(List candidates, Predicate filter) { - return candidates.stream().filter((candidate) -> filter.test((T) candidate)) - .limit(3).collect(Collectors.toList()); + return candidates.stream().filter((candidate) -> filter.test((T) candidate)).limit(3) + .collect(Collectors.toList()); } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - WebMvcEndpointManagementContextConfiguration.class, - WebFluxEndpointManagementContextConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, WebMvcEndpointManagementContextConfiguration.class, + WebFluxEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class }) static class BaseDocumentationConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java index ff83a1f1679..8d011d58559 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java @@ -47,8 +47,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class AuditEventsEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @MockBean private AuditEventRepository repository; @@ -56,41 +55,33 @@ public class AuditEventsEndpointDocumentationTests @Test public void allAuditEvents() throws Exception { String queryTimestamp = "2017-11-07T09:37Z"; - given(this.repository.find(any(), any(), any())).willReturn( - Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); - this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp)) - .andExpect(status().isOk()) + given(this.repository.find(any(), any(), any())) + .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); + this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp)).andExpect(status().isOk()) .andDo(document("auditevents/all", responseFields( fieldWithPath("events").description("An array of audit events."), - fieldWithPath("events.[].timestamp") - .description("The timestamp of when the event occurred."), - fieldWithPath("events.[].principal") - .description("The principal that triggered the event."), - fieldWithPath("events.[].type") - .description("The type of the event.")))); + fieldWithPath("events.[].timestamp").description("The timestamp of when the event occurred."), + fieldWithPath("events.[].principal").description("The principal that triggered the event."), + fieldWithPath("events.[].type").description("The type of the event.")))); } @Test public void filteredAuditEvents() throws Exception { OffsetDateTime now = OffsetDateTime.now(); String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now); - given(this.repository.find("alice", now.toInstant(), "logout")).willReturn( - Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); + given(this.repository.find("alice", now.toInstant(), "logout")) + .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); this.mockMvc - .perform(get("/actuator/auditevents").param("principal", "alice") - .param("after", queryTimestamp).param("type", "logout")) + .perform(get("/actuator/auditevents") + .param("principal", "alice").param("after", queryTimestamp).param("type", "logout")) .andExpect(status().isOk()) - .andDo(document("auditevents/filtered", - requestParameters( - parameterWithName("after").description( - "Restricts the events to those that occurred " - + "after the given time. Optional."), - parameterWithName("principal").description( - "Restricts the events to those with the given " - + "principal. Optional."), - parameterWithName("type").description( - "Restricts the events to those with the given " - + "type. Optional.")))); + .andDo(document("auditevents/filtered", requestParameters( + parameterWithName("after").description( + "Restricts the events to those that occurred " + "after the given time. Optional."), + parameterWithName("principal") + .description("Restricts the events to those with the given " + "principal. Optional."), + parameterWithName("type") + .description("Restricts the events to those with the given " + "type. Optional.")))); verify(this.repository).find("alice", now.toInstant(), "logout"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java index 7eb31ed8e0f..5c4ac066ec3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java @@ -49,32 +49,25 @@ public class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentatio @Test public void beans() throws Exception { - List beanFields = Arrays.asList( - fieldWithPath("aliases").description("Names of any aliases."), + List beanFields = Arrays.asList(fieldWithPath("aliases").description("Names of any aliases."), fieldWithPath("scope").description("Scope of the bean."), fieldWithPath("type").description("Fully qualified type of the bean."), - fieldWithPath("resource") - .description("Resource in which the bean was defined, if any.") - .optional(), + fieldWithPath("resource").description("Resource in which the bean was defined, if any.").optional(), fieldWithPath("dependencies").description("Names of any dependencies.")); ResponseFieldsSnippet responseFields = responseFields( - fieldWithPath("contexts") - .description("Application contexts keyed by id."), - parentIdField(), - fieldWithPath("contexts.*.beans") - .description("Beans in the application context keyed by name.")) - .andWithPrefix("contexts.*.beans.*.", beanFields); + fieldWithPath("contexts").description("Application contexts keyed by id."), parentIdField(), + fieldWithPath("contexts.*.beans").description("Beans in the application context keyed by name.")) + .andWithPrefix("contexts.*.beans.*.", beanFields); this.mockMvc.perform(get("/actuator/beans")).andExpect(status().isOk()) .andDo(document("beans", - preprocessResponse(limit(this::isIndependentBean, "contexts", - getApplicationContext().getId(), "beans")), + preprocessResponse( + limit(this::isIndependentBean, "contexts", getApplicationContext().getId(), "beans")), responseFields)); } private boolean isIndependentBean(Entry> bean) { return CollectionUtils.isEmpty((Collection) bean.getValue().get("aliases")) - && CollectionUtils - .isEmpty((Collection) bean.getValue().get("dependencies")); + && CollectionUtils.isEmpty((Collection) bean.getValue().get("dependencies")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java index 0bb7f1fec9e..f2307e2ed3b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java @@ -53,34 +53,28 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati private static final List levelFields = Arrays.asList( fieldWithPath("name").description("Cache name."), fieldWithPath("cacheManager").description("Cache manager name."), - fieldWithPath("target") - .description("Fully qualified name of the native cache.")); + fieldWithPath("target").description("Fully qualified name of the native cache.")); private static final List requestParameters = Collections - .singletonList(parameterWithName("cacheManager") - .description("Name of the cacheManager to qualify the cache. May be " - + "omitted if the cache name is unique.") + .singletonList(parameterWithName("cacheManager").description( + "Name of the cacheManager to qualify the cache. May be " + "omitted if the cache name is unique.") .optional()); @Test public void allCaches() throws Exception { this.mockMvc.perform(get("/actuator/caches")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("caches/all", responseFields( - fieldWithPath("cacheManagers") - .description("Cache managers keyed by id."), - fieldWithPath("cacheManagers.*.caches").description( - "Caches in the application context keyed by " + "name.")) - .andWithPrefix("cacheManagers.*.caches.*.", - fieldWithPath("target").description( - "Fully qualified name of the native cache.")))); + .andDo(MockMvcRestDocumentation.document("caches/all", + responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), + fieldWithPath("cacheManagers.*.caches") + .description("Caches in the application context keyed by " + "name.")) + .andWithPrefix("cacheManagers.*.caches.*.", fieldWithPath("target") + .description("Fully qualified name of the native cache.")))); } @Test public void namedCache() throws Exception { - this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("caches/named", - requestParameters(requestParameters), - responseFields(levelFields))); + this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()).andDo(MockMvcRestDocumentation + .document("caches/named", requestParameters(requestParameters), responseFields(levelFields))); } @Test @@ -91,12 +85,9 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati @Test public void evictNamedCache() throws Exception { - this.mockMvc - .perform(delete( - "/actuator/caches/countries?cacheManager=anotherCacheManager")) + this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager")) .andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("caches/evict-named", - requestParameters(requestParameters))); + .andDo(MockMvcRestDocumentation.document("caches/evict-named", requestParameters(requestParameters))); } @Configuration(proxyBeanMethods = false) @@ -106,10 +97,8 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati @Bean public CachesEndpoint endpoint() { Map cacheManagers = new HashMap<>(); - cacheManagers.put("cacheManager", - new ConcurrentMapCacheManager("countries", "cities")); - cacheManagers.put("anotherCacheManager", - new ConcurrentMapCacheManager("countries")); + cacheManagers.put("cacheManager", new ConcurrentMapCacheManager("countries", "cities")); + cacheManagers.put("anotherCacheManager", new ConcurrentMapCacheManager("countries")); return new CachesEndpoint(cacheManagers); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java index 3910e62c1c9..898d2e58a95 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java @@ -49,8 +49,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ConditionsReportEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private MockMvc mockMvc; @@ -61,53 +60,36 @@ public class ConditionsReportEndpointDocumentationTests @BeforeEach public void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation - .documentationConfiguration(restDocumentation).uris()) - .build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()).build(); } @Test public void conditions() throws Exception { List positiveMatchFields = Arrays.asList( - fieldWithPath("").description( - "Classes and methods with conditions that were " + "matched."), + fieldWithPath("").description("Classes and methods with conditions that were " + "matched."), fieldWithPath(".*.[].condition").description("Name of the condition."), - fieldWithPath(".*.[].message") - .description("Details of why the condition was matched.")); + fieldWithPath(".*.[].message").description("Details of why the condition was matched.")); List negativeMatchFields = Arrays.asList( - fieldWithPath("").description("Classes and methods with conditions that " - + "were not matched."), - fieldWithPath(".*.notMatched") - .description("Conditions that were matched."), - fieldWithPath(".*.notMatched.[].condition") - .description("Name of the condition."), - fieldWithPath(".*.notMatched.[].message").description( - "Details of why the condition was" + " not matched."), + fieldWithPath("").description("Classes and methods with conditions that " + "were not matched."), + fieldWithPath(".*.notMatched").description("Conditions that were matched."), + fieldWithPath(".*.notMatched.[].condition").description("Name of the condition."), + fieldWithPath(".*.notMatched.[].message") + .description("Details of why the condition was" + " not matched."), fieldWithPath(".*.matched").description("Conditions that were matched."), - fieldWithPath(".*.matched.[].condition") - .description("Name of the condition.").type(JsonFieldType.STRING) - .optional(), - fieldWithPath(".*.matched.[].message") - .description("Details of why the condition was matched.") + fieldWithPath(".*.matched.[].condition").description("Name of the condition.") + .type(JsonFieldType.STRING).optional(), + fieldWithPath(".*.matched.[].message").description("Details of why the condition was matched.") .type(JsonFieldType.STRING).optional()); - FieldDescriptor unconditionalClassesField = fieldWithPath( - "contexts.*.unconditionalClasses").description( - "Names of unconditional auto-configuration classes if any."); + FieldDescriptor unconditionalClassesField = fieldWithPath("contexts.*.unconditionalClasses") + .description("Names of unconditional auto-configuration classes if any."); this.mockMvc.perform(get("/actuator/conditions")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("conditions", - preprocessResponse( - limit("contexts", getApplicationContext() - .getId(), "positiveMatches"), - limit("contexts", getApplicationContext().getId(), - "negativeMatches")), - responseFields(fieldWithPath("contexts") - .description("Application contexts keyed by id.")) - .andWithPrefix("contexts.*.positiveMatches", - positiveMatchFields) - .andWithPrefix("contexts.*.negativeMatches", - negativeMatchFields) - .and(unconditionalClassesField, - parentIdField()))); + preprocessResponse(limit("contexts", getApplicationContext().getId(), "positiveMatches"), + limit("contexts", getApplicationContext().getId(), "negativeMatches")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id.")) + .andWithPrefix("contexts.*.positiveMatches", positiveMatchFields) + .andWithPrefix("contexts.*.negativeMatches", negativeMatchFields) + .and(unconditionalClassesField, parentIdField()))); } @Configuration(proxyBeanMethods = false) @@ -115,12 +97,11 @@ public class ConditionsReportEndpointDocumentationTests static class TestConfiguration { @Bean - public ConditionsReportEndpoint autoConfigurationReportEndpoint( - ConfigurableApplicationContext context) { + public ConditionsReportEndpoint autoConfigurationReportEndpoint(ConfigurableApplicationContext context) { ConditionEvaluationReport conditionEvaluationReport = ConditionEvaluationReport .get(context.getBeanFactory()); - conditionEvaluationReport.recordEvaluationCandidates( - Arrays.asList(PropertyPlaceholderAutoConfiguration.class.getName())); + conditionEvaluationReport + .recordEvaluationCandidates(Arrays.asList(PropertyPlaceholderAutoConfiguration.class.getName())); return new ConditionsReportEndpoint(context); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java index 9a3438411e9..e43b2d896c7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java @@ -37,25 +37,20 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ConfigurationPropertiesReportEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void configProps() throws Exception { this.mockMvc.perform(get("/actuator/configprops")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("configprops", - preprocessResponse(limit("contexts", - getApplicationContext().getId(), "beans")), - responseFields( - fieldWithPath("contexts") - .description("Application contexts keyed by id."), - fieldWithPath("contexts.*.beans.*").description( - "`@ConfigurationProperties` beans keyed by bean name."), - fieldWithPath("contexts.*.beans.*.prefix").description( - "Prefix applied to the names of the bean's properties."), + preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), + fieldWithPath("contexts.*.beans.*") + .description("`@ConfigurationProperties` beans keyed by bean name."), + fieldWithPath("contexts.*.beans.*.prefix") + .description("Prefix applied to the names of the bean's properties."), subsectionWithPath("contexts.*.beans.*.properties") - .description( - "Properties of the bean as name-value pairs."), + .description("Properties of the bean as name-value pairs."), parentIdField()))); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java index 6aeb258b972..553170856b5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java @@ -57,61 +57,49 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @TestPropertySource( properties = "spring.config.location=classpath:/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/") -public class EnvironmentEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final FieldDescriptor activeProfiles = fieldWithPath("activeProfiles") .description("Names of the active profiles, if any."); - private static final FieldDescriptor propertySources = fieldWithPath( - "propertySources").description("Property sources in order of precedence."); + private static final FieldDescriptor propertySources = fieldWithPath("propertySources") + .description("Property sources in order of precedence."); - private static final FieldDescriptor propertySourceName = fieldWithPath( - "propertySources.[].name").description("Name of the property source."); + private static final FieldDescriptor propertySourceName = fieldWithPath("propertySources.[].name") + .description("Name of the property source."); @Test public void env() throws Exception { - this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk()).andDo( - document("env/all", preprocessResponse(replacePattern(Pattern.compile( - "org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), + this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk()) + .andDo(document("env/all", preprocessResponse(replacePattern( + Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), ""), filterProperties()), - responseFields(activeProfiles, propertySources, - propertySourceName, + responseFields(activeProfiles, propertySources, propertySourceName, fieldWithPath("propertySources.[].properties") - .description( - "Properties in the property source keyed by property name."), + .description("Properties in the property source keyed by property name."), fieldWithPath("propertySources.[].properties.*.value") .description("Value of the property."), fieldWithPath("propertySources.[].properties.*.origin") - .description("Origin of the property, if any.") - .optional()))); + .description("Origin of the property, if any.").optional()))); } @Test public void singlePropertyFromEnv() throws Exception { - this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")) - .andExpect(status().isOk()) - .andDo(document("env/single", - preprocessResponse(replacePattern(Pattern.compile( - "org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), - "")), - responseFields( - fieldWithPath("property").description( - "Property from the environment, if found.") - .optional(), - fieldWithPath("property.source").description( - "Name of the source of the property."), - fieldWithPath("property.value") - .description("Value of the property."), - activeProfiles, propertySources, propertySourceName, - fieldWithPath("propertySources.[].property").description( - "Property in the property source, if any.") - .optional(), - fieldWithPath("propertySources.[].property.value") - .description("Value of the property."), - fieldWithPath("propertySources.[].property.origin") - .description("Origin of the property, if any.") - .optional()))); + this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")).andExpect(status().isOk()).andDo(document( + "env/single", + preprocessResponse(replacePattern( + Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), + "")), + responseFields( + fieldWithPath("property").description("Property from the environment, if found.").optional(), + fieldWithPath("property.source").description("Name of the source of the property."), + fieldWithPath("property.value").description("Value of the property."), activeProfiles, + propertySources, propertySourceName, + fieldWithPath("propertySources.[].property") + .description("Property in the property source, if any.").optional(), + fieldWithPath("propertySources.[].property.value").description("Value of the property."), + fieldWithPath("propertySources.[].property.origin") + .description("Origin of the property, if any.").optional()))); } private OperationPreprocessor filterProperties() { @@ -120,17 +108,14 @@ public class EnvironmentEndpointDocumentationTests @SuppressWarnings("unchecked") private byte[] filterProperties(byte[] content, MediaType mediaType) { - ObjectMapper objectMapper = new ObjectMapper() - .enable(SerializationFeature.INDENT_OUTPUT); + ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); try { Map payload = objectMapper.readValue(content, Map.class); - List> propertySources = (List>) payload - .get("propertySources"); + List> propertySources = (List>) payload.get("propertySources"); for (Map propertySource : propertySources) { - Map properties = (Map) propertySource - .get("properties"); - Set filteredKeys = properties.keySet().stream() - .filter(this::retainKey).limit(3).collect(Collectors.toSet()); + Map properties = (Map) propertySource.get("properties"); + Set filteredKeys = properties.keySet().stream().filter(this::retainKey).limit(3) + .collect(Collectors.toSet()); properties.keySet().retainAll(filteredKeys); } return objectMapper.writeValueAsBytes(payload); @@ -141,8 +126,7 @@ public class EnvironmentEndpointDocumentationTests } private boolean retainKey(String key) { - return key.startsWith("java.") || key.equals("JAVA_HOME") - || key.startsWith("com.example"); + return key.startsWith("java.") || key.equals("JAVA_HOME") || key.startsWith("com.example"); } @Configuration(proxyBeanMethods = false) @@ -154,17 +138,14 @@ public class EnvironmentEndpointDocumentationTests return new EnvironmentEndpoint(new AbstractEnvironment() { @Override - protected void customizePropertySources( - MutablePropertySources propertySources) { - environment.getPropertySources().stream() - .filter(this::includedPropertySource) + protected void customizePropertySources(MutablePropertySources propertySources) { + environment.getPropertySources().stream().filter(this::includedPropertySource) .forEach(propertySources::addLast); } private boolean includedPropertySource(PropertySource propertySource) { return propertySource instanceof EnumerablePropertySource - && !"Inlined Test Properties" - .equals(propertySource.getName()); + && !"Inlined Test Properties".equals(propertySource.getName()); } }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java index 8cf9db25c32..97c3d5765fc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java @@ -52,49 +52,35 @@ public class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentati @Test public void flyway() throws Exception { this.mockMvc.perform(get("/actuator/flyway")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("flyway", responseFields( - fieldWithPath("contexts") - .description("Application contexts keyed by id"), - fieldWithPath("contexts.*.flywayBeans.*.migrations").description( - "Migrations performed by the Flyway instance, keyed by" - + " Flyway bean name.")).andWithPrefix( - "contexts.*.flywayBeans.*.migrations.[].", - migrationFieldDescriptors()) + .andDo(MockMvcRestDocumentation.document("flyway", + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), + fieldWithPath("contexts.*.flywayBeans.*.migrations").description( + "Migrations performed by the Flyway instance, keyed by" + " Flyway bean name.")) + .andWithPrefix("contexts.*.flywayBeans.*.migrations.[].", + migrationFieldDescriptors()) .and(parentIdField()))); } private List migrationFieldDescriptors() { - return Arrays.asList( - fieldWithPath("checksum") - .description("Checksum of the migration, if any.").optional(), - fieldWithPath("description") - .description("Description of the migration, if any.").optional(), - fieldWithPath("executionTime") - .description( - "Execution time in milliseconds of an applied migration.") + return Arrays.asList(fieldWithPath("checksum").description("Checksum of the migration, if any.").optional(), + fieldWithPath("description").description("Description of the migration, if any.").optional(), + fieldWithPath("executionTime").description("Execution time in milliseconds of an applied migration.") .optional(), - fieldWithPath("installedBy") - .description("User that installed the applied migration, if any.") + fieldWithPath("installedBy").description("User that installed the applied migration, if any.") .optional(), - fieldWithPath("installedOn").description( - "Timestamp of when the applied migration was installed, " - + "if any.") + fieldWithPath("installedOn") + .description("Timestamp of when the applied migration was installed, " + "if any.").optional(), + fieldWithPath("installedRank") + .description("Rank of the applied migration, if any. Later migrations have " + "higher ranks.") .optional(), - fieldWithPath("installedRank").description( - "Rank of the applied migration, if any. Later migrations have " - + "higher ranks.") + fieldWithPath("script").description("Name of the script used to execute the migration, if any.") .optional(), - fieldWithPath("script").description( - "Name of the script used to execute the migration, if any.") - .optional(), - fieldWithPath("state").description("State of the migration. (" - + describeEnumValues(MigrationState.class) + ")"), - fieldWithPath("type").description("Type of the migration. (" - + describeEnumValues(MigrationType.class) + ")"), - fieldWithPath("version").description( - "Version of the database after applying the migration, " - + "if any.") - .optional()); + fieldWithPath("state") + .description("State of the migration. (" + describeEnumValues(MigrationState.class) + ")"), + fieldWithPath("type") + .description("Type of the migration. (" + describeEnumValues(MigrationType.class) + ")"), + fieldWithPath("version") + .description("Version of the database after applying the migration, " + "if any.").optional()); } @Configuration(proxyBeanMethods = false) @@ -104,9 +90,8 @@ public class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentati @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType( - EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) - .build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()).build(); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java index 45c030a9335..498e363c63c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java @@ -58,25 +58,20 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final List componentFields = Arrays.asList( - fieldWithPath("status") - .description("Status of a specific part of the application"), - subsectionWithPath("details").description( - "Details of the health of a specific part of the" + " application.")); + fieldWithPath("status").description("Status of a specific part of the application"), + subsectionWithPath("details") + .description("Details of the health of a specific part of the" + " application.")); @Test public void health() throws Exception { - this.mockMvc.perform(get("/actuator/health")).andExpect(status().isOk()) - .andDo(document("health", responseFields( - fieldWithPath("status") - .description("Overall status of the application."), - fieldWithPath("details").description( - "Details of the health of the application. Presence is controlled by " + this.mockMvc.perform(get("/actuator/health")).andExpect(status().isOk()).andDo(document("health", + responseFields(fieldWithPath("status").description("Overall status of the application."), + fieldWithPath("details") + .description("Details of the health of the application. Presence is controlled by " + "`management.endpoint.health.show-details`)."), - fieldWithPath("details.*.status").description( - "Status of a specific part of the application."), - subsectionWithPath("details.*.details").description( - "Details of the health of a specific part of the" - + " application.")))); + fieldWithPath("details.*.status").description("Status of a specific part of the application."), + subsectionWithPath("details.*.details") + .description("Details of the health of a specific part of the" + " application.")))); } @Test @@ -87,8 +82,7 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati @Test public void healthComponentInstance() throws Exception { - this.mockMvc.perform(get("/actuator/health/broker/us1")) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/actuator/health/broker/us1")).andExpect(status().isOk()) .andDo(document("health/instance", responseFields(componentFields))); } @@ -99,9 +93,8 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati @Bean public HealthEndpoint endpoint(Map healthIndicators) { - return new HealthEndpoint(new CompositeHealthIndicator( - new OrderedHealthAggregator(), new HealthIndicatorRegistryFactory() - .createHealthIndicatorRegistry(healthIndicators))); + return new HealthEndpoint(new CompositeHealthIndicator(new OrderedHealthAggregator(), + new HealthIndicatorRegistryFactory().createHealthIndicatorRegistry(healthIndicators))); } @Bean @@ -117,12 +110,9 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati @Bean public CompositeHealthIndicator brokerHealthIndicator() { Map indicators = new LinkedHashMap<>(); - indicators.put("us1", - () -> Health.up().withDetail("version", "1.0.2").build()); - indicators.put("us2", - () -> Health.up().withDetail("version", "1.0.4").build()); - return new CompositeHealthIndicator(new OrderedHealthAggregator(), - indicators); + indicators.put("us1", () -> Health.up().withDetail("version", "1.0.2").build()); + indicators.put("us2", () -> Health.up().withDetail("version", "1.0.4").build()); + return new CompositeHealthIndicator(new OrderedHealthAggregator(), indicators); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java index a5ea7a9630d..79ef92d34a8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java @@ -39,24 +39,21 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class HeapDumpWebEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void heapDump() throws Exception { this.mockMvc.perform(get("/actuator/heapdump")).andExpect(status().isOk()) - .andDo(document("heapdump", - new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { + .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { - @Override - protected Map createModel( - Operation operation) { - Map model = super.createModel(operation); - model.put("options", "-O"); - return model; - } + @Override + protected Map createModel(Operation operation) { + Map model = super.createModel(operation); + model.put("options", "-O"); + return model; + } - })); + })); } @Configuration(proxyBeanMethods = false) @@ -68,10 +65,8 @@ public class HeapDumpWebEndpointDocumentationTests return new HeapDumpWebEndpoint() { @Override - protected HeapDumper createHeapDumper() - throws HeapDumperUnavailableException { - return (file, live) -> FileCopyUtils.copy("<>", - new FileWriter(file)); + protected HeapDumper createHeapDumper() throws HeapDumperUnavailableException { + return (file, live) -> FileCopyUtils.copy("<>", new FileWriter(file)); } }; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java index e4cb7825cd3..48aa0a9099a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java @@ -52,8 +52,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class HttpTraceEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class HttpTraceEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @MockBean private HttpTraceRepository repository; @@ -63,55 +62,43 @@ public class HttpTraceEndpointDocumentationTests TraceableRequest request = mock(TraceableRequest.class); given(request.getUri()).willReturn(URI.create("https://api.example.com")); given(request.getMethod()).willReturn("GET"); - given(request.getHeaders()).willReturn(Collections - .singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); + given(request.getHeaders()) + .willReturn(Collections.singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); TraceableResponse response = mock(TraceableResponse.class); given(response.getStatus()).willReturn(200); - given(response.getHeaders()).willReturn(Collections.singletonMap( - HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); + given(response.getHeaders()) + .willReturn(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); HttpExchangeTracer tracer = new HttpExchangeTracer(EnumSet.allOf(Include.class)); HttpTrace trace = tracer.receivedRequest(request); - tracer.sendingResponse(trace, response, () -> principal, - () -> UUID.randomUUID().toString()); + tracer.sendingResponse(trace, response, () -> principal, () -> UUID.randomUUID().toString()); given(this.repository.findAll()).willReturn(Arrays.asList(trace)); this.mockMvc.perform(get("/actuator/httptrace")).andExpect(status().isOk()) .andDo(document("httptrace", responseFields( - fieldWithPath("traces").description( - "An array of traced HTTP request-response exchanges."), - fieldWithPath("traces.[].timestamp").description( - "Timestamp of when the traced exchange occurred."), - fieldWithPath("traces.[].principal") - .description("Principal of the exchange, if any.") + fieldWithPath("traces").description("An array of traced HTTP request-response exchanges."), + fieldWithPath("traces.[].timestamp") + .description("Timestamp of when the traced exchange occurred."), + fieldWithPath("traces.[].principal").description("Principal of the exchange, if any.") .optional(), - fieldWithPath("traces.[].principal.name") - .description("Name of the principal.").optional(), - fieldWithPath("traces.[].request.method") - .description("HTTP method of the request."), - fieldWithPath("traces.[].request.remoteAddress").description( - "Remote address from which the request was received, if known.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("traces.[].request.uri") - .description("URI of the request."), - fieldWithPath("traces.[].request.headers").description( - "Headers of the request, keyed by header name."), - fieldWithPath("traces.[].request.headers.*.[]") - .description("Values of the header"), - fieldWithPath("traces.[].response.status") - .description("Status of the response"), - fieldWithPath("traces.[].response.headers").description( - "Headers of the response, keyed by header name."), - fieldWithPath("traces.[].response.headers.*.[]") - .description("Values of the header"), - fieldWithPath("traces.[].session") - .description( - "Session associated with the exchange, if any.") + fieldWithPath("traces.[].principal.name").description("Name of the principal.").optional(), + fieldWithPath("traces.[].request.method").description("HTTP method of the request."), + fieldWithPath("traces.[].request.remoteAddress") + .description("Remote address from which the request was received, if known.").optional() + .type(JsonFieldType.STRING), + fieldWithPath("traces.[].request.uri").description("URI of the request."), + fieldWithPath("traces.[].request.headers") + .description("Headers of the request, keyed by header name."), + fieldWithPath("traces.[].request.headers.*.[]").description("Values of the header"), + fieldWithPath("traces.[].response.status").description("Status of the response"), + fieldWithPath("traces.[].response.headers") + .description("Headers of the response, keyed by header name."), + fieldWithPath("traces.[].response.headers.*.[]").description("Values of the header"), + fieldWithPath("traces.[].session").description("Session associated with the exchange, if any.") .optional(), - fieldWithPath("traces.[].session.id") - .description("ID of the session."), - fieldWithPath("traces.[].timeTaken").description( - "Time, in milliseconds, taken to handle the exchange.")))); + fieldWithPath("traces.[].session.id").description("ID of the session."), + fieldWithPath("traces.[].timeTaken") + .description("Time, in milliseconds, taken to handle the exchange.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java index 6c6937faa78..35e2413e403 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java @@ -51,33 +51,20 @@ public class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentation this.mockMvc.perform(get("/actuator/info")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("info", responseFields(beneathPath("git"), - fieldWithPath("branch") - .description("Name of the Git branch, if any."), - fieldWithPath("commit").description( - "Details of the Git commit, if any."), - fieldWithPath("commit.time") - .description("Timestamp of the commit, if any.") + fieldWithPath("branch").description("Name of the Git branch, if any."), + fieldWithPath("commit").description("Details of the Git commit, if any."), + fieldWithPath("commit.time").description("Timestamp of the commit, if any.") .type(JsonFieldType.VARIES), - fieldWithPath("commit.id") - .description("ID of the commit, if any.")), + fieldWithPath("commit.id").description("ID of the commit, if any.")), responseFields(beneathPath("build"), - fieldWithPath("artifact") - .description( - "Artifact ID of the application, if any.") + fieldWithPath("artifact").description("Artifact ID of the application, if any.") .optional(), - fieldWithPath("group") - .description( - "Group ID of the application, if any.") - .optional(), - fieldWithPath("name") - .description("Name of the application, if any.") + fieldWithPath("group").description("Group ID of the application, if any.").optional(), + fieldWithPath("name").description("Name of the application, if any.") .type(JsonFieldType.STRING).optional(), - fieldWithPath("version") - .description( - "Version of the application, if any.") - .optional(), - fieldWithPath("time").description( - "Timestamp of when the application was built, if any.") + fieldWithPath("version").description("Version of the application, if any.").optional(), + fieldWithPath("time") + .description("Timestamp of when the application was built, if any.") .type(JsonFieldType.VARIES).optional()))); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java index 424660905c5..ac5baf78e6d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java @@ -35,8 +35,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Tim Ysewyn */ -public class IntegrationGraphEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void graph() throws Exception { @@ -46,8 +45,7 @@ public class IntegrationGraphEndpointDocumentationTests @Test public void rebuild() throws Exception { - this.mockMvc.perform(post("/actuator/integrationgraph")) - .andExpect(status().isNoContent()) + this.mockMvc.perform(post("/actuator/integrationgraph")).andExpect(status().isNoContent()) .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); } @@ -62,8 +60,7 @@ public class IntegrationGraphEndpointDocumentationTests } @Bean - public IntegrationGraphEndpoint endpoint( - IntegrationGraphServer integrationGraphServer) { + public IntegrationGraphEndpoint endpoint(IntegrationGraphServer integrationGraphServer) { return new IntegrationGraphEndpoint(integrationGraphServer); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java index 1d9341ffbe2..e27b99c81a1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java @@ -43,50 +43,37 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class LiquibaseEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void liquibase() throws Exception { - FieldDescriptor changeSetsField = fieldWithPath( - "contexts.*.liquibaseBeans.*.changeSets") - .description("Change sets made by the Liquibase beans, keyed by " - + "bean name."); + FieldDescriptor changeSetsField = fieldWithPath("contexts.*.liquibaseBeans.*.changeSets") + .description("Change sets made by the Liquibase beans, keyed by " + "bean name."); this.mockMvc.perform(get("/actuator/liquibase")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("liquibase", - responseFields( - fieldWithPath("contexts") - .description("Application contexts keyed by id"), - changeSetsField).andWithPrefix( - "contexts.*.liquibaseBeans.*.changeSets[].", - getChangeSetFieldDescriptors()) + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), + changeSetsField) + .andWithPrefix("contexts.*.liquibaseBeans.*.changeSets[].", + getChangeSetFieldDescriptors()) .and(parentIdField()))); } private List getChangeSetFieldDescriptors() { - return Arrays.asList( - fieldWithPath("author").description("Author of the change set."), - fieldWithPath("changeLog") - .description("Change log that contains the change set."), + return Arrays.asList(fieldWithPath("author").description("Author of the change set."), + fieldWithPath("changeLog").description("Change log that contains the change set."), fieldWithPath("comments").description("Comments on the change set."), fieldWithPath("contexts").description("Contexts of the change set."), - fieldWithPath("dateExecuted") - .description("Timestamp of when the change set was executed."), - fieldWithPath("deploymentId") - .description("ID of the deployment that ran the change set."), - fieldWithPath("description") - .description("Description of the change set."), - fieldWithPath("execType").description("Execution type of the change set (" - + describeEnumValues(ExecType.class) + ")."), + fieldWithPath("dateExecuted").description("Timestamp of when the change set was executed."), + fieldWithPath("deploymentId").description("ID of the deployment that ran the change set."), + fieldWithPath("description").description("Description of the change set."), + fieldWithPath("execType") + .description("Execution type of the change set (" + describeEnumValues(ExecType.class) + ")."), fieldWithPath("id").description("ID of the change set."), - fieldWithPath("labels") - .description("Labels associated with the change set."), + fieldWithPath("labels").description("Labels associated with the change set."), fieldWithPath("checksum").description("Checksum of the change set."), - fieldWithPath("orderExecuted") - .description("Order of the execution of the change set."), - fieldWithPath("tag") - .description("Tag associated with the change set, if any.") - .optional().type(JsonFieldType.STRING)); + fieldWithPath("orderExecuted").description("Order of the execution of the change set."), + fieldWithPath("tag").description("Tag associated with the change set, if any.").optional() + .type(JsonFieldType.STRING)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java index 6aa04ccebfd..28d8ea3fe35 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java @@ -36,8 +36,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @TestPropertySource( properties = "logging.file.name=src/test/resources/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/sample.log") -public class LogFileWebEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void logFile() throws Exception { @@ -48,8 +47,7 @@ public class LogFileWebEndpointDocumentationTests @Test public void logFileRange() throws Exception { this.mockMvc.perform(get("/actuator/logfile").header("Range", "bytes=0-1023")) - .andExpect(status().isPartialContent()) - .andDo(MockMvcRestDocumentation.document("logfile/range")); + .andExpect(status().isPartialContent()).andDo(MockMvcRestDocumentation.document("logfile/range")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java index 082ec1db766..e21f21cc594 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java @@ -51,60 +51,49 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final List levelFields = Arrays.asList( - fieldWithPath("configuredLevel") - .description("Configured level of the logger, if any.").optional(), - fieldWithPath("effectiveLevel") - .description("Effective level of the logger.")); + fieldWithPath("configuredLevel").description("Configured level of the logger, if any.").optional(), + fieldWithPath("effectiveLevel").description("Effective level of the logger.")); @MockBean private LoggingSystem loggingSystem; @Test public void allLoggers() throws Exception { - given(this.loggingSystem.getSupportedLogLevels()) - .willReturn(EnumSet.allOf(LogLevel.class)); - given(this.loggingSystem.getLoggerConfigurations()).willReturn(Arrays.asList( - new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), - new LoggerConfiguration("com.example", LogLevel.DEBUG, LogLevel.DEBUG))); + given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); + given(this.loggingSystem.getLoggerConfigurations()) + .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), + new LoggerConfiguration("com.example", LogLevel.DEBUG, LogLevel.DEBUG))); this.mockMvc.perform(get("/actuator/loggers")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/all", responseFields( - fieldWithPath("levels") - .description("Levels support by the logging system."), - fieldWithPath("loggers").description("Loggers keyed by name.")) - .andWithPrefix("loggers.*.", levelFields))); + .andDo(MockMvcRestDocumentation.document("loggers/all", + responseFields(fieldWithPath("levels").description("Levels support by the logging system."), + fieldWithPath("loggers").description("Loggers keyed by name.")) + .andWithPrefix("loggers.*.", levelFields))); } @Test public void logger() throws Exception { - given(this.loggingSystem.getLoggerConfiguration("com.example")).willReturn( - new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); - this.mockMvc.perform(get("/actuator/loggers/com.example")) - .andExpect(status().isOk()).andDo(MockMvcRestDocumentation - .document("loggers/single", responseFields(levelFields))); + given(this.loggingSystem.getLoggerConfiguration("com.example")) + .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); + this.mockMvc.perform(get("/actuator/loggers/com.example")).andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/single", responseFields(levelFields))); } @Test public void setLogLevel() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/com.example") - .content("{\"configuredLevel\":\"debug\"}") + .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()).andDo( - MockMvcRestDocumentation.document("loggers/set", - requestFields(fieldWithPath("configuredLevel") - .description("Level for the logger. May be" - + " omitted to clear the level.") - .optional()))); + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/set", requestFields(fieldWithPath("configuredLevel") + .description("Level for the logger. May be" + " omitted to clear the level.").optional()))); verify(this.loggingSystem).setLogLevel("com.example", LogLevel.DEBUG); } @Test public void clearLogLevel() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/com.example").content("{}") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("loggers/clear")); + .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear")); verify(this.loggingSystem).setLogLevel("com.example", null); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java index e041b711a8e..0997629c9ac 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java @@ -61,10 +61,8 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r * @author Andy Wilkinson */ @ExtendWith(RestDocumentationExtension.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.main.web-application-type=reactive") -public class MappingsEndpointReactiveDocumentationTests - extends AbstractEndpointDocumentationTests { +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") +public class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumentationTests { @LocalServerPort private int port; @@ -73,92 +71,61 @@ public class MappingsEndpointReactiveDocumentationTests @BeforeEach public void webTestClient(RestDocumentationContextProvider restDocumentation) { - this.client = WebTestClient - .bindToServer().filter(documentationConfiguration(restDocumentation) - .snippets().withDefaults()) + this.client = WebTestClient.bindToServer() + .filter(documentationConfiguration(restDocumentation).snippets().withDefaults()) .baseUrl("http://localhost:" + this.port).build(); } @Test public void mappings() throws Exception { List requestMappingConditions = Arrays.asList( - requestMappingConditionField("") - .description("Details of the request mapping conditions.") - .optional(), - requestMappingConditionField(".consumes") - .description("Details of the consumes condition"), - requestMappingConditionField(".consumes.[].mediaType") - .description("Consumed media type."), - requestMappingConditionField(".consumes.[].negated") - .description("Whether the media type is negated."), - requestMappingConditionField(".headers") - .description("Details of the headers condition."), - requestMappingConditionField(".headers.[].name") - .description("Name of the header."), - requestMappingConditionField(".headers.[].value") - .description("Required value of the header, if any."), - requestMappingConditionField(".headers.[].negated") - .description("Whether the value is negated."), - requestMappingConditionField(".methods") - .description("HTTP methods that are handled."), - requestMappingConditionField(".params") - .description("Details of the params condition."), - requestMappingConditionField(".params.[].name") - .description("Name of the parameter."), + requestMappingConditionField("").description("Details of the request mapping conditions.").optional(), + requestMappingConditionField(".consumes").description("Details of the consumes condition"), + requestMappingConditionField(".consumes.[].mediaType").description("Consumed media type."), + requestMappingConditionField(".consumes.[].negated").description("Whether the media type is negated."), + requestMappingConditionField(".headers").description("Details of the headers condition."), + requestMappingConditionField(".headers.[].name").description("Name of the header."), + requestMappingConditionField(".headers.[].value").description("Required value of the header, if any."), + requestMappingConditionField(".headers.[].negated").description("Whether the value is negated."), + requestMappingConditionField(".methods").description("HTTP methods that are handled."), + requestMappingConditionField(".params").description("Details of the params condition."), + requestMappingConditionField(".params.[].name").description("Name of the parameter."), requestMappingConditionField(".params.[].value") .description("Required value of the parameter, if any."), - requestMappingConditionField(".params.[].negated") - .description("Whether the value is negated."), - requestMappingConditionField(".patterns").description( - "Patterns identifying the paths handled by the mapping."), - requestMappingConditionField(".produces") - .description("Details of the produces condition."), - requestMappingConditionField(".produces.[].mediaType") - .description("Produced media type."), - requestMappingConditionField(".produces.[].negated") - .description("Whether the media type is negated.")); + requestMappingConditionField(".params.[].negated").description("Whether the value is negated."), + requestMappingConditionField(".patterns") + .description("Patterns identifying the paths handled by the mapping."), + requestMappingConditionField(".produces").description("Details of the produces condition."), + requestMappingConditionField(".produces.[].mediaType").description("Produced media type."), + requestMappingConditionField(".produces.[].negated").description("Whether the media type is negated.")); List handlerMethod = Arrays.asList( - fieldWithPath("*.[].details.handlerMethod").optional() - .type(JsonFieldType.OBJECT) - .description("Details of the method, if any, " - + "that will handle requests to this mapping."), - fieldWithPath("*.[].details.handlerMethod.className") - .type(JsonFieldType.STRING) + fieldWithPath("*.[].details.handlerMethod").optional().type(JsonFieldType.OBJECT) + .description("Details of the method, if any, " + "that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerMethod.className").type(JsonFieldType.STRING) .description("Fully qualified name of the class of the method."), - fieldWithPath("*.[].details.handlerMethod.name") - .type(JsonFieldType.STRING).description("Name of the method."), - fieldWithPath("*.[].details.handlerMethod.descriptor") - .type(JsonFieldType.STRING) - .description("Descriptor of the method as specified in the Java " - + "Language Specification.")); + fieldWithPath("*.[].details.handlerMethod.name").type(JsonFieldType.STRING) + .description("Name of the method."), + fieldWithPath("*.[].details.handlerMethod.descriptor").type(JsonFieldType.STRING) + .description("Descriptor of the method as specified in the Java " + "Language Specification.")); List handlerFunction = Arrays.asList( - fieldWithPath("*.[].details.handlerFunction").optional() - .type(JsonFieldType.OBJECT) - .description("Details of the function, if any, that will handle " - + "requests to this mapping."), - fieldWithPath("*.[].details.handlerFunction.className") - .type(JsonFieldType.STRING).description( - "Fully qualified name of the class of the function.")); + fieldWithPath("*.[].details.handlerFunction").optional().type(JsonFieldType.OBJECT).description( + "Details of the function, if any, that will handle " + "requests to this mapping."), + fieldWithPath("*.[].details.handlerFunction.className").type(JsonFieldType.STRING) + .description("Fully qualified name of the class of the function.")); List dispatcherHandlerFields = new ArrayList<>(Arrays.asList( - fieldWithPath("*") - .description("Dispatcher handler mappings, if any, keyed by " - + "dispatcher handler bean name."), + fieldWithPath("*").description( + "Dispatcher handler mappings, if any, keyed by " + "dispatcher handler bean name."), fieldWithPath("*.[].details").optional().type(JsonFieldType.OBJECT) - .description("Additional implementation-specific " - + "details about the mapping. Optional."), + .description("Additional implementation-specific " + "details about the mapping. Optional."), fieldWithPath("*.[].handler").description("Handler for the mapping."), - fieldWithPath("*.[].predicate") - .description("Predicate for the mapping."))); + fieldWithPath("*.[].predicate").description("Predicate for the mapping."))); dispatcherHandlerFields.addAll(requestMappingConditions); dispatcherHandlerFields.addAll(handlerMethod); dispatcherHandlerFields.addAll(handlerFunction); - this.client.get().uri("/actuator/mappings").exchange().expectStatus().isOk() - .expectBody() - .consumeWith(document("mappings", - responseFields( - beneathPath("contexts.*.mappings.dispatcherHandlers") - .withSubsectionId("dispatcher-handlers"), - dispatcherHandlerFields))); + this.client.get().uri("/actuator/mappings").exchange().expectStatus().isOk().expectBody() + .consumeWith(document("mappings", responseFields( + beneathPath("contexts.*.mappings.dispatcherHandlers").withSubsectionId("dispatcher-handlers"), + dispatcherHandlerFields))); } private FieldDescriptor requestMappingConditionField(String path) { @@ -180,8 +147,7 @@ public class MappingsEndpointReactiveDocumentationTests } @Bean - public MappingsEndpoint mappingsEndpoint( - Collection descriptionProviders, + public MappingsEndpoint mappingsEndpoint(Collection descriptionProviders, ConfigurableApplicationContext context) { return new MappingsEndpoint(descriptionProviders, context); } @@ -201,10 +167,8 @@ public class MappingsEndpointReactiveDocumentationTests @RestController private static class ExampleController { - @PostMapping(path = "/", - consumes = { MediaType.APPLICATION_JSON_VALUE, "!application/xml" }, - produces = MediaType.TEXT_PLAIN_VALUE, headers = "X-Custom=Foo", - params = "a!=alpha") + @PostMapping(path = "/", consumes = { MediaType.APPLICATION_JSON_VALUE, "!application/xml" }, + produces = MediaType.TEXT_PLAIN_VALUE, headers = "X-Custom=Foo", params = "a!=alpha") public String example() { return "Hello World"; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java index 2c901dd2be0..420575bac23 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java @@ -62,8 +62,7 @@ import static org.springframework.restdocs.webtestclient.WebTestClientRestDocume */ @ExtendWith(RestDocumentationExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class MappingsEndpointServletDocumentationTests - extends AbstractEndpointDocumentationTests { +public class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocumentationTests { @LocalServerPort private int port; @@ -72,115 +71,76 @@ public class MappingsEndpointServletDocumentationTests @BeforeEach public void webTestClient(RestDocumentationContextProvider restDocumentation) { - this.client = WebTestClient.bindToServer() - .filter(documentationConfiguration(restDocumentation)) + this.client = WebTestClient.bindToServer().filter(documentationConfiguration(restDocumentation)) .baseUrl("http://localhost:" + this.port).build(); } @Test public void mappings() throws Exception { ResponseFieldsSnippet commonResponseFields = responseFields( - fieldWithPath("contexts") - .description("Application contexts keyed by id."), - fieldWithPath("contexts.*.mappings") - .description("Mappings in the context, keyed by mapping type."), + fieldWithPath("contexts").description("Application contexts keyed by id."), + fieldWithPath("contexts.*.mappings").description("Mappings in the context, keyed by mapping type."), subsectionWithPath("contexts.*.mappings.dispatcherServlets") .description("Dispatcher servlet mappings, if any."), subsectionWithPath("contexts.*.mappings.servletFilters") .description("Servlet filter mappings, if any."), - subsectionWithPath("contexts.*.mappings.servlets") - .description("Servlet mappings, if any."), + subsectionWithPath("contexts.*.mappings.servlets").description("Servlet mappings, if any."), subsectionWithPath("contexts.*.mappings.dispatcherHandlers") - .description("Dispatcher handler mappings, if any.").optional() - .type(JsonFieldType.OBJECT), + .description("Dispatcher handler mappings, if any.").optional().type(JsonFieldType.OBJECT), parentIdField()); List dispatcherServletFields = new ArrayList<>(Arrays.asList( - fieldWithPath("*") - .description("Dispatcher servlet mappings, if any, keyed by " - + "dispatcher servlet bean name."), + fieldWithPath("*").description( + "Dispatcher servlet mappings, if any, keyed by " + "dispatcher servlet bean name."), fieldWithPath("*.[].details").optional().type(JsonFieldType.OBJECT) - .description("Additional implementation-specific " - + "details about the mapping. Optional."), + .description("Additional implementation-specific " + "details about the mapping. Optional."), fieldWithPath("*.[].handler").description("Handler for the mapping."), - fieldWithPath("*.[].predicate") - .description("Predicate for the mapping."))); + fieldWithPath("*.[].predicate").description("Predicate for the mapping."))); List requestMappingConditions = Arrays.asList( - requestMappingConditionField("") - .description("Details of the request mapping conditions.") - .optional(), - requestMappingConditionField(".consumes") - .description("Details of the consumes condition"), - requestMappingConditionField(".consumes.[].mediaType") - .description("Consumed media type."), - requestMappingConditionField(".consumes.[].negated") - .description("Whether the media type is negated."), - requestMappingConditionField(".headers") - .description("Details of the headers condition."), - requestMappingConditionField(".headers.[].name") - .description("Name of the header."), - requestMappingConditionField(".headers.[].value") - .description("Required value of the header, if any."), - requestMappingConditionField(".headers.[].negated") - .description("Whether the value is negated."), - requestMappingConditionField(".methods") - .description("HTTP methods that are handled."), - requestMappingConditionField(".params") - .description("Details of the params condition."), - requestMappingConditionField(".params.[].name") - .description("Name of the parameter."), + requestMappingConditionField("").description("Details of the request mapping conditions.").optional(), + requestMappingConditionField(".consumes").description("Details of the consumes condition"), + requestMappingConditionField(".consumes.[].mediaType").description("Consumed media type."), + requestMappingConditionField(".consumes.[].negated").description("Whether the media type is negated."), + requestMappingConditionField(".headers").description("Details of the headers condition."), + requestMappingConditionField(".headers.[].name").description("Name of the header."), + requestMappingConditionField(".headers.[].value").description("Required value of the header, if any."), + requestMappingConditionField(".headers.[].negated").description("Whether the value is negated."), + requestMappingConditionField(".methods").description("HTTP methods that are handled."), + requestMappingConditionField(".params").description("Details of the params condition."), + requestMappingConditionField(".params.[].name").description("Name of the parameter."), requestMappingConditionField(".params.[].value") .description("Required value of the parameter, if any."), - requestMappingConditionField(".params.[].negated") - .description("Whether the value is negated."), - requestMappingConditionField(".patterns").description( - "Patterns identifying the paths handled by the mapping."), - requestMappingConditionField(".produces") - .description("Details of the produces condition."), - requestMappingConditionField(".produces.[].mediaType") - .description("Produced media type."), - requestMappingConditionField(".produces.[].negated") - .description("Whether the media type is negated.")); + requestMappingConditionField(".params.[].negated").description("Whether the value is negated."), + requestMappingConditionField(".patterns") + .description("Patterns identifying the paths handled by the mapping."), + requestMappingConditionField(".produces").description("Details of the produces condition."), + requestMappingConditionField(".produces.[].mediaType").description("Produced media type."), + requestMappingConditionField(".produces.[].negated").description("Whether the media type is negated.")); List handlerMethod = Arrays.asList( - fieldWithPath("*.[].details.handlerMethod").optional() - .type(JsonFieldType.OBJECT) - .description("Details of the method, if any, " - + "that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerMethod").optional().type(JsonFieldType.OBJECT) + .description("Details of the method, if any, " + "that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerMethod.className") .description("Fully qualified name of the class of the method."), - fieldWithPath("*.[].details.handlerMethod.name") - .description("Name of the method."), + fieldWithPath("*.[].details.handlerMethod.name").description("Name of the method."), fieldWithPath("*.[].details.handlerMethod.descriptor") - .description("Descriptor of the method as specified in the Java " - + "Language Specification.")); + .description("Descriptor of the method as specified in the Java " + "Language Specification.")); dispatcherServletFields.addAll(handlerMethod); dispatcherServletFields.addAll(requestMappingConditions); this.client.get().uri("/actuator/mappings").exchange().expectBody() - .consumeWith(document( - "mappings", commonResponseFields, - responseFields(beneathPath( - "contexts.*.mappings.dispatcherServlets") - .withSubsectionId("dispatcher-servlets"), - dispatcherServletFields), + .consumeWith(document("mappings", commonResponseFields, + responseFields(beneathPath("contexts.*.mappings.dispatcherServlets") + .withSubsectionId("dispatcher-servlets"), dispatcherServletFields), responseFields( - beneathPath("contexts.*.mappings.servletFilters") - .withSubsectionId("servlet-filters"), - fieldWithPath("[].servletNameMappings").description( - "Names of the servlets to which the filter is mapped."), - fieldWithPath("[].urlPatternMappings").description( - "URL pattern to which the filter is mapped."), - fieldWithPath("[].name") - .description("Name of the filter."), - fieldWithPath("[].className") - .description("Class name of the filter")), - responseFields( - beneathPath("contexts.*.mappings.servlets") - .withSubsectionId("servlets"), - fieldWithPath("[].mappings") - .description("Mappings of the servlet."), - fieldWithPath("[].name") - .description("Name of the servlet."), - fieldWithPath("[].className") - .description("Class name of the servlet")))); + beneathPath("contexts.*.mappings.servletFilters").withSubsectionId("servlet-filters"), + fieldWithPath("[].servletNameMappings") + .description("Names of the servlets to which the filter is mapped."), + fieldWithPath("[].urlPatternMappings") + .description("URL pattern to which the filter is mapped."), + fieldWithPath("[].name").description("Name of the filter."), + fieldWithPath("[].className").description("Class name of the filter")), + responseFields(beneathPath("contexts.*.mappings.servlets").withSubsectionId("servlets"), + fieldWithPath("[].mappings").description("Mappings of the servlet."), + fieldWithPath("[].name").description("Name of the servlet."), + fieldWithPath("[].className").description("Class name of the servlet")))); } private FieldDescriptor requestMappingConditionField(String path) { @@ -212,8 +172,7 @@ public class MappingsEndpointServletDocumentationTests } @Bean - public MappingsEndpoint mappingsEndpoint( - Collection descriptionProviders, + public MappingsEndpoint mappingsEndpoint(Collection descriptionProviders, ConfigurableApplicationContext context) { return new MappingsEndpoint(descriptionProviders, context); } @@ -228,10 +187,8 @@ public class MappingsEndpointServletDocumentationTests @RestController private static class ExampleController { - @PostMapping(path = "/", - consumes = { MediaType.APPLICATION_JSON_VALUE, "!application/xml" }, - produces = MediaType.TEXT_PLAIN_VALUE, headers = "X-Custom=Foo", - params = "a!=alpha") + @PostMapping(path = "/", consumes = { MediaType.APPLICATION_JSON_VALUE, "!application/xml" }, + produces = MediaType.TEXT_PLAIN_VALUE, headers = "X-Custom=Foo", params = "a!=alpha") public String example() { return "Hello World"; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java index 757fb9be044..99f6b5eb8ef 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java @@ -43,43 +43,34 @@ public class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentat @Test public void metricNames() throws Exception { - this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()) - .andDo(document("metrics/names", responseFields(fieldWithPath("names") - .description("Names of the known metrics.")))); + this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()).andDo(document("metrics/names", + responseFields(fieldWithPath("names").description("Names of the known metrics.")))); } @Test public void metric() throws Exception { - this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")) - .andExpect(status().isOk()) - .andDo(document("metrics/metric", responseFields( - fieldWithPath("name").description("Name of the metric"), - fieldWithPath("description") - .description("Description of the metric"), - fieldWithPath("baseUnit").description("Base unit of the metric"), - fieldWithPath("measurements") - .description("Measurements of the metric"), - fieldWithPath("measurements[].statistic") - .description("Statistic of the measurement. (" - + describeEnumValues(Statistic.class) + ")."), - fieldWithPath("measurements[].value") - .description("Value of the measurement."), - fieldWithPath("availableTags") - .description("Tags that are available for drill-down."), - fieldWithPath("availableTags[].tag") - .description("Name of the tag."), - fieldWithPath("availableTags[].values") - .description("Possible values of the tag.")))); + this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")).andExpect(status().isOk()) + .andDo(document("metrics/metric", + responseFields(fieldWithPath("name").description("Name of the metric"), + fieldWithPath("description").description("Description of the metric"), + fieldWithPath("baseUnit").description("Base unit of the metric"), + fieldWithPath("measurements").description("Measurements of the metric"), + fieldWithPath("measurements[].statistic").description( + "Statistic of the measurement. (" + describeEnumValues(Statistic.class) + ")."), + fieldWithPath("measurements[].value").description("Value of the measurement."), + fieldWithPath("availableTags").description("Tags that are available for drill-down."), + fieldWithPath("availableTags[].tag").description("Name of the tag."), + fieldWithPath("availableTags[].values").description("Possible values of the tag.")))); } @Test public void metricWithTags() throws Exception { - this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max") - .param("tag", "area:nonheap").param("tag", "id:Compressed Class Space")) + this.mockMvc + .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap").param("tag", + "id:Compressed Class Space")) .andExpect(status().isOk()) - .andDo(document("metrics/metric-with-tags", - requestParameters(parameterWithName("tag").description( - "A tag to use for drill-down in the form `name:value`.")))); + .andDo(document("metrics/metric-with-tags", requestParameters(parameterWithName("tag") + .description("A tag to use for drill-down in the form `name:value`.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java index 5d365a678ba..d2747a00462 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java @@ -36,8 +36,7 @@ import org.springframework.web.context.WebApplicationContext; */ @ExtendWith(RestDocumentationExtension.class) @SpringBootTest -public abstract class MockMvcEndpointDocumentationTests - extends AbstractEndpointDocumentationTests { +public abstract class MockMvcEndpointDocumentationTests extends AbstractEndpointDocumentationTests { protected MockMvc mockMvc; @@ -47,9 +46,7 @@ public abstract class MockMvcEndpointDocumentationTests @BeforeEach public void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation - .documentationConfiguration(restDocumentation).uris()) - .build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()).build(); } protected WebApplicationContext getApplicationContext() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java index 8161026898e..72becce0bed 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java @@ -36,13 +36,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class PrometheusScrapeEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void prometheus() throws Exception { - this.mockMvc.perform(get("/actuator/prometheus")).andExpect(status().isOk()) - .andDo(document("prometheus")); + this.mockMvc.perform(get("/actuator/prometheus")).andExpect(status().isOk()).andDo(document("prometheus")); } @Configuration(proxyBeanMethods = false) @@ -52,8 +50,8 @@ public class PrometheusScrapeEndpointDocumentationTests @Bean public PrometheusScrapeEndpoint endpoint() { CollectorRegistry collectorRegistry = new CollectorRegistry(true); - PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry( - (key) -> null, collectorRegistry, Clock.SYSTEM); + PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry((key) -> null, collectorRegistry, + Clock.SYSTEM); new JvmMemoryMetrics().bindTo(meterRegistry); return new PrometheusScrapeEndpoint(collectorRegistry); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java index 0341cfd6dd1..2097f852723 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java @@ -48,51 +48,40 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ScheduledTasksEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void scheduledTasks() throws Exception { - this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()) - .andDo(document("scheduled-tasks", - preprocessResponse(replacePattern(Pattern.compile( - "org.*\\.ScheduledTasksEndpointDocumentationTests\\$" - + "TestConfiguration"), - "com.example.Processor")), - responseFields( - fieldWithPath("cron").description("Cron tasks, if any."), - targetFieldWithPrefix("cron.[]."), - fieldWithPath("cron.[].expression") - .description("Cron expression."), - fieldWithPath("fixedDelay") - .description("Fixed delay tasks, if any."), - targetFieldWithPrefix("fixedDelay.[]."), - initialDelayWithPrefix("fixedDelay.[]."), - fieldWithPath("fixedDelay.[].interval").description( - "Interval, in milliseconds, between the end of the last" - + " execution and the start of the next."), - fieldWithPath("fixedRate") - .description("Fixed rate tasks, if any."), - targetFieldWithPrefix("fixedRate.[]."), - fieldWithPath("fixedRate.[].interval").description( - "Interval, in milliseconds, between the start of each execution."), - initialDelayWithPrefix("fixedRate.[]."), - fieldWithPath("custom").description( - "Tasks with custom triggers, if any."), - targetFieldWithPrefix("custom.[]."), - fieldWithPath("custom.[].trigger") - .description("Trigger for the task.")))) + this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()).andDo(document( + "scheduled-tasks", + preprocessResponse(replacePattern( + Pattern.compile("org.*\\.ScheduledTasksEndpointDocumentationTests\\$" + "TestConfiguration"), + "com.example.Processor")), + responseFields(fieldWithPath("cron").description("Cron tasks, if any."), + targetFieldWithPrefix("cron.[]."), + fieldWithPath("cron.[].expression").description("Cron expression."), + fieldWithPath("fixedDelay").description("Fixed delay tasks, if any."), + targetFieldWithPrefix("fixedDelay.[]."), initialDelayWithPrefix("fixedDelay.[]."), + fieldWithPath("fixedDelay.[].interval") + .description("Interval, in milliseconds, between the end of the last" + + " execution and the start of the next."), + fieldWithPath("fixedRate").description("Fixed rate tasks, if any."), + targetFieldWithPrefix("fixedRate.[]."), + fieldWithPath("fixedRate.[].interval") + .description("Interval, in milliseconds, between the start of each execution."), + initialDelayWithPrefix("fixedRate.[]."), + fieldWithPath("custom").description("Tasks with custom triggers, if any."), + targetFieldWithPrefix("custom.[]."), + fieldWithPath("custom.[].trigger").description("Trigger for the task.")))) .andDo(MockMvcResultHandlers.print()); } private FieldDescriptor targetFieldWithPrefix(String prefix) { - return fieldWithPath(prefix + "runnable.target") - .description("Target that will be executed."); + return fieldWithPath(prefix + "runnable.target").description("Target that will be executed."); } private FieldDescriptor initialDelayWithPrefix(String prefix) { - return fieldWithPath(prefix + "initialDelay") - .description("Delay, in milliseconds, before first execution."); + return fieldWithPath(prefix + "initialDelay").description("Delay, in milliseconds, before first execution."); } @Configuration(proxyBeanMethods = false) @@ -122,8 +111,7 @@ public class ScheduledTasksEndpointDocumentationTests @Bean public SchedulingConfigurer schedulingConfigurer() { - return (registrar) -> registrar.addTriggerTask(new CustomTriggeredRunnable(), - new CustomTrigger()); + return (registrar) -> registrar.addTriggerTask(new CustomTriggeredRunnable(), new CustomTrigger()); } static class CustomTrigger implements Trigger { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java index b087231f87b..a28495c62b1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java @@ -53,32 +53,25 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -@TestPropertySource( - properties = "spring.jackson.serialization.write-dates-as-timestamps=false") -public class SessionsEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +@TestPropertySource(properties = "spring.jackson.serialization.write-dates-as-timestamps=false") +public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { - private static final Session sessionOne = createSession( - Instant.now().minusSeconds(60 * 60 * 12), Instant.now().minusSeconds(45)); + private static final Session sessionOne = createSession(Instant.now().minusSeconds(60 * 60 * 12), + Instant.now().minusSeconds(45)); - private static final Session sessionTwo = createSession( - "4db5efcc-99cb-4d05-a52c-b49acfbb7ea9", + private static final Session sessionTwo = createSession("4db5efcc-99cb-4d05-a52c-b49acfbb7ea9", Instant.now().minusSeconds(60 * 60 * 5), Instant.now().minusSeconds(37)); - private static final Session sessionThree = createSession( - Instant.now().minusSeconds(60 * 60 * 2), Instant.now().minusSeconds(12)); + private static final Session sessionThree = createSession(Instant.now().minusSeconds(60 * 60 * 2), + Instant.now().minusSeconds(12)); private static final List sessionFields = Arrays.asList( fieldWithPath("id").description("ID of the session."), - fieldWithPath("attributeNames") - .description("Names of the attributes stored in the session."), - fieldWithPath("creationTime") - .description("Timestamp of when the session was created."), - fieldWithPath("lastAccessedTime") - .description("Timestamp of when the session was last accessed."), - fieldWithPath("maxInactiveInterval") - .description("Maximum permitted period of inactivity, in seconds, " - + "before the session will expire."), + fieldWithPath("attributeNames").description("Names of the attributes stored in the session."), + fieldWithPath("creationTime").description("Timestamp of when the session was created."), + fieldWithPath("lastAccessedTime").description("Timestamp of when the session was last accessed."), + fieldWithPath("maxInactiveInterval").description( + "Maximum permitted period of inactivity, in seconds, " + "before the session will expire."), fieldWithPath("expired").description("Whether the session has expired.")); @MockBean @@ -91,14 +84,11 @@ public class SessionsEndpointDocumentationTests sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionThree.getId(), sessionThree); given(this.sessionRepository.findByPrincipalName("alice")).willReturn(sessions); - this.mockMvc.perform(get("/actuator/sessions").param("username", "alice")) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/actuator/sessions").param("username", "alice")).andExpect(status().isOk()) .andDo(document("sessions/username", - responseFields(fieldWithPath("sessions") - .description("Sessions for the given username.")) - .andWithPrefix("sessions.[].", sessionFields), - requestParameters(parameterWithName("username") - .description("Name of the user.")))); + responseFields(fieldWithPath("sessions").description("Sessions for the given username.")) + .andWithPrefix("sessions.[].", sessionFields), + requestParameters(parameterWithName("username").description("Name of the user.")))); } @Test @@ -108,26 +98,22 @@ public class SessionsEndpointDocumentationTests sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionThree.getId(), sessionThree); given(this.sessionRepository.findById(sessionTwo.getId())).willReturn(sessionTwo); - this.mockMvc.perform(get("/actuator/sessions/{id}", sessionTwo.getId())) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isOk()) .andDo(document("sessions/id", responseFields(sessionFields))); } @Test public void deleteASession() throws Exception { - this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())) - .andExpect(status().isNoContent()).andDo(document("sessions/delete")); + this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent()) + .andDo(document("sessions/delete")); verify(this.sessionRepository).deleteById(sessionTwo.getId()); } - private static MapSession createSession(Instant creationTime, - Instant lastAccessedTime) { - return createSession(UUID.randomUUID().toString(), creationTime, - lastAccessedTime); + private static MapSession createSession(Instant creationTime, Instant lastAccessedTime) { + return createSession(UUID.randomUUID().toString(), creationTime, lastAccessedTime); } - private static MapSession createSession(String id, Instant creationTime, - Instant lastAccessedTime) { + private static MapSession createSession(String id, Instant creationTime, Instant lastAccessedTime) { MapSession session = new MapSession(id); session.setCreationTime(creationTime); session.setLastAccessedTime(lastAccessedTime); @@ -139,8 +125,7 @@ public class SessionsEndpointDocumentationTests static class TestConfiguration { @Bean - public SessionsEndpoint endpoint( - FindByIndexNameSessionRepository sessionRepository) { + public SessionsEndpoint endpoint(FindByIndexNameSessionRepository sessionRepository) { return new SessionsEndpoint(sessionRepository); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java index 6e254e46002..f8a386ccd34 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java @@ -36,15 +36,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ShutdownEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void shutdown() throws Exception { this.mockMvc.perform(post("/actuator/shutdown")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("shutdown", - responseFields(fieldWithPath("message").description( - "Message describing the result of the request.")))); + .andDo(MockMvcRestDocumentation.document("shutdown", responseFields( + fieldWithPath("message").description("Message describing the result of the request.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java index 21bb4c219e1..2994b259ab6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java @@ -40,8 +40,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ThreadDumpEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test public void threadDump() throws Exception { @@ -62,151 +61,102 @@ public class ThreadDumpEndpointDocumentationTests } }).start(); this.mockMvc.perform(get("/actuator/threaddump")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("threaddump", - preprocessResponse(limit("threads")), - responseFields( - fieldWithPath("threads").description("JVM's threads."), - fieldWithPath("threads.[].blockedCount").description( - "Total number of times that the thread has been " - + "blocked."), - fieldWithPath("threads.[].blockedTime").description( - "Time in milliseconds that the thread has spent " - + "blocked. -1 if thread contention " - + "monitoring is disabled."), + .andDo(MockMvcRestDocumentation.document("threaddump", preprocessResponse(limit("threads")), + responseFields(fieldWithPath("threads").description("JVM's threads."), + fieldWithPath("threads.[].blockedCount") + .description("Total number of times that the thread has been " + "blocked."), + fieldWithPath("threads.[].blockedTime") + .description("Time in milliseconds that the thread has spent " + + "blocked. -1 if thread contention " + "monitoring is disabled."), fieldWithPath("threads.[].daemon") .description("Whether the thread is a daemon " - + "thread. Only available on Java 9 or " - + "later.") + + "thread. Only available on Java 9 or " + "later.") .optional().type(JsonFieldType.BOOLEAN), - fieldWithPath("threads.[].inNative").description( - "Whether the thread is executing native code."), - fieldWithPath("threads.[].lockName") - .description( - "Description of the object on which the " - + "thread is blocked, if any.") + fieldWithPath("threads.[].inNative") + .description("Whether the thread is executing native code."), + fieldWithPath("threads.[].lockName").description( + "Description of the object on which the " + "thread is blocked, if any.") .optional().type(JsonFieldType.STRING), fieldWithPath("threads.[].lockInfo") - .description( - "Object for which the thread is blocked " - + "waiting.") - .optional().type(JsonFieldType.OBJECT), + .description("Object for which the thread is blocked " + "waiting.").optional() + .type(JsonFieldType.OBJECT), fieldWithPath("threads.[].lockInfo.className") - .description( - "Fully qualified class name of the lock" - + " object.") - .optional().type(JsonFieldType.STRING), + .description("Fully qualified class name of the lock" + " object.").optional() + .type(JsonFieldType.STRING), fieldWithPath("threads.[].lockInfo.identityHashCode") - .description( - "Identity hash code of the lock object.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockedMonitors").description( - "Monitors locked by this thread, if any"), + .description("Identity hash code of the lock object.").optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockedMonitors") + .description("Monitors locked by this thread, if any"), fieldWithPath("threads.[].lockedMonitors.[].className") - .description("Class name of the lock object.") - .optional().type(JsonFieldType.STRING), - fieldWithPath( - "threads.[].lockedMonitors.[].identityHashCode") - .description( - "Identity hash code of the lock " - + "object.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath( - "threads.[].lockedMonitors.[].lockedStackDepth") - .description( - "Stack depth where the monitor " - + "was locked.") - .optional().type(JsonFieldType.NUMBER), - subsectionWithPath( - "threads.[].lockedMonitors.[].lockedStackFrame") - .description( - "Stack frame that locked the " - + "monitor.") - .optional().type(JsonFieldType.OBJECT), + .description("Class name of the lock object.").optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockedMonitors.[].identityHashCode") + .description("Identity hash code of the lock " + "object.").optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockedMonitors.[].lockedStackDepth") + .description("Stack depth where the monitor " + "was locked.").optional() + .type(JsonFieldType.NUMBER), + subsectionWithPath("threads.[].lockedMonitors.[].lockedStackFrame") + .description("Stack frame that locked the " + "monitor.").optional() + .type(JsonFieldType.OBJECT), fieldWithPath("threads.[].lockedSynchronizers") - .description( - "Synchronizers locked by this thread."), - fieldWithPath( - "threads.[].lockedSynchronizers.[].className") - .description("Class name of the locked " - + "synchronizer.") - .optional().type(JsonFieldType.STRING), - fieldWithPath( - "threads.[].lockedSynchronizers.[].identityHashCode") - .description( - "Identity hash code of the locked " - + "synchronizer.") - .optional().type(JsonFieldType.NUMBER), + .description("Synchronizers locked by this thread."), + fieldWithPath("threads.[].lockedSynchronizers.[].className").description( + "Class name of the locked " + "synchronizer.").optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockedSynchronizers.[].identityHashCode").description( + "Identity hash code of the locked " + "synchronizer.").optional() + .type(JsonFieldType.NUMBER), fieldWithPath("threads.[].lockOwnerId").description( "ID of the thread that owns the object on which " - + "the thread is blocked. `-1` if the " - + "thread is not blocked."), + + "the thread is blocked. `-1` if the " + "thread is not blocked."), fieldWithPath("threads.[].lockOwnerName") .description("Name of the thread that owns the " - + "object on which the thread is " - + "blocked, if any.") + + "object on which the thread is " + "blocked, if any.") .optional().type(JsonFieldType.STRING), fieldWithPath("threads.[].priority") - .description("Priority of the thread. Only " - + "available on Java 9 or later.") + .description("Priority of the thread. Only " + "available on Java 9 or later.") .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].stackTrace") - .description("Stack trace of the thread."), - fieldWithPath("threads.[].stackTrace.[].classLoaderName") - .description("Name of the class loader of the " - + "class that contains the execution " + fieldWithPath("threads.[].stackTrace").description("Stack trace of the thread."), + fieldWithPath("threads.[].stackTrace.[].classLoaderName").description( + "Name of the class loader of the " + "class that contains the execution " + "point identified by this entry, if " - + "any. Only available on Java 9 or " - + "later.") + + "any. Only available on Java 9 or " + "later.") .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].className") - .description( - "Name of the class that contains the " - + "execution point identified " - + "by this entry."), + fieldWithPath("threads.[].stackTrace.[].className").description( + "Name of the class that contains the " + "execution point identified " + + "by this entry."), fieldWithPath("threads.[].stackTrace.[].fileName") - .description("Name of the source file that " - + "contains the execution point " + .description("Name of the source file that " + "contains the execution point " + "identified by this entry, if any.") .optional().type(JsonFieldType.STRING), fieldWithPath("threads.[].stackTrace.[].lineNumber") .description("Line number of the execution " - + "point identified by this entry. " - + "Negative if unknown."), - fieldWithPath("threads.[].stackTrace.[].methodName") - .description("Name of the method."), + + "point identified by this entry. " + "Negative if unknown."), + fieldWithPath("threads.[].stackTrace.[].methodName").description("Name of the method."), fieldWithPath("threads.[].stackTrace.[].moduleName") .description("Name of the module that contains " + "the execution point identified by " - + "this entry, if any. Only available " - + "on Java 9 or later.") + + "this entry, if any. Only available " + "on Java 9 or later.") .optional().type(JsonFieldType.STRING), fieldWithPath("threads.[].stackTrace.[].moduleVersion") - .description("Version of the module that " - + "contains the execution point " + .description("Version of the module that " + "contains the execution point " + "identified by this entry, if any. " + "Only available on Java 9 or later.") .optional().type(JsonFieldType.STRING), fieldWithPath("threads.[].stackTrace.[].nativeMethod") - .description( - "Whether the execution point is a native " - + "method."), - fieldWithPath("threads.[].suspended") - .description("Whether the thread is suspended."), - fieldWithPath("threads.[].threadId") - .description("ID of the thread."), - fieldWithPath("threads.[].threadName") - .description("Name of the thread."), - fieldWithPath("threads.[].threadState") - .description("State of the thread (" - + describeEnumValues(Thread.State.class) - + ")."), + .description("Whether the execution point is a native " + "method."), + fieldWithPath("threads.[].suspended").description("Whether the thread is suspended."), + fieldWithPath("threads.[].threadId").description("ID of the thread."), + fieldWithPath("threads.[].threadName").description("Name of the thread."), + fieldWithPath("threads.[].threadState").description( + "State of the thread (" + describeEnumValues(Thread.State.class) + ")."), fieldWithPath("threads.[].waitedCount").description( - "Total number of times that the thread has waited" - + " for notification."), - fieldWithPath("threads.[].waitedTime").description( - "Time in milliseconds that the thread has spent " - + "waiting. -1 if thread contention " - + "monitoring is disabled")))); + "Total number of times that the thread has waited" + " for notification."), + fieldWithPath("threads.[].waitedTime") + .description("Time in milliseconds that the thread has spent " + + "waiting. -1 if thread contention " + "monitoring is disabled")))); latch.countDown(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java index c8de53d60ef..9cd777d37eb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java @@ -47,24 +47,21 @@ public class JerseyWebEndpointManagementContextConfigurationTests { @Test public void resourceConfigCustomizerForEndpointsIsAutoConfigured() { - this.runner.run((context) -> assertThat(context) - .hasSingleBean(ResourceConfigCustomizer.class)); + this.runner.run((context) -> assertThat(context).hasSingleBean(ResourceConfigCustomizer.class)); } @Test public void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(JerseySameManagementContextConfiguration.class)); - contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test public void autoConfigurationIsConditionalOnClassResourceConfig() { this.runner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java index 27209f64d5c..9e2e0e2d6b4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java @@ -39,13 +39,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class EnvironmentEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=env") + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") .withSystemProperties("dbPassword=123456", "apiKey=123456") .run(validateSystemProperties("******", "******")); } @@ -53,43 +51,36 @@ public class EnvironmentEndpointAutoConfigurationTests { @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.env.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(EnvironmentEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(EnvironmentEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); } @Test public void keysToSanitizeCanBeConfiguredViaTheEnvironment() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=env") + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") .withSystemProperties("dbPassword=123456", "apiKey=123456") .withPropertyValues("management.endpoint.env.keys-to-sanitize=.*pass.*") .run(validateSystemProperties("******", "123456")); } - private ContextConsumer validateSystemProperties( - String dbPassword, String apiKey) { + private ContextConsumer validateSystemProperties(String dbPassword, String apiKey) { return (context) -> { assertThat(context).hasSingleBean(EnvironmentEndpoint.class); EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); EnvironmentDescriptor env = endpoint.environment(null); - Map systemProperties = getSource( - "systemProperties", env).getProperties(); - assertThat(systemProperties.get("dbPassword").getValue()) - .isEqualTo(dbPassword); + Map systemProperties = getSource("systemProperties", env).getProperties(); + assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo(dbPassword); assertThat(systemProperties.get("apiKey").getValue()).isEqualTo(apiKey); }; } - private PropertySourceDescriptor getSource(String name, - EnvironmentDescriptor descriptor) { - return descriptor.getPropertySources().stream() - .filter((source) -> name.equals(source.getName())).findFirst().get(); + private PropertySourceDescriptor getSource(String name, EnvironmentDescriptor descriptor) { + return descriptor.getPropertySources().stream().filter((source) -> name.equals(source.getName())).findFirst() + .get(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java index cc5587954a4..82e7122a4f1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java @@ -34,29 +34,24 @@ import static org.mockito.Mockito.mock; public class FlywayEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) .withBean(Flyway.class, () -> mock(Flyway.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=flyway") - .run((context) -> assertThat(context) - .hasSingleBean(FlywayEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=flyway") + .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.flyway.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(FlywayEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java index a7b0b3c8aa5..39a47af214a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java @@ -42,34 +42,28 @@ import static org.mockito.Mockito.verify; */ public class HealthEndpointAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); @Test public void healthEndpointShowDetailsDefault() { - this.contextRunner - .withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator) - .run((context) -> { - ReactiveHealthIndicator indicator = context.getBean( - "reactiveHealthIndicator", ReactiveHealthIndicator.class); - verify(indicator, never()).health(); - Health health = context.getBean(HealthEndpoint.class).health(); - assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).isNotEmpty(); - verify(indicator, times(1)).health(); - }); + this.contextRunner.withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> { + ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator", + ReactiveHealthIndicator.class); + verify(indicator, never()).health(); + Health health = context.getBean(HealthEndpoint.class).health(); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails()).isNotEmpty(); + verify(indicator, times(1)).health(); + }); } @Test public void healthEndpointAdaptReactiveHealthIndicator() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator) - .run((context) -> { - ReactiveHealthIndicator indicator = context.getBean( - "reactiveHealthIndicator", ReactiveHealthIndicator.class); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") + .withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> { + ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator", + ReactiveHealthIndicator.class); verify(indicator, never()).health(); Health health = context.getBean(HealthEndpoint.class).health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -80,23 +74,18 @@ public class HealthEndpointAutoConfigurationTests { @Test public void healthEndpointMergeRegularAndReactive() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .withBean("simpleHealthIndicator", HealthIndicator.class, - this::simpleHealthIndicator) - .withBean("reactiveHealthIndicator", ReactiveHealthIndicator.class, - this::reactiveHealthIndicator) + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") + .withBean("simpleHealthIndicator", HealthIndicator.class, this::simpleHealthIndicator) + .withBean("reactiveHealthIndicator", ReactiveHealthIndicator.class, this::reactiveHealthIndicator) .run((context) -> { - HealthIndicator indicator = context.getBean("simpleHealthIndicator", - HealthIndicator.class); - ReactiveHealthIndicator reactiveHealthIndicator = context.getBean( - "reactiveHealthIndicator", ReactiveHealthIndicator.class); + HealthIndicator indicator = context.getBean("simpleHealthIndicator", HealthIndicator.class); + ReactiveHealthIndicator reactiveHealthIndicator = context.getBean("reactiveHealthIndicator", + ReactiveHealthIndicator.class); verify(indicator, never()).health(); verify(reactiveHealthIndicator, never()).health(); Health health = context.getBean(HealthEndpoint.class).health(); assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnlyKeys("simple", - "reactive"); + assertThat(health.getDetails()).containsOnlyKeys("simple", "reactive"); verify(indicator, times(1)).health(); verify(reactiveHealthIndicator, times(1)).health(); }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java index babb870ed90..4d61cdc5df7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java @@ -52,347 +52,258 @@ import static org.mockito.Mockito.mock; public class HealthEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration( - AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class)); + .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration(AutoConfigurations + .of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); @Test public void runShouldCreateExtensionBeans() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(HealthEndpointWebExtension.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); } @Test public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HealthEndpointWebExtension.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HealthEndpointWebExtension.class)); } @Test public void runWithCustomHealthMappingShouldMapStatusCode() { - this.contextRunner - .withPropertyValues("management.health.status.http-mapping.CUSTOM=500") - .run((context) -> { - Object extension = context.getBean(HealthEndpointWebExtension.class); - HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils - .getField(extension, "responseMapper"); - Class securityContext = SecurityContext.class; - assertThat(responseMapper - .map(Health.down().build(), mock(securityContext)) - .getStatus()).isEqualTo(503); - assertThat(responseMapper.map(Health.status("OUT_OF_SERVICE").build(), - mock(securityContext)).getStatus()).isEqualTo(503); - assertThat(responseMapper - .map(Health.status("CUSTOM").build(), mock(securityContext)) - .getStatus()).isEqualTo(500); - }); + this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> { + Object extension = context.getBean(HealthEndpointWebExtension.class); + HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils + .getField(extension, "responseMapper"); + Class securityContext = SecurityContext.class; + assertThat(responseMapper.map(Health.down().build(), mock(securityContext)).getStatus()).isEqualTo(503); + assertThat(responseMapper.map(Health.status("OUT_OF_SERVICE").build(), mock(securityContext)).getStatus()) + .isEqualTo(503); + assertThat(responseMapper.map(Health.status("CUSTOM").build(), mock(securityContext)).getStatus()) + .isEqualTo(500); + }); } @Test public void unauthenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertThat( - extension.health(mock(SecurityContext.class)).getBody().getDetails()) - .isEmpty(); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty(); }); } @Test public void authenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); - assertThat(extension.health(securityContext).getBody().getDetails()) - .isEmpty(); + assertThat(extension.health(securityContext).getBody().getDetails()).isEmpty(); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { - this.contextRunner - .withPropertyValues( - "management.endpoint.health.show-details=when-authorized") + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); - assertThat(extension.health(securityContext).getBody().getDetails()) - .isNotEmpty(); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); + assertThat(extension.health(securityContext).getBody().getDetails()).isNotEmpty(); }); } @Test public void unauthenticatedUsersCanBeShownDetails() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertThat(extension.health(null).getBody().getDetails()) - .isNotEmpty(); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertThat(extension.health(null).getBody().getDetails()).isNotEmpty(); + }); } @Test public void detailsCanBeHiddenFromAuthenticatedUsers() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=never") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertThat(extension.health(mock(SecurityContext.class)).getBody() - .getDetails()).isEmpty(); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty(); + }); } @Test public void detailsCanBeHiddenFromUnauthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); - assertThat(extension.health(securityContext).getBody().getDetails()) - .isEmpty(); + assertThat(extension.health(securityContext).getBody().getDetails()).isEmpty(); }); } @Test public void detailsCanBeShownToAuthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); - assertThat(extension.health(securityContext).getBody().getDetails()) - .isNotEmpty(); + assertThat(extension.health(securityContext).getBody().getDetails()).isNotEmpty(); }); } @Test public void unauthenticatedUsersAreNotShownComponentByDefault() { this.contextRunner.run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertDetailsNotFound( - extension.healthForComponent(mock(SecurityContext.class), "simple")); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple")); }); } @Test public void authenticatedUsersAreNotShownComponentByDefault() { this.contextRunner.run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); - assertDetailsNotFound( - extension.healthForComponent(securityContext, "simple")); + assertDetailsNotFound(extension.healthForComponent(securityContext, "simple")); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownComponent() { - this.contextRunner - .withPropertyValues( - "management.endpoint.health.show-details=when-authorized") + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); - assertSimpleComponent( - extension.healthForComponent(securityContext, "simple")); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); + assertSimpleComponent(extension.healthForComponent(securityContext, "simple")); }); } @Test public void unauthenticatedUsersCanBeShownComponent() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertSimpleComponent(extension.healthForComponent(null, "simple")); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertSimpleComponent(extension.healthForComponent(null, "simple")); + }); } @Test public void componentCanBeHiddenFromAuthenticatedUsers() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=never") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertDetailsNotFound(extension - .healthForComponent(mock(SecurityContext.class), "simple")); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple")); + }); } @Test public void componentCanBeHiddenFromUnauthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); - assertDetailsNotFound( - extension.healthForComponent(securityContext, "simple")); + assertDetailsNotFound(extension.healthForComponent(securityContext, "simple")); }); } @Test public void componentCanBeShownToAuthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); - assertSimpleComponent( - extension.healthForComponent(securityContext, "simple")); + assertSimpleComponent(extension.healthForComponent(securityContext, "simple")); }); } @Test public void componentThatDoesNotExistMapTo404() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertDetailsNotFound( - extension.healthForComponent(null, "does-not-exist")); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertDetailsNotFound(extension.healthForComponent(null, "does-not-exist")); + }); } @Test public void unauthenticatedUsersAreNotShownComponentInstanceByDefault() { this.contextRunner.run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertDetailsNotFound(extension.healthForComponentInstance( - mock(SecurityContext.class), "composite", "one")); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertDetailsNotFound( + extension.healthForComponentInstance(mock(SecurityContext.class), "composite", "one")); }); } @Test public void authenticatedUsersAreNotShownComponentInstanceByDefault() { this.contextRunner.run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); - assertDetailsNotFound(extension.healthForComponentInstance(securityContext, - "composite", "one")); + assertDetailsNotFound(extension.healthForComponentInstance(securityContext, "composite", "one")); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownComponentInstance() { - this.contextRunner - .withPropertyValues( - "management.endpoint.health.show-details=when-authorized") + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); - assertSimpleComponent(extension.healthForComponentInstance( - securityContext, "composite", "one")); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); + assertSimpleComponent(extension.healthForComponentInstance(securityContext, "composite", "one")); }); } @Test public void unauthenticatedUsersCanBeShownComponentInstance() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertSimpleComponent(extension.healthForComponentInstance(null, - "composite", "one")); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertSimpleComponent(extension.healthForComponentInstance(null, "composite", "one")); + }); } @Test public void componentInstanceCanBeHiddenFromAuthenticatedUsers() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=never") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertDetailsNotFound(extension.healthForComponentInstance( - mock(SecurityContext.class), "composite", "one")); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertDetailsNotFound( + extension.healthForComponentInstance(mock(SecurityContext.class), "composite", "one")); + }); } @Test public void componentInstanceCanBeHiddenFromUnauthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); - assertDetailsNotFound(extension.healthForComponentInstance( - securityContext, "composite", "one")); + assertDetailsNotFound(extension.healthForComponentInstance(securityContext, "composite", "one")); }); } @Test public void componentInstanceCanBeShownToAuthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); - assertSimpleComponent(extension.healthForComponentInstance( - securityContext, "composite", "one")); + assertSimpleComponent(extension.healthForComponentInstance(securityContext, "composite", "one")); }); } @Test public void componentInstanceThatDoesNotExistMapTo404() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); - assertDetailsNotFound(extension.healthForComponentInstance(null, - "composite", "does-not-exist")); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertDetailsNotFound(extension.healthForComponentInstance(null, "composite", "does-not-exist")); + }); } private void assertDetailsNotFound(WebEndpointResponse response) { @@ -407,17 +318,13 @@ public class HealthEndpointWebExtensionTests { @Test public void roleCanBeCustomized() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ADMIN").run((context) -> { - HealthEndpointWebExtension extension = context - .getBean(HealthEndpointWebExtension.class); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ADMIN")).willReturn(true); - assertThat(extension.health(securityContext).getBody().getDetails()) - .isNotEmpty(); + assertThat(extension.health(securityContext).getBody().getDetails()).isNotEmpty(); }); } @@ -434,8 +341,7 @@ public class HealthEndpointWebExtensionTests { Map nestedIndicators = new HashMap<>(); nestedIndicators.put("one", healthIndicator); nestedIndicators.put("two", () -> Health.up().build()); - return new CompositeHealthIndicator(new OrderedHealthAggregator(), - nestedIndicators); + return new CompositeHealthIndicator(new OrderedHealthAggregator(), nestedIndicators); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java index 8203b34483d..6f74e1de767 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java @@ -43,14 +43,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class HealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HealthIndicatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthIndicatorAutoConfiguration.class)); @Test public void runWhenNoOtherIndicatorsShouldCreateDefaultApplicationHealthIndicator() { - this.contextRunner - .run((context) -> assertThat(context).getBean(HealthIndicator.class) - .isInstanceOf(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).getBean(HealthIndicator.class) + .isInstanceOf(ApplicationHealthIndicator.class)); } @Test @@ -63,17 +61,15 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void runWhenHasDefaultsDisabledAndNoSingleIndicatorEnabledShouldCreateDefaultApplicationHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .withPropertyValues("management.health.defaults.enabled:false") - .run((context) -> assertThat(context).getBean(HealthIndicator.class) - .isInstanceOf(ApplicationHealthIndicator.class)); + .withPropertyValues("management.health.defaults.enabled:false").run((context) -> assertThat(context) + .getBean(HealthIndicator.class).isInstanceOf(ApplicationHealthIndicator.class)); } @Test public void runWhenHasDefaultsDisabledAndSingleIndicatorEnabledShouldCreateEnabledIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .withPropertyValues("management.health.defaults.enabled:false", - "management.health.custom.enabled:true") + .withPropertyValues("management.health.defaults.enabled:false", "management.health.custom.enabled:true") .run((context) -> assertThat(context).getBean(HealthIndicator.class) .isInstanceOf(CustomHealthIndicator.class)); @@ -81,29 +77,25 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void runShouldCreateOrderedHealthAggregator() { - this.contextRunner - .run((context) -> assertThat(context).getBean(HealthAggregator.class) - .isInstanceOf(OrderedHealthAggregator.class)); + this.contextRunner.run((context) -> assertThat(context).getBean(HealthAggregator.class) + .isInstanceOf(OrderedHealthAggregator.class)); } @Test public void runWhenHasCustomOrderPropertyShouldCreateOrderedHealthAggregator() { - this.contextRunner.withPropertyValues("management.health.status.order:UP,DOWN") - .run((context) -> { - OrderedHealthAggregator aggregator = context - .getBean(OrderedHealthAggregator.class); - Map healths = new LinkedHashMap<>(); - healths.put("foo", Health.up().build()); - healths.put("bar", Health.down().build()); - Health aggregate = aggregator.aggregate(healths); - assertThat(aggregate.getStatus()).isEqualTo(Status.UP); - }); + this.contextRunner.withPropertyValues("management.health.status.order:UP,DOWN").run((context) -> { + OrderedHealthAggregator aggregator = context.getBean(OrderedHealthAggregator.class); + Map healths = new LinkedHashMap<>(); + healths.put("foo", Health.up().build()); + healths.put("bar", Health.down().build()); + Health aggregate = aggregator.aggregate(healths); + assertThat(aggregate.getStatus()).isEqualTo(Status.UP); + }); } @Test public void runWhenHasCustomHealthAggregatorShouldNotCreateOrderedHealthAggregator() { - this.contextRunner - .withUserConfiguration(CustomHealthAggregatorConfiguration.class) + this.contextRunner.withUserConfiguration(CustomHealthAggregatorConfiguration.class) .run((context) -> assertThat(context).getBean(HealthAggregator.class) .isNotInstanceOf(OrderedHealthAggregator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java index a793bb5ad72..eb8aa08d83a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java @@ -49,196 +49,157 @@ import static org.mockito.Mockito.mock; public class ReactiveHealthEndpointWebExtensionTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withUserConfiguration(HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class); + .withUserConfiguration(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class); @Test public void runShouldCreateExtensionBeans() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ReactiveHealthEndpointWebExtension.class)); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } @Test public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveHealthEndpointWebExtension.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveHealthEndpointWebExtension.class)); } @Test public void runWithCustomHealthMappingShouldMapStatusCode() { - this.contextRunner - .withPropertyValues("management.health.status.http-mapping.CUSTOM=500") - .run((context) -> { - Object extension = context - .getBean(ReactiveHealthEndpointWebExtension.class); - HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils - .getField(extension, "responseMapper"); - Class securityContext = SecurityContext.class; - assertThat(responseMapper - .map(Health.down().build(), mock(securityContext)) - .getStatus()).isEqualTo(503); - assertThat(responseMapper.map(Health.status("OUT_OF_SERVICE").build(), - mock(securityContext)).getStatus()).isEqualTo(503); - assertThat(responseMapper - .map(Health.status("CUSTOM").build(), mock(securityContext)) - .getStatus()).isEqualTo(500); - }); + this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> { + Object extension = context.getBean(ReactiveHealthEndpointWebExtension.class); + HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils + .getField(extension, "responseMapper"); + Class securityContext = SecurityContext.class; + assertThat(responseMapper.map(Health.down().build(), mock(securityContext)).getStatus()).isEqualTo(503); + assertThat(responseMapper.map(Health.status("OUT_OF_SERVICE").build(), mock(securityContext)).getStatus()) + .isEqualTo(503); + assertThat(responseMapper.map(Health.status("CUSTOM").build(), mock(securityContext)).getStatus()) + .isEqualTo(500); + }); } @Test public void regularAndReactiveHealthIndicatorsMatch() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .withUserConfiguration(HealthIndicatorsConfiguration.class) - .run((context) -> { + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") + .withUserConfiguration(HealthIndicatorsConfiguration.class).run((context) -> { HealthEndpoint endpoint = context.getBean(HealthEndpoint.class); ReactiveHealthEndpointWebExtension extension = context .getBean(ReactiveHealthEndpointWebExtension.class); Health endpointHealth = endpoint.health(); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); - Health extensionHealth = extension.health(securityContext) - .block(Duration.ofSeconds(30)).getBody(); - assertThat(endpointHealth.getDetails()) - .containsOnlyKeys("application", "first", "second"); - assertThat(extensionHealth.getDetails()) - .containsOnlyKeys("application", "first", "second"); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); + Health extensionHealth = extension.health(securityContext).block(Duration.ofSeconds(30)).getBody(); + assertThat(endpointHealth.getDetails()).containsOnlyKeys("application", "first", "second"); + assertThat(extensionHealth.getDetails()).containsOnlyKeys("application", "first", "second"); }); } @Test public void unauthenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { - ReactiveHealthEndpointWebExtension extension = context - .getBean(ReactiveHealthEndpointWebExtension.class); - assertThat(extension.health(mock(SecurityContext.class)) - .block(Duration.ofSeconds(30)).getBody().getDetails()).isEmpty(); + ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); + assertThat( + extension.health(mock(SecurityContext.class)).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isEmpty(); }); } @Test public void authenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { - ReactiveHealthEndpointWebExtension extension = context - .getBean(ReactiveHealthEndpointWebExtension.class); + ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); - assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)) - .getBody().getDetails()).isEmpty(); + assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isEmpty(); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { - this.contextRunner - .withPropertyValues( - "management.endpoint.health.show-details=when-authorized") + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { ReactiveHealthEndpointWebExtension extension = context .getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); - assertThat(extension.health(securityContext) - .block(Duration.ofSeconds(30)).getBody().getDetails()) - .isNotEmpty(); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); + assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isNotEmpty(); }); } @Test public void unauthenticatedUsersCanBeShownDetails() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - ReactiveHealthEndpointWebExtension extension = context - .getBean(ReactiveHealthEndpointWebExtension.class); - assertThat(extension.health(null).block(Duration.ofSeconds(30)) - .getBody().getDetails()).isNotEmpty(); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); + assertThat(extension.health(null).block(Duration.ofSeconds(30)).getBody().getDetails()).isNotEmpty(); + }); } @Test public void detailsCanBeHiddenFromAuthenticatedUsers() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=never") - .run((context) -> { - ReactiveHealthEndpointWebExtension extension = context - .getBean(ReactiveHealthEndpointWebExtension.class); - SecurityContext securityContext = mock(SecurityContext.class); - assertThat(extension.health(securityContext) - .block(Duration.ofSeconds(30)).getBody().getDetails()) - .isEmpty(); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { + ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); + SecurityContext securityContext = mock(SecurityContext.class); + assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isEmpty(); + }); } @Test public void detailsCanBeHiddenFromUnauthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { ReactiveHealthEndpointWebExtension extension = context .getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); - assertThat(extension.health(securityContext) - .block(Duration.ofSeconds(30)).getBody().getDetails()) - .isEmpty(); + assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isEmpty(); }); } @Test public void detailsCanBeShownToAuthorizedUsers() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { ReactiveHealthEndpointWebExtension extension = context .getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); - assertThat(extension.health(securityContext) - .block(Duration.ofSeconds(30)).getBody().getDetails()) - .isNotEmpty(); + assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isNotEmpty(); }); } @Test public void roleCanBeCustomized() { - this.contextRunner.withPropertyValues( - "management.endpoint.health.show-details=when-authorized", + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ADMIN").run((context) -> { ReactiveHealthEndpointWebExtension extension = context .getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); - given(securityContext.getPrincipal()) - .willReturn(mock(Principal.class)); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ADMIN")).willReturn(true); - assertThat(extension.health(securityContext) - .block(Duration.ofSeconds(30)).getBody().getDetails()) - .isNotEmpty(); + assertThat(extension.health(securityContext).block(Duration.ofSeconds(30)).getBody().getDetails()) + .isNotEmpty(); }); } @Test public void registryCanBeAltered() { this.contextRunner.withUserConfiguration(HealthIndicatorsConfiguration.class) - .withPropertyValues("management.endpoint.health.show-details=always") - .run((context) -> { - ReactiveHealthIndicatorRegistry registry = context - .getBean(ReactiveHealthIndicatorRegistry.class); + .withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class); ReactiveHealthEndpointWebExtension extension = context .getBean(ReactiveHealthEndpointWebExtension.class); - assertThat(extension.health(null).block(Duration.ofSeconds(30)) - .getBody().getDetails()).containsOnlyKeys("application", - "first", "second"); + assertThat(extension.health(null).block(Duration.ofSeconds(30)).getBody().getDetails()) + .containsOnlyKeys("application", "first", "second"); assertThat(registry.unregister("second")).isNotNull(); - assertThat(extension.health(null).block(Duration.ofSeconds(30)) - .getBody().getDetails()).containsKeys("application", "first"); + assertThat(extension.health(null).block(Duration.ofSeconds(30)).getBody().getDetails()) + .containsKeys("application", "first"); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java index 62a98547eea..3572c7d6625 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java @@ -36,22 +36,19 @@ import static org.mockito.Mockito.mock; public class InfluxDbHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration( - AutoConfigurations.of(InfluxDbHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration(AutoConfigurations + .of(InfluxDbHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(InfluxDbHealthIndicator.class) + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(InfluxDbHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.influxdb.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(InfluxDbHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java index d45b1f9c095..15291409d74 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java @@ -54,36 +54,30 @@ public class InfoContributorAutoConfigurationTests { @Test public void disableEnvContributor() { load("management.info.env.enabled:false"); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(0); } @Test public void defaultInfoContributorsDisabled() { load("management.info.defaults.enabled:false"); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(0); } @Test public void defaultInfoContributorsDisabledWithCustomOne() { - load(CustomInfoContributorConfiguration.class, - "management.info.defaults.enabled:false"); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + load(CustomInfoContributorConfiguration.class, "management.info.defaults.enabled:false"); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(1); - assertThat(this.context.getBean("customInfoContributor")) - .isSameAs(beans.values().iterator().next()); + assertThat(this.context.getBean("customInfoContributor")).isSameAs(beans.values().iterator().next()); } @SuppressWarnings("unchecked") @Test public void gitPropertiesDefaultMode() { load(GitPropertiesConfiguration.class); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).containsKeys("gitInfoContributor"); Map content = invokeContributor( this.context.getBean("gitInfoContributor", InfoContributor.class)); @@ -117,8 +111,7 @@ public class InfoContributorAutoConfigurationTests { @Test public void buildProperties() { load(BuildPropertiesConfiguration.class); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).containsKeys("buildInfoContributor"); Map content = invokeContributor( this.context.getBean("buildInfoContributor", InfoContributor.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java index 9d0016dedbd..fb13bf85adb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java @@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class InfoEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { @@ -51,8 +50,7 @@ public class InfoEndpointAutoConfigurationTests { @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(InfoEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java index ee47bd85c55..6ac89b5bb68 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java @@ -36,27 +36,21 @@ import static org.assertj.core.api.Assertions.assertThat; public class IntegrationGraphEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, - IntegrationAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, IntegrationGraphEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.exposure.include=integrationgraph") - .run((context) -> assertThat(context) - .hasSingleBean(IntegrationGraphEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=integrationgraph") + .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.integrationgraph.enabled:false") - .run((context) -> { - assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); - assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); - }); + this.contextRunner.withPropertyValues("management.endpoint.integrationgraph.enabled:false").run((context) -> { + assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); + assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); + }); } @Test @@ -70,8 +64,7 @@ public class IntegrationGraphEndpointAutoConfigurationTests { @Test public void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() { ApplicationContextRunner noSpringIntegrationRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(IntegrationGraphEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); noSpringIntegrationRunner.run((context) -> { assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java index 8fa3d431476..4c497e45a33 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java @@ -57,25 +57,21 @@ public class ControllerEndpointWebFluxIntegrationTests { @Test public void endpointsCanBeAccessed() throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigReactiveWebApplicationContext(); this.context.register(DefaultConfiguration.class, ExampleController.class); - TestPropertyValues.of("management.endpoints.web.exposure.include=*") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); this.context.refresh(); - WebTestClient webClient = WebTestClient.bindToApplicationContext(this.context) - .build(); + WebTestClient webClient = WebTestClient.bindToApplicationContext(this.context).build(); webClient.get().uri("/actuator/example").exchange().expectStatus().isOk(); } - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, - AuditAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - WebFluxAutoConfiguration.class, ManagementContextAutoConfiguration.class, - BeansEndpointAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, AuditAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, WebFluxAutoConfiguration.class, + ManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class }) static class DefaultConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java index 341e6ed7385..ff624db3a8f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java @@ -79,13 +79,12 @@ public class ControllerEndpointWebMvcIntegrationTests { @Test public void endpointsCanBeAccessed() throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class, ExampleController.class); TestPropertyValues - .of("management.endpoints.web.base-path:/management", - "management.endpoints.web.exposure.include=*") + .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") .applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/example")).andExpect(status().isOk()); @@ -105,13 +104,11 @@ public class ControllerEndpointWebMvcIntegrationTests { return builder.build(); } - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, AuditAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, + ManagementContextAutoConfiguration.class, DispatcherServletAutoConfiguration.class, BeansEndpointAutoConfiguration.class }) static class DefaultConfiguration { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java index 6eeef1565df..9af2040928b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java @@ -47,8 +47,7 @@ public class JerseyEndpointIntegrationTests { @Test public void linksAreProvidedToAllEndpointTypes() { - testJerseyEndpoints(new Class[] { EndpointsConfiguration.class, - ResourceConfigConfiguration.class }); + testJerseyEndpoints(new Class[] { EndpointsConfiguration.class, ResourceConfigConfiguration.class }); } @Test @@ -57,33 +56,23 @@ public class JerseyEndpointIntegrationTests { } protected void testJerseyEndpoints(Class[] userConfigurations) { - FilteredClassLoader classLoader = new FilteredClassLoader( - DispatcherServlet.class); - new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withClassLoader(classLoader) - .withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, - JerseyAutoConfiguration.class, - EndpointAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - BeansEndpointAutoConfiguration.class)) - .withUserConfiguration(userConfigurations) - .withPropertyValues("management.endpoints.web.exposure.include:*", - "server.port:0") - .run((context) -> { - int port = context.getSourceApplicationContext( - AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer() - .baseUrl("http://localhost:" + port).build(); - client.get().uri("/actuator").exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.beans").isNotEmpty() - .jsonPath("_links.restcontroller").doesNotExist() - .jsonPath("_links.controller").doesNotExist(); - }); + FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class); + new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) + .withClassLoader(classLoader) + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, + EndpointAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + BeansEndpointAutoConfiguration.class)) + .withUserConfiguration(userConfigurations) + .withPropertyValues("management.endpoints.web.exposure.include:*", "server.port:0").run((context) -> { + int port = context + .getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) + .getWebServer().getPort(); + WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build(); + client.get().uri("/actuator").exchange().expectStatus().isOk().expectBody().jsonPath("_links.beans") + .isNotEmpty().jsonPath("_links.restcontroller").doesNotExist().jsonPath("_links.controller") + .doesNotExist(); + }); } @ControllerEndpoint(id = "controller") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java index 31783cea99c..6a43e1f5e16 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java @@ -50,54 +50,42 @@ import static org.assertj.core.api.Assertions.assertThat; public class JmxEndpointIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, - EndpointAutoConfiguration.class, JmxEndpointAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, + JmxEndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class, HttpTraceAutoConfiguration.class)) - .withUserConfiguration(HttpTraceRepositoryConfiguration.class, - AuditEventRepositoryConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true").withConfiguration( - AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); + .withUserConfiguration(HttpTraceRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) + .withPropertyValues("spring.jmx.enabled=true") + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); @Test public void jmxEndpointsAreExposed() { this.contextRunner.run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); - checkEndpointMBeans(mBeanServer, - new String[] { "beans", "conditions", "configprops", "env", "health", - "info", "mappings", "threaddump", "httptrace" }, - new String[] { "shutdown" }); + checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", "health", + "info", "mappings", "threaddump", "httptrace" }, new String[] { "shutdown" }); }); } @Test public void jmxEndpointsCanBeExcluded() { - this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.exclude:*") - .run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - checkEndpointMBeans(mBeanServer, new String[0], - new String[] { "beans", "conditions", "configprops", "env", - "health", "mappings", "shutdown", "threaddump", - "httptrace" }); + this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.exclude:*").run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + checkEndpointMBeans(mBeanServer, new String[0], new String[] { "beans", "conditions", "configprops", "env", + "health", "mappings", "shutdown", "threaddump", "httptrace" }); - }); + }); } @Test public void singleJmxEndpointCanBeExposed() { - this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.include=beans") - .run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - checkEndpointMBeans(mBeanServer, new String[] { "beans" }, - new String[] { "conditions", "configprops", "env", "health", - "mappings", "shutdown", "threaddump", "httptrace" }); - }); + this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=beans").run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + checkEndpointMBeans(mBeanServer, new String[] { "beans" }, new String[] { "conditions", "configprops", + "env", "health", "mappings", "shutdown", "threaddump", "httptrace" }); + }); } - private void checkEndpointMBeans(MBeanServer mBeanServer, String[] enabledEndpoints, - String[] disabledEndpoints) { + private void checkEndpointMBeans(MBeanServer mBeanServer, String[] enabledEndpoints, String[] disabledEndpoints) { for (String enabledEndpoint : enabledEndpoints) { assertThat(isRegistered(mBeanServer, getDefaultObjectName(enabledEndpoint))) .as(String.format("Endpoint %s", enabledEndpoint)).isTrue(); @@ -118,14 +106,12 @@ public class JmxEndpointIntegrationTests { } } - private MBeanInfo getMBeanInfo(MBeanServer mBeanServer, ObjectName objectName) - throws InstanceNotFoundException { + private MBeanInfo getMBeanInfo(MBeanServer mBeanServer, ObjectName objectName) throws InstanceNotFoundException { try { return mBeanServer.getMBeanInfo(objectName); } catch (ReflectionException | IntrospectionException ex) { - throw new IllegalStateException( - "Failed to retrieve MBeanInfo for ObjectName " + objectName, ex); + throw new IllegalStateException("Failed to retrieve MBeanInfo for ObjectName " + objectName, ex); } } @@ -135,8 +121,8 @@ public class JmxEndpointIntegrationTests { private ObjectName getObjectName(String domain, String endpointId) { try { - return new ObjectName(String.format("%s:type=Endpoint,name=%s", domain, - StringUtils.capitalize(endpointId))); + return new ObjectName( + String.format("%s:type=Endpoint,name=%s", domain, StringUtils.capitalize(endpointId))); } catch (MalformedObjectNameException ex) { throw new IllegalStateException("Invalid object name", ex); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java index d5e0b0e61d0..fea99f5fdd3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java @@ -65,8 +65,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests { @Test public void jolokiaIsExposed() { - ResponseEntity response = this.restTemplate - .getForEntity("/actuator/jolokia", String.class); + ResponseEntity response = this.restTemplate.getForEntity("/actuator/jolokia", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).contains("\"agent\""); assertThat(response.getBody()).contains("\"request\":{\"type\""); @@ -74,36 +73,33 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests { @Test public void search() { - ResponseEntity response = this.restTemplate - .getForEntity("/actuator/jolokia/search/java.lang:*", String.class); + ResponseEntity response = this.restTemplate.getForEntity("/actuator/jolokia/search/java.lang:*", + String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).contains("GarbageCollector"); } @Test public void read() { - ResponseEntity response = this.restTemplate.getForEntity( - "/actuator/jolokia/read/java.lang:type=Memory", String.class); + ResponseEntity response = this.restTemplate.getForEntity("/actuator/jolokia/read/java.lang:type=Memory", + String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).contains("NonHeapMemoryUsage"); } @Test public void list() { - ResponseEntity response = this.restTemplate.getForEntity( - "/actuator/jolokia/list/java.lang/type=Memory/attr", String.class); + ResponseEntity response = this.restTemplate + .getForEntity("/actuator/jolokia/list/java.lang/type=Memory/attr", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).contains("NonHeapMemoryUsage"); } @Configuration(proxyBeanMethods = false) @MinimalWebConfiguration - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - JolokiaEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - ManagementContextAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + JolokiaEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, ManagementContextAutoConfiguration.class, ServletEndpointManagementContextConfiguration.class }) protected static class Application { @@ -112,9 +108,8 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, + @Import({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + ValidationAutoConfiguration.class, WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java index e8b5520e5c6..2d6d1ad33dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java @@ -55,41 +55,36 @@ public class WebEndpointsAutoConfigurationIntegrationTests { @Test public void healthEndpointWebExtensionIsAutoConfigured() { - servletWebRunner() - .run((context) -> context.getBean(WebEndpointTestApplication.class)); - servletWebRunner().run((context) -> assertThat(context) - .hasSingleBean(HealthEndpointWebExtension.class)); + servletWebRunner().run((context) -> context.getBean(WebEndpointTestApplication.class)); + servletWebRunner().run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); } @Test public void healthEndpointReactiveWebExtensionIsAutoConfigured() { - reactiveWebRunner().run((context) -> assertThat(context) - .hasSingleBean(ReactiveHealthEndpointWebExtension.class)); + reactiveWebRunner() + .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } private WebApplicationContextRunner servletWebRunner() { - return new WebApplicationContextRunner().withConfiguration( - UserConfigurations.of(WebEndpointTestApplication.class)); + return new WebApplicationContextRunner() + .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)); } private ReactiveWebApplicationContextRunner reactiveWebRunner() { - return new ReactiveWebApplicationContextRunner().withConfiguration( - UserConfigurations.of(WebEndpointTestApplication.class)); + return new ReactiveWebApplicationContextRunner() + .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)); } - @EnableAutoConfiguration(exclude = { FlywayAutoConfiguration.class, - LiquibaseAutoConfiguration.class, CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class, Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, + @EnableAutoConfiguration(exclude = { FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class, + CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, Neo4jDataAutoConfiguration.class, + Neo4jRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class, HazelcastAutoConfiguration.class, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration.class, - SolrRepositoriesAutoConfiguration.class, SolrAutoConfiguration.class, - RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, - MetricsAutoConfiguration.class }) + SolrRepositoriesAutoConfiguration.class, SolrAutoConfiguration.class, RedisAutoConfiguration.class, + RedisRepositoriesAutoConfiguration.class, MetricsAutoConfiguration.class }) @SpringBootConfiguration @SuppressWarnings("deprecation") public static class WebEndpointTestApplication { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java index 1835389db2c..649136af35b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java @@ -47,141 +47,113 @@ import org.springframework.test.web.reactive.server.WebTestClient; public class WebFluxEndpointCorsIntegrationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - CodecsAutoConfiguration.class, WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, - BeansEndpointAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test public void corsIsDisabledByDefault() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient - .options().uri("/actuator/beans").header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange() - .expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") + .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange().expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); } @Test public void settingAllowedOriginsEnablesCors() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org") + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") .run(withWebTestClient((webTestClient) -> { - webTestClient.options().uri("/actuator/beans") - .header("Origin", "test.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .exchange().expectStatus().isForbidden(); + webTestClient.options().uri("/actuator/beans").header("Origin", "test.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus() + .isForbidden(); performAcceptedCorsRequest(webTestClient, "/actuator/beans"); })); } @Test public void maxAgeDefaultsTo30Minutes() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient( - (webTestClient) -> performAcceptedCorsRequest(webTestClient, - "/actuator/beans").expectHeader().valueEquals( - HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") + .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") + .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); } @Test public void maxAgeCanBeConfigured() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.max-age: 2400") - .run(withWebTestClient( - (webTestClient) -> performAcceptedCorsRequest(webTestClient, - "/actuator/beans").expectHeader().valueEquals( - HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"))); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.max-age: 2400") + .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") + .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"))); } @Test public void requestsWithDisallowedHeadersAreRejected() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> webTestClient.options() - .uri("/actuator/beans").header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") - .exchange().expectStatus().isForbidden())); + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") + .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") + .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus() + .isForbidden())); } @Test public void allowedHeadersCanBeConfigured() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .run(withWebTestClient((webTestClient) -> webTestClient.options() - .uri("/actuator/beans").header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"))); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") + .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") + .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus().isOk() + .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"))); } @Test public void requestsWithDisallowedMethodsAreRejected() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> webTestClient.options() - .uri("/actuator/beans").header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH") - .exchange().expectStatus().isForbidden())); + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") + .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH").exchange().expectStatus() + .isForbidden())); } @Test public void allowedMethodsCanBeConfigured() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .run(withWebTestClient((webTestClient) -> webTestClient.options() - .uri("/actuator/beans").header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD") - .exchange().expectStatus().isOk().expectHeader().valueEquals( - HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD"))); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-methods:GET,HEAD") + .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD").exchange().expectStatus().isOk() + .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD"))); } @Test public void credentialsCanBeAllowed() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:true") - .run(withWebTestClient( - (webTestClient) -> performAcceptedCorsRequest(webTestClient, - "/actuator/beans").expectHeader().valueEquals( - HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, - "true"))); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:true") + .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") + .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))); } @Test public void credentialsCanBeDisabled() { - this.contextRunner.withPropertyValues( - "management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:false") - .run(withWebTestClient( - (webTestClient) -> performAcceptedCorsRequest(webTestClient, - "/actuator/beans").expectHeader().doesNotExist( - HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:false") + .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") + .expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))); } - private ContextConsumer withWebTestClient( - Consumer webTestClient) { - return (context) -> webTestClient - .accept(WebTestClient.bindToApplicationContext(context).configureClient() - .baseUrl("https://spring.example.org").build()); + private ContextConsumer withWebTestClient(Consumer webTestClient) { + return (context) -> webTestClient.accept(WebTestClient.bindToApplicationContext(context).configureClient() + .baseUrl("https://spring.example.org").build()); } - private WebTestClient.ResponseSpec performAcceptedCorsRequest( - WebTestClient webTestClient, String url) { - return webTestClient.options().uri(url) - .header(HttpHeaders.ORIGIN, "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange() - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, - "spring.example.org") - .expectStatus().isOk(); + private WebTestClient.ResponseSpec performAcceptedCorsRequest(WebTestClient webTestClient, String url) { + return webTestClient.options().uri(url).header(HttpHeaders.ORIGIN, "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "spring.example.org").expectStatus().isOk(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java index 8c7f3293f21..ddd8052ad28 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java @@ -46,28 +46,23 @@ public class WebFluxEndpointIntegrationTests { @Test public void linksAreProvidedToAllEndpointTypes() throws Exception { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - CodecsAutoConfiguration.class, WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, - EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) .withUserConfiguration(EndpointsConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include:*") - .run((context) -> { + .withPropertyValues("management.endpoints.web.exposure.include:*").run((context) -> { WebTestClient client = createWebTestClient(context); - client.get().uri("/actuator").exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.beans").isNotEmpty() - .jsonPath("_links.restcontroller").isNotEmpty() - .jsonPath("_links.controller").isNotEmpty(); + client.get().uri("/actuator").exchange().expectStatus().isOk().expectBody().jsonPath("_links.beans") + .isNotEmpty().jsonPath("_links.restcontroller").isNotEmpty().jsonPath("_links.controller") + .isNotEmpty(); }); } private WebTestClient createWebTestClient(ApplicationContext context) { - return WebTestClient.bindToApplicationContext(context).configureClient() - .baseUrl("https://spring.example.org").build(); + return WebTestClient.bindToApplicationContext(context).configureClient().baseUrl("https://spring.example.org") + .build(); } @ControllerEndpoint(id = "controller") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java index 437d7581f92..48f51281847 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java @@ -52,13 +52,10 @@ public class WebMvcEndpointCorsIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - BeansEndpointAutoConfiguration.class)) + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test @@ -66,18 +63,14 @@ public class WebMvcEndpointCorsIntegrationTests { this.contextRunner.run(withMockMvc((mockMvc) -> mockMvc .perform(options("/actuator/beans").header("Origin", "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect( - header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)))); + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)))); } @Test public void settingAllowedOriginsEnablesCors() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com") + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> { - mockMvc.perform(options("/actuator/beans") - .header("Origin", "bar.example.com") + mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) .andExpect(status().isForbidden()); performAcceptedCorsRequest(mockMvc); @@ -86,34 +79,26 @@ public class WebMvcEndpointCorsIntegrationTests { @Test public void maxAgeDefaultsTo30Minutes() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com") + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, - "1800")))); + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); } @Test public void maxAgeCanBeConfigured() { this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com", + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.max-age: 2400") .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, - "2400")))); + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")))); } @Test public void requestsWithDisallowedHeadersAreRejected() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com") + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> - mockMvc.perform(options("/actuator/beans") - .header("Origin", "foo.example.com") + mockMvc.perform(options("/actuator/beans").header("Origin", "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) .andExpect(status().isForbidden()))); @@ -122,79 +107,68 @@ public class WebMvcEndpointCorsIntegrationTests { @Test public void allowedHeadersCanBeConfigured() { this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com", + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .run(withMockMvc((mockMvc) -> mockMvc.perform(options("/actuator/beans") - .header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isOk()).andExpect(header().string( - HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")))); + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")))); } @Test public void requestsWithDisallowedMethodsAreRejected() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> mockMvc.perform(options("/actuator/beans") - .header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) + this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) .andExpect(status().isForbidden()))); } @Test public void allowedMethodsCanBeConfigured() { this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com", + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .run(withMockMvc((mockMvc) -> mockMvc.perform(options("/actuator/beans") - .header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) - .andExpect(status().isOk()).andExpect(header().string( - HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")))); + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")))); } @Test public void credentialsCanBeAllowed() { this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com", + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allow-credentials:true") .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string( - HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")))); + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")))); } @Test public void credentialsCanBeDisabled() { this.contextRunner - .withPropertyValues( - "management.endpoints.web.cors.allowed-origins:foo.example.com", + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allow-credentials:false") .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().doesNotExist( - HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))); + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))); } private ContextConsumer withMockMvc(MockMvcConsumer mockMvc) { - return (context) -> mockMvc - .accept(MockMvcBuilders.webAppContextSetup(context).build()); + return (context) -> mockMvc.accept(MockMvcBuilders.webAppContextSetup(context).build()); } private ResultActions performAcceptedCorsRequest(MockMvc mockMvc) throws Exception { return performAcceptedCorsRequest(mockMvc, "/actuator/beans"); } - private ResultActions performAcceptedCorsRequest(MockMvc mockMvc, String url) - throws Exception { + private ResultActions performAcceptedCorsRequest(MockMvc mockMvc, String url) throws Exception { return mockMvc .perform(options(url).header(HttpHeaders.ORIGIN, "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, - "foo.example.com")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "foo.example.com")) .andExpect(status().isOk()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java index 67cf7ce3103..6b77355e775 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java @@ -66,26 +66,17 @@ import static org.assertj.core.api.Assertions.assertThat; public class WebMvcEndpointExposureIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new).withConfiguration( - AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, - EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - HttpTraceAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)) - .withConfiguration( - AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) - .withUserConfiguration(CustomMvcEndpoint.class, - CustomServletEndpoint.class, - HttpTraceRepositoryConfiguration.class, - AuditEventRepositoryConfiguration.class) + AnnotationConfigServletWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + HttpTraceAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) + .withUserConfiguration(CustomMvcEndpoint.class, CustomServletEndpoint.class, + HttpTraceRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) .withPropertyValues("server.port:0"); @Test @@ -152,8 +143,7 @@ public class WebMvcEndpointExposureIntegrationTests { @Test public void singleWebEndpointCanBeExcluded() { WebApplicationContextRunner contextRunner = this.contextRunner.withPropertyValues( - "management.endpoints.web.exposure.include=*", - "management.endpoints.web.exposure.exclude=shutdown"); + "management.endpoints.web.exposure.include=*", "management.endpoints.web.exposure.exclude=shutdown"); contextRunner.run((context) -> { WebTestClient client = createClient(context); assertThat(isExposed(client, HttpMethod.GET, "beans")).isTrue(); @@ -172,17 +162,14 @@ public class WebMvcEndpointExposureIntegrationTests { } private WebTestClient createClient(AssertableWebApplicationContext context) { - int port = context - .getSourceApplicationContext(ServletWebServerApplicationContext.class) - .getWebServer().getPort(); + int port = context.getSourceApplicationContext(ServletWebServerApplicationContext.class).getWebServer() + .getPort(); return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build(); } - private boolean isExposed(WebTestClient client, HttpMethod method, String path) - throws Exception { + private boolean isExposed(WebTestClient client, HttpMethod method, String path) throws Exception { path = "/actuator/" + path; - EntityExchangeResult result = client.method(method).uri(path).exchange() - .expectBody().returnResult(); + EntityExchangeResult result = client.method(method).uri(path).exchange().expectBody().returnResult(); if (result.getStatus() == HttpStatus.OK) { return true; } @@ -190,8 +177,7 @@ public class WebMvcEndpointExposureIntegrationTests { return false; } throw new IllegalStateException( - String.format("Unexpected %s HTTP status for " + "endpoint %s", - result.getStatus(), path)); + String.format("Unexpected %s HTTP status for " + "endpoint %s", result.getStatus(), path)); } @RestControllerEndpoint(id = "custommvc") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java index 55f321be584..c8f3c1057e5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java @@ -83,16 +83,14 @@ public class WebMvcEndpointIntegrationTests { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); MockMvc mockMvc = createSecureMockMvc(); - mockMvc.perform(get("/actuator/beans").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/actuator/beans").accept(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); } @Test public void endpointsAreSecureByDefaultWithCustomBasePath() throws Exception { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); - TestPropertyValues.of("management.endpoints.web.base-path:/management") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.base-path:/management").applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isUnauthorized()); @@ -100,13 +98,12 @@ public class WebMvcEndpointIntegrationTests { @Test public void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); TestPropertyValues - .of("management.endpoints.web.base-path:/management", - "management.endpoints.web.exposure.include=*") + .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") .applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isOk()); @@ -116,12 +113,10 @@ public class WebMvcEndpointIntegrationTests { public void linksAreProvidedToAllEndpointTypes() throws Exception { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(DefaultConfiguration.class, EndpointsConfiguration.class); - TestPropertyValues.of("management.endpoints.web.exposure.include=*") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); MockMvc mockMvc = doCreateMockMvc(); - mockMvc.perform(get("/actuator").accept("*/*")).andExpect(status().isOk()) - .andExpect(jsonPath("_links", both(hasKey("beans")).and(hasKey("servlet")) - .and(hasKey("restcontroller")).and(hasKey("controller")))); + mockMvc.perform(get("/actuator").accept("*/*")).andExpect(status().isOk()).andExpect(jsonPath("_links", + both(hasKey("beans")).and(hasKey("servlet")).and(hasKey("restcontroller")).and(hasKey("controller")))); } private MockMvc createSecureMockMvc() { @@ -138,14 +133,12 @@ public class WebMvcEndpointIntegrationTests { return builder.build(); } - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, AuditAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class, ManagementContextAutoConfiguration.class, AuditAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - BeansEndpointAutoConfiguration.class }) + DispatcherServletAutoConfiguration.class, BeansEndpointAutoConfiguration.class }) static class DefaultConfiguration { } @@ -157,8 +150,7 @@ public class WebMvcEndpointIntegrationTests { } @Import(SecureConfiguration.class) - @ImportAutoConfiguration({ HypermediaAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class }) + @ImportAutoConfiguration({ HypermediaAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) static class SpringDataRestConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java index 403573e3c08..7534e5a26c0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java @@ -49,8 +49,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class, - DataSourceHealthIndicatorAutoConfiguration.class)) + HealthIndicatorAutoConfiguration.class, DataSourceHealthIndicatorAutoConfiguration.class)) .withPropertyValues("spring.datasource.initialization-mode=never"); @Test @@ -64,37 +63,28 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { @Test public void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - DataSourceConfig.class).run((context) -> { + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) + .run((context) -> { assertThat(context).hasSingleBean(HealthIndicator.class); - HealthIndicator indicator = context - .getBean(CompositeHealthIndicator.class); - assertThat(indicator.health().getDetails()) - .containsOnlyKeys("dataSource", "testDataSource"); + HealthIndicator indicator = context.getBean(CompositeHealthIndicator.class); + assertThat(indicator.health().getDetails()).containsOnlyKeys("dataSource", "testDataSource"); }); } @Test public void runShouldFilterRoutingDataSource() { - this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - RoutingDatasourceConfig.class) - .run((context) -> assertThat(context) - .hasSingleBean(DataSourceHealthIndicator.class) + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDatasourceConfig.class) + .run((context) -> assertThat(context).hasSingleBean(DataSourceHealthIndicator.class) .doesNotHaveBean(CompositeHealthIndicator.class)); } @Test public void runWithValidationQueryPropertyShouldUseCustomQuery() { this.contextRunner - .withUserConfiguration(DataSourceConfig.class, - DataSourcePoolMetadataProvidersConfiguration.class) - .withPropertyValues( - "spring.datasource.test.validation-query:SELECT from FOOBAR") - .run((context) -> { + .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) + .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR").run((context) -> { assertThat(context).hasSingleBean(HealthIndicator.class); - DataSourceHealthIndicator indicator = context - .getBean(DataSourceHealthIndicator.class); + DataSourceHealthIndicator indicator = context.getBean(DataSourceHealthIndicator.class); assertThat(indicator.getQuery()).isEqualTo("SELECT from FOOBAR"); }); } @@ -103,8 +93,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("management.health.db.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(DataSourceHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) .doesNotHaveBean(CompositeHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } @@ -116,10 +105,8 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { @Bean @ConfigurationProperties(prefix = "spring.datasource.test") public DataSource testDataSource() { - return DataSourceBuilder.create() - .type(org.apache.tomcat.jdbc.pool.DataSource.class) - .driverClassName("org.hsqldb.jdbc.JDBCDriver") - .url("jdbc:hsqldb:mem:test").username("sa").build(); + return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class) + .driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test").username("sa").build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java index c0846eb903c..269e66c71ff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java @@ -37,21 +37,18 @@ public class JmsHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, - JmsHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + JmsHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(JmsHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JmsHealthIndicator.class) + .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.jms.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LdapHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java index 6dd4e1fca12..0a4b0e788cc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java @@ -49,31 +49,26 @@ import static org.assertj.core.api.Assertions.assertThat; public class JolokiaEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - DispatcherServletAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - ServletEndpointManagementContextConfiguration.class, - JolokiaEndpointAutoConfiguration.class, TestConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + ServletEndpointManagementContextConfiguration.class, JolokiaEndpointAutoConfiguration.class, + TestConfiguration.class)); @Test public void jolokiaServletShouldBeEnabledByDefault() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=jolokia") - .run((context) -> { - ExposableServletEndpoint endpoint = getEndpoint(context); - assertThat(endpoint.getRootPath()).isEqualTo("jolokia"); - Object servlet = ReflectionTestUtils - .getField(endpoint.getEndpointServlet(), "servlet"); - assertThat(servlet).isInstanceOf(AgentServlet.class); - }); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { + ExposableServletEndpoint endpoint = getEndpoint(context); + assertThat(endpoint.getRootPath()).isEqualTo("jolokia"); + Object servlet = ReflectionTestUtils.getField(endpoint.getEndpointServlet(), "servlet"); + assertThat(servlet).isInstanceOf(AgentServlet.class); + }); } @Test public void jolokiaServletWhenEndpointNotExposedShouldNotBeDiscovered() { this.contextRunner.run((context) -> { - Collection endpoints = context - .getBean(ServletEndpointsSupplier.class).getEndpoints(); + Collection endpoints = context.getBean(ServletEndpointsSupplier.class) + .getEndpoints(); assertThat(endpoints).isEmpty(); }); } @@ -81,30 +76,25 @@ public class JolokiaEndpointAutoConfigurationTests { @Test public void jolokiaServletWhenDisabledShouldNotBeDiscovered() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false") - .withPropertyValues("management.endpoints.web.exposure.include=jolokia") - .run((context) -> { - Collection endpoints = context - .getBean(ServletEndpointsSupplier.class).getEndpoints(); + .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { + Collection endpoints = context.getBean(ServletEndpointsSupplier.class) + .getEndpoints(); assertThat(endpoints).isEmpty(); }); } @Test public void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() { - this.contextRunner - .withPropertyValues("management.endpoint.jolokia.config.debug=true") - .withPropertyValues("management.endpoints.web.exposure.include=jolokia") - .run((context) -> { + this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true") + .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { ExposableServletEndpoint endpoint = getEndpoint(context); assertThat(endpoint.getEndpointServlet()).extracting("initParameters") .containsOnly(Collections.singletonMap("debug", "true")); }); } - private ExposableServletEndpoint getEndpoint( - AssertableWebApplicationContext context) { - Collection endpoints = context - .getBean(ServletEndpointsSupplier.class).getEndpoints(); + private ExposableServletEndpoint getEndpoint(AssertableWebApplicationContext context) { + Collection endpoints = context.getBean(ServletEndpointsSupplier.class).getEndpoints(); return endpoints.iterator().next(); } @@ -112,10 +102,8 @@ public class JolokiaEndpointAutoConfigurationTests { static class TestConfiguration { @Bean - public ServletEndpointDiscoverer servletEndpointDiscoverer( - ApplicationContext applicationContext) { - return new ServletEndpointDiscoverer(applicationContext, null, - Collections.emptyList()); + public ServletEndpointDiscoverer servletEndpointDiscoverer(ApplicationContext applicationContext) { + return new ServletEndpointDiscoverer(applicationContext, null, Collections.emptyList()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java index aa74ed44d0b..174252a90c8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java @@ -37,23 +37,19 @@ import static org.mockito.Mockito.mock; public class LdapHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(LdapOperations.class, () -> mock(LdapOperations.class)) - .withConfiguration( - AutoConfigurations.of(LdapHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withBean(LdapOperations.class, () -> mock(LdapOperations.class)).withConfiguration(AutoConfigurations + .of(LdapHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(LdapHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(LdapHealthIndicator.class) + .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.ldap.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LdapHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java index c9c8afd1849..994b81729de 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java @@ -37,57 +37,44 @@ import static org.mockito.Mockito.mock; public class LiquibaseEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=liquibase") + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase") .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) - .run((context) -> assertThat(context) - .hasSingleBean(LiquibaseEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) + this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) .withPropertyValues("management.endpoint.liquibase.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LiquibaseEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(LiquibaseEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test public void disablesCloseOfDataSourceWhenEndpointIsEnabled() { - this.contextRunner - .withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=liquibase") - .run((context) -> { + this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) + .withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> { assertThat(context).hasSingleBean(LiquibaseEndpoint.class); assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) - .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", - false); + .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false); }); } @Test public void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() { - this.contextRunner - .withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .withPropertyValues("management.endpoint.liquibase.enabled:false") - .run((context) -> { + this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) + .withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> { assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); - DataSourceClosingSpringLiquibase bean = context - .getBean(DataSourceClosingSpringLiquibase.class); - assertThat(bean).hasFieldOrPropertyWithValue( - "closeDataSourceOnceMigrated", true); + DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class); + assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true); }); } @@ -101,11 +88,10 @@ public class LiquibaseEndpointAutoConfigurationTests { private boolean propertiesSet = false; @Override - public void setCloseDataSourceOnceMigrated( - boolean closeDataSourceOnceMigrated) { + public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) { if (this.propertiesSet) { - throw new IllegalStateException("setCloseDataSourceOnceMigrated " - + "invoked after afterPropertiesSet"); + throw new IllegalStateException( + "setCloseDataSourceOnceMigrated " + "invoked after afterPropertiesSet"); } super.setCloseDataSourceOnceMigrated(closeDataSourceOnceMigrated); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java index e2002629a44..e9cefd8639e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java @@ -44,104 +44,82 @@ import static org.assertj.core.api.Assertions.assertThat; public class LogFileWebEndpointAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); @Test public void runWithOnlyExposedShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context) - .doesNotHaveBean(LogFileWebEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test public void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.name:test.log") - .run((context) -> assertThat(context) - .doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test public void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file.name:test.log", - "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test @Deprecated public void runWhenLoggingFileIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file:test.log", - "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file:test.log", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.path:test/logs") - .run((context) -> assertThat(context) - .doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test public void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file.path:test/logs", - "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test @Deprecated public void runWhenLoggingPathIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.path:test/logs", - "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.path:test/logs", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { this.contextRunner - .withPropertyValues( - "management.endpoint.logfile.external-file:external.log", + .withPropertyValues("management.endpoint.logfile.external-file:external.log", "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void logFileWebEndpointCanBeDisabled() { - this.contextRunner - .withPropertyValues("logging.file.name:test.log", - "management.endpoint.logfile.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LogFileWebEndpoint.class)); + this.contextRunner.withPropertyValues("logging.file.name:test.log", "management.endpoint.logfile.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test - public void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) - throws IOException { + public void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException { File file = new File(temp.toFile(), "logfile"); FileCopyUtils.copy("--TEST--".getBytes(), file); - this.contextRunner.withPropertyValues( - "management.endpoints.web.exposure.include=logfile", - "management.endpoint.logfile.external-file:" + file.getAbsolutePath()) - .run((context) -> { + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile", + "management.endpoint.logfile.external-file:" + file.getAbsolutePath()).run((context) -> { assertThat(context).hasSingleBean(LogFileWebEndpoint.class); - LogFileWebEndpoint endpoint = context - .getBean(LogFileWebEndpoint.class); + LogFileWebEndpoint endpoint = context.getBean(LogFileWebEndpoint.class); Resource resource = endpoint.logFile(); assertThat(resource).isNotNull(); - assertThat(StreamUtils.copyToString(resource.getInputStream(), - StandardCharsets.UTF_8)).isEqualTo("--TEST--"); + assertThat(StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8)) + .isEqualTo("--TEST--"); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java index e1bc1d68113..79efa5414e7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java @@ -36,38 +36,30 @@ import static org.mockito.Mockito.mock; public class LoggersEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) .withUserConfiguration(LoggingConfiguration.class); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=loggers") - .run((context) -> assertThat(context) - .hasSingleBean(LoggersEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=loggers") + .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.loggers.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Test public void runWithNoneLoggingSystemShouldNotHaveEndpointBean() { - this.contextRunner - .withSystemProperties( - "org.springframework.boot.logging.LoggingSystem=none") - .run((context) -> assertThat(context) - .doesNotHaveBean(LoggersEndpoint.class)); + this.contextRunner.withSystemProperties("org.springframework.boot.logging.LoggingSystem=none") + .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java index 80bdf29b2ca..55cc9b8841b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java @@ -36,22 +36,19 @@ public class MailHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, - MailHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)) + MailHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)) .withPropertyValues("spring.mail.host:smtp.example.com"); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(MailHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MailHealthIndicator.class) + .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mail.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(MailHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java index 8cebbca12a6..3ff77c07b3c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java @@ -36,16 +36,13 @@ public class HeapDumpWebEndpointAutoConfigurationTests { @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(HeapDumpWebEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HeapDumpWebEndpoint.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { - this.contextRunner - .withPropertyValues("management.endpoint.heapdump.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HeapDumpWebEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.heapdump.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java index c838988b977..0759a6849aa 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java @@ -32,31 +32,24 @@ import static org.assertj.core.api.Assertions.assertThat; public class ThreadDumpEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.exposure.include=threaddump") - .run((context) -> assertThat(context) - .hasSingleBean(ThreadDumpEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=threaddump") + .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ThreadDumpEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*") + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") .withPropertyValues("management.endpoint.threaddump.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ThreadDumpEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java index 8b104f51841..29ca30f469d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java @@ -42,55 +42,47 @@ public class CompositeMeterRegistryAutoConfigurationTests { private static final String COMPOSITE_NAME = "compositeMeterRegistry"; private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(BaseConfig.class).withConfiguration( - AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); + .withUserConfiguration(BaseConfig.class) + .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); @Test public void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() { - this.contextRunner.withUserConfiguration(NoMeterRegistryConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(MeterRegistry.class); - CompositeMeterRegistry registry = context.getBean("noOpMeterRegistry", - CompositeMeterRegistry.class); - assertThat(registry.getRegistries()).isEmpty(); - }); + this.contextRunner.withUserConfiguration(NoMeterRegistryConfig.class).run((context) -> { + assertThat(context).hasSingleBean(MeterRegistry.class); + CompositeMeterRegistry registry = context.getBean("noOpMeterRegistry", CompositeMeterRegistry.class); + assertThat(registry.getRegistries()).isEmpty(); + }); } @Test public void registerWhenHasSingleMeterRegistryShouldDoNothing() { - this.contextRunner.withUserConfiguration(SingleMeterRegistryConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(MeterRegistry.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry).isInstanceOf(TestMeterRegistry.class); - }); + this.contextRunner.withUserConfiguration(SingleMeterRegistryConfig.class).run((context) -> { + assertThat(context).hasSingleBean(MeterRegistry.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry).isInstanceOf(TestMeterRegistry.class); + }); } @Test public void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() { - this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class) - .run((context) -> { - assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3) - .containsKeys("meterRegistryOne", "meterRegistryTwo", - COMPOSITE_NAME); - MeterRegistry primary = context.getBean(MeterRegistry.class); - assertThat(primary).isInstanceOf(CompositeMeterRegistry.class); - assertThat(((CompositeMeterRegistry) primary).getRegistries()) - .hasSize(2); - assertThat(primary.config().clock()).isNotNull(); - }); + this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class).run((context) -> { + assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3).containsKeys("meterRegistryOne", + "meterRegistryTwo", COMPOSITE_NAME); + MeterRegistry primary = context.getBean(MeterRegistry.class); + assertThat(primary).isInstanceOf(CompositeMeterRegistry.class); + assertThat(((CompositeMeterRegistry) primary).getRegistries()).hasSize(2); + assertThat(primary.config().clock()).isNotNull(); + }); } @Test public void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() { - this.contextRunner - .withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class) - .run((context) -> { - assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2) - .containsKeys("meterRegistryOne", "meterRegistryTwo"); - MeterRegistry primary = context.getBean(MeterRegistry.class); - assertThat(primary).isInstanceOf(TestMeterRegistry.class); - }); + this.contextRunner.withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class).run((context) -> { + assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2).containsKeys("meterRegistryOne", + "meterRegistryTwo"); + MeterRegistry primary = context.getBean(MeterRegistry.class); + assertThat(primary).isInstanceOf(TestMeterRegistry.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java index bea439ba6f1..c5100f87b42 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java @@ -38,59 +38,46 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class JvmMetricsAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()) + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test public void autoConfiguresJvmMetrics() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(JvmGcMetrics.class).hasSingleBean(JvmMemoryMetrics.class) - .hasSingleBean(JvmThreadMetrics.class) - .hasSingleBean(ClassLoaderMetrics.class)); + this.contextRunner.run( + (context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasSingleBean(JvmMemoryMetrics.class) + .hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class)); } @Test public void allowsCustomJvmGcMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmGcMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) - .hasBean("customJvmGcMetrics") - .hasSingleBean(JvmMemoryMetrics.class) - .hasSingleBean(JvmThreadMetrics.class) + .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasBean("customJvmGcMetrics") + .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) .hasSingleBean(ClassLoaderMetrics.class)); } @Test public void allowsCustomJvmMemoryMetricsToBeUsed() { - this.contextRunner - .withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class) + this.contextRunner.withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) - .hasSingleBean(JvmMemoryMetrics.class) - .hasBean("customJvmMemoryMetrics") - .hasSingleBean(JvmThreadMetrics.class) - .hasSingleBean(ClassLoaderMetrics.class)); + .hasSingleBean(JvmMemoryMetrics.class).hasBean("customJvmMemoryMetrics") + .hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class)); } @Test public void allowsCustomJvmThreadMetricsToBeUsed() { - this.contextRunner - .withUserConfiguration(CustomJvmThreadMetricsConfiguration.class) + this.contextRunner.withUserConfiguration(CustomJvmThreadMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) - .hasSingleBean(JvmMemoryMetrics.class) - .hasSingleBean(JvmThreadMetrics.class) - .hasSingleBean(ClassLoaderMetrics.class) - .hasBean("customJvmThreadMetrics")); + .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) + .hasSingleBean(ClassLoaderMetrics.class).hasBean("customJvmThreadMetrics")); } @Test public void allowsCustomClassLoaderMetricsToBeUsed() { - this.contextRunner - .withUserConfiguration(CustomClassLoaderMetricsConfiguration.class) + this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) - .hasSingleBean(JvmMemoryMetrics.class) - .hasSingleBean(JvmThreadMetrics.class) - .hasSingleBean(ClassLoaderMetrics.class) - .hasBean("customClassLoaderMetrics")); + .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) + .hasSingleBean(ClassLoaderMetrics.class).hasBean("customClassLoaderMetrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java index 4869e6fbb8f..c0b0661b272 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java @@ -35,32 +35,26 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class KafkaMetricsAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withPropertyValues("spring.jmx.enabled=true") - .withConfiguration( - AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withPropertyValues("spring.jmx.enabled=true") + .withConfiguration(AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); @Test public void whenThereIsNoMBeanServerAutoConfigurationBacksOff() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(KafkaConsumerMetrics.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(KafkaConsumerMetrics.class)); } @Test public void whenThereIsAnMBeanServerKafkaConsumerMetricsIsConfigured() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(KafkaConsumerMetrics.class)); + this.contextRunner.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(KafkaConsumerMetrics.class)); } @Test public void allowsCustomKafkaConsumerMetricsToBeUsed() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)) .withUserConfiguration(CustomKafkaConsumerMetricsConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(KafkaConsumerMetrics.class) + .run((context) -> assertThat(context).hasSingleBean(KafkaConsumerMetrics.class) .hasBean("customKafkaConsumerMetrics")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java index 22776073316..daa394ab72b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java @@ -40,25 +40,22 @@ import static org.assertj.core.api.Assertions.assertThat; @ClassPathOverrides("org.apache.logging.log4j:log4j-core:2.11.1") public class Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test public void autoConfiguresLog4J2Metrics() { assertThat(LogManager.getContext().getClass().getName()) .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class)); } @Test public void allowsCustomLog4J2MetricsToBeUsed() { assertThat(LogManager.getContext().getClass().getName()) .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); - this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class) - .hasBean("customLog4J2Metrics")); + this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class).run( + (context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class).hasBean("customLog4J2Metrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java index e1d7af08c6f..75b6c316f4e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,15 +34,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test public void backsOffWhenLoggerContextIsBackedBySlf4j() { assertThat(LogManager.getContext()).isInstanceOf(SLF4JLoggerContext.class); - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(Log4j2Metrics.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Log4j2Metrics.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java index d9dfcd46e71..e2efba0797e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java @@ -35,21 +35,18 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class LogbackMetricsAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); @Test public void autoConfiguresLogbackMetrics() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(LogbackMetrics.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(LogbackMetrics.class)); } @Test public void allowsCustomLogbackMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(LogbackMetrics.class) - .hasBean("customLogbackMetrics")); + this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class).run( + (context) -> assertThat(context).hasSingleBean(LogbackMetrics.class).hasBean("customLogbackMetrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java index 5d2d7cf30b0..28fe97551af 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java @@ -56,8 +56,7 @@ public class MeterRegistryConfigurerIntegrationTests { @Test public void binderMetricsAreSearchableFromTheComposite() { this.contextRunner.run((context) -> { - CompositeMeterRegistry composite = context - .getBean(CompositeMeterRegistry.class); + CompositeMeterRegistry composite = context.getBean(CompositeMeterRegistry.class); composite.get("jvm.memory.used").gauge(); context.getBeansOfType(MeterRegistry.class) .forEach((name, registry) -> registry.get("jvm.memory.used").gauge()); @@ -76,20 +75,15 @@ public class MeterRegistryConfigurerIntegrationTests { @Test public void counterIsIncrementedOncePerEventWithoutCompositeMeterRegistry() { - new ApplicationContextRunner() - .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class)) - .withConfiguration( - AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)) - .run((context) -> { - Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton() - .getLoggerFactory()).getLogger("test-logger"); + new ApplicationContextRunner().with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { + Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) + .getLogger("test-logger"); logger.error("Error."); - Map registriesByName = context - .getBeansOfType(MeterRegistry.class); + Map registriesByName = context.getBeansOfType(MeterRegistry.class); assertThat(registriesByName).hasSize(1); MeterRegistry registry = registriesByName.values().iterator().next(); - assertThat(registry.get("logback.events").tag("level", "error") - .counter().count()).isEqualTo(1); + assertThat(registry.get("logback.events").tag("level", "error").counter().count()).isEqualTo(1); }); } @@ -98,18 +92,15 @@ public class MeterRegistryConfigurerIntegrationTests { new ApplicationContextRunner() .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class, PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration( - AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)) - .run((context) -> { - Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton() - .getLoggerFactory()).getLogger("test-logger"); + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { + Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) + .getLogger("test-logger"); logger.error("Error."); - Map registriesByName = context - .getBeansOfType(MeterRegistry.class); + Map registriesByName = context.getBeansOfType(MeterRegistry.class); assertThat(registriesByName).hasSize(3); registriesByName.forEach((name, - registry) -> assertThat(registry.get("logback.events") - .tag("level", "error").counter().count()) + registry) -> assertThat( + registry.get("logback.events").tag("level", "error").counter().count()) .isEqualTo(1)); }); } @@ -143,14 +134,11 @@ public class MeterRegistryConfigurerIntegrationTests { return new BeanPostProcessor() { @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Bravo) { - MeterRegistry meterRegistry = context - .getBean(MeterRegistry.class); + MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); meterRegistry.gauge("test", 1); - System.out.println( - meterRegistry.find("test").gauge().getId().getTags()); + System.out.println(meterRegistry.find("test").gauge().getId().getTags()); } return bean; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java index 0aa9df8789f..6440af65d5d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java @@ -78,10 +78,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureWhenCompositeShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); CompositeMeterRegistry composite = new CompositeMeterRegistry(); configurer.configure(composite); verify(this.mockCustomizer).customize(composite); @@ -90,10 +88,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); configurer.configure(this.mockRegistry); verify(this.mockCustomizer).customize(this.mockRegistry); } @@ -101,10 +97,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyFilter() { this.filters.add(this.mockFilter); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); configurer.configure(this.mockRegistry); verify(this.mockConfig).meterFilter(this.mockFilter); } @@ -112,10 +106,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyBinder() { this.binders.add(this.mockBinder); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); configurer.configure(this.mockRegistry); verify(this.mockBinder).bindTo(this.mockRegistry); } @@ -123,10 +115,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyBinderToComposite() { this.binders.add(this.mockBinder); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, true); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, true); CompositeMeterRegistry composite = new CompositeMeterRegistry(); configurer.configure(composite); verify(this.mockBinder).bindTo(composite); @@ -135,10 +125,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldNotApplyBinderWhenCompositeExists() { this.binders.add(this.mockBinder); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, true); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, true); configurer.configure(this.mockRegistry); verifyZeroInteractions(this.mockBinder); } @@ -148,10 +136,8 @@ public class MeterRegistryConfigurerTests { this.customizers.add(this.mockCustomizer); this.filters.add(this.mockFilter); this.binders.add(this.mockBinder); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); configurer.configure(this.mockRegistry); InOrder ordered = inOrder(this.mockBinder, this.mockConfig, this.mockCustomizer); ordered.verify(this.mockCustomizer).customize(this.mockRegistry); @@ -161,14 +147,11 @@ public class MeterRegistryConfigurerTests { @Test public void configureWhenAddToGlobalRegistryShouldAddToGlobalRegistry() { - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - true, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), true, false); try { configurer.configure(this.mockRegistry); - assertThat(Metrics.globalRegistry.getRegistries()) - .contains(this.mockRegistry); + assertThat(Metrics.globalRegistry.getRegistries()).contains(this.mockRegistry); } finally { Metrics.removeRegistry(this.mockRegistry); @@ -177,13 +160,10 @@ public class MeterRegistryConfigurerTests { @Test public void configureWhenNotAddToGlobalRegistryShouldAddToGlobalRegistry() { - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer( - createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), - false, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), + createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); configurer.configure(this.mockRegistry); - assertThat(Metrics.globalRegistry.getRegistries()) - .doesNotContain(this.mockRegistry); + assertThat(Metrics.globalRegistry.getRegistries()).doesNotContain(this.mockRegistry); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java index ebe080ea11d..67c5b0acbc5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java @@ -46,36 +46,28 @@ public class MeterRegistryCustomizerTests { @Test public void commonTagsAreAppliedToAutoConfiguredBinders() { - this.contextRunner - .withUserConfiguration(MeterRegistryCustomizerConfiguration.class) - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jvm.memory.used").tags("region", "us-east-1").gauge(); - }); + this.contextRunner.withUserConfiguration(MeterRegistryCustomizerConfiguration.class).run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jvm.memory.used").tags("region", "us-east-1").gauge(); + }); } @Test public void commonTagsAreAppliedBeforeRegistryIsInjectableElsewhere() { - this.contextRunner - .withUserConfiguration(MeterRegistryCustomizerConfiguration.class) - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("my.thing").tags("region", "us-east-1").gauge(); - }); + this.contextRunner.withUserConfiguration(MeterRegistryCustomizerConfiguration.class).run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("my.thing").tags("region", "us-east-1").gauge(); + }); } @Test public void customizersCanBeAppliedToSpecificRegistryTypes() { - this.contextRunner - .withUserConfiguration(MeterRegistryCustomizerConfiguration.class) - .run((context) -> { - MeterRegistry prometheus = context - .getBean(PrometheusMeterRegistry.class); - prometheus.get("jvm.memory.used").tags("job", "myjob").gauge(); - MeterRegistry atlas = context.getBean(AtlasMeterRegistry.class); - assertThat(atlas.find("jvm.memory.used").tags("job", "myjob").gauge()) - .isNull(); - }); + this.contextRunner.withUserConfiguration(MeterRegistryCustomizerConfiguration.class).run((context) -> { + MeterRegistry prometheus = context.getBean(PrometheusMeterRegistry.class); + prometheus.get("jvm.memory.used").tags("job", "myjob").gauge(); + MeterRegistry atlas = context.getBean(AtlasMeterRegistry.class); + assertThat(atlas.find("jvm.memory.used").tags("job", "myjob").gauge()).isNull(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java index 2f7b71b1b8e..faed39bf97c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java @@ -82,10 +82,10 @@ public class MeterValueTests { public void valueOfShouldWorkInBinder() { MockEnvironment environment = new MockEnvironment(); TestPropertyValues.of("duration=10ms", "long=20").applyTo(environment); - assertThat(Binder.get(environment).bind("duration", Bindable.of(MeterValue.class)) - .get().getValue(Type.TIMER)).isEqualTo(10000000); - assertThat(Binder.get(environment).bind("long", Bindable.of(MeterValue.class)) - .get().getValue(Type.TIMER)).isEqualTo(20000000); + assertThat(Binder.get(environment).bind("duration", Bindable.of(MeterValue.class)).get().getValue(Type.TIMER)) + .isEqualTo(10000000); + assertThat(Binder.get(environment).bind("long", Bindable.of(MeterValue.class)).get().getValue(Type.TIMER)) + .isEqualTo(20000000); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java index 25583be32e2..ad8d28d992f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java @@ -42,36 +42,33 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MetricsAutoConfigurationIntegrationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()); @Test public void propertyBasedMeterFilteringIsAutoConfigured() { - this.contextRunner.withPropertyValues("management.metrics.enable.my.org=false") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.timer("my.org.timer"); - assertThat(registry.find("my.org.timer").timer()).isNull(); - }); + this.contextRunner.withPropertyValues("management.metrics.enable.my.org=false").run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.timer("my.org.timer"); + assertThat(registry.find("my.org.timer").timer()).isNull(); + }); } @Test public void propertyBasedCommonTagsIsAutoConfigured() { - this.contextRunner.withPropertyValues("management.metrics.tags.region=test", - "management.metrics.tags.origin=local").run((context) -> { + this.contextRunner + .withPropertyValues("management.metrics.tags.region=test", "management.metrics.tags.origin=local") + .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); registry.counter("my.counter", "env", "qa"); - assertThat(registry.find("my.counter").tags("env", "qa") - .tags("region", "test").tags("origin", "local").counter()) - .isNotNull(); + assertThat(registry.find("my.counter").tags("env", "qa").tags("region", "test") + .tags("origin", "local").counter()).isNotNull(); }); } @Test public void simpleMeterRegistryIsUsedAsAFallback() { - this.contextRunner - .run((context) -> assertThat(context.getBean(MeterRegistry.class)) - .isInstanceOf(SimpleMeterRegistry.class)); + this.contextRunner.run( + (context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); } @Test @@ -85,8 +82,7 @@ public class MetricsAutoConfigurationIntegrationTests { @Test public void noCompositeIsCreatedWhenASingleMeterRegistryIsAutoConfigured() { - new ApplicationContextRunner() - .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class)) + new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class)) .run((context) -> assertThat(context.getBean(MeterRegistry.class)) .isInstanceOf(GraphiteMeterRegistry.class)); } @@ -103,10 +99,8 @@ public class MetricsAutoConfigurationIntegrationTests { @Test public void compositeCreatedWithMultipleRegistries() { - new ApplicationContextRunner() - .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)) - .run((context) -> { + new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); assertThat(((CompositeMeterRegistry) registry).getRegistries()) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java index 72ddf15d0fe..63cbf2059b0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java @@ -48,36 +48,28 @@ public class MetricsAutoConfigurationTests { @Test public void autoConfiguresAClock() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(Clock.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Clock.class)); } @Test public void allowsACustomClockToBeUsed() { this.contextRunner.withUserConfiguration(CustomClockConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasBean("customClock")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasBean("customClock")); } @SuppressWarnings("unchecked") @Test public void configuresMeterRegistries() { - this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class) - .run((context) -> { - MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); - MeterFilter[] filters = (MeterFilter[]) ReflectionTestUtils - .getField(meterRegistry, "filters"); - assertThat(filters).hasSize(3); - assertThat(filters[0].accept((Meter.Id) null)) - .isEqualTo(MeterFilterReply.DENY); - assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class); - assertThat(filters[2].accept((Meter.Id) null)) - .isEqualTo(MeterFilterReply.ACCEPT); - verify((MeterBinder) context.getBean("meterBinder")) - .bindTo(meterRegistry); - verify(context.getBean(MeterRegistryCustomizer.class)) - .customize(meterRegistry); - }); + this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class).run((context) -> { + MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); + MeterFilter[] filters = (MeterFilter[]) ReflectionTestUtils.getField(meterRegistry, "filters"); + assertThat(filters).hasSize(3); + assertThat(filters[0].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.DENY); + assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class); + assertThat(filters[2].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.ACCEPT); + verify((MeterBinder) context.getBean("meterBinder")).bindTo(meterRegistry); + verify(context.getBean(MeterRegistryCustomizer.class)).customize(meterRegistry); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java index 63125408750..844c294802a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathOverrides({ "org.apache.logging.log4j:log4j-core:2.9.0", - "org.apache.logging.log4j:log4j-slf4j-impl:2.9.0" }) +@ClassPathOverrides({ "org.apache.logging.log4j:log4j-core:2.9.0", "org.apache.logging.log4j:log4j-slf4j-impl:2.9.0" }) public class MetricsAutoConfigurationWithLog4j2AndLogbackTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() @@ -43,8 +42,7 @@ public class MetricsAutoConfigurationWithLog4j2AndLogbackTests { @Test public void doesNotConfigureLogbackMetrics() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(LogbackMetrics.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LogbackMetrics.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java index a7372ab745e..3bc7a4179e2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java @@ -41,15 +41,12 @@ public class MissingRequiredConfigurationFailureAnalyzerTests { FailureAnalysis analysis = new MissingRequiredConfigurationFailureAnalyzer() .analyze(createFailure(MissingAccountIdConfiguration.class)); assertThat(analysis).isNotNull(); - assertThat(analysis.getDescription()) - .isEqualTo("accountId must be set to report metrics to New Relic."); - assertThat(analysis.getAction()).isEqualTo( - "Update your application to provide the missing configuration."); + assertThat(analysis.getDescription()).isEqualTo("accountId must be set to report metrics to New Relic."); + assertThat(analysis.getAction()).isEqualTo("Update your application to provide the missing configuration."); } private Exception createFailure(Class configuration) { - try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - configuration)) { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { fail("Expected failure did not occur"); return null; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java index 5b91bf07a5d..eae3a694d9a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java @@ -46,120 +46,103 @@ public class PropertiesMeterFilterTests { @Test public void createWhenPropertiesIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new PropertiesMeterFilter(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null)) .withMessageContaining("Properties must not be null"); } @Test public void acceptWhenHasNoEnabledPropertiesShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties()); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.NEUTRAL); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test public void acceptWhenHasNoMatchingEnabledPropertyShouldReturnNeutral() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("enable.something.else=false")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.NEUTRAL); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.something.else=false")); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test public void acceptWhenHasEnableFalseShouldReturnDeny() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("enable.spring.boot=false")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.DENY); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring.boot=false")); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test public void acceptWhenHasEnableTrueShouldReturnNeutral() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("enable.spring.boot=true")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.NEUTRAL); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring.boot=true")); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test public void acceptWhenHasHigherEnableFalseShouldReturnDeny() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("enable.spring=false")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.DENY); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring=false")); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test public void acceptWhenHasHigherEnableTrueShouldReturnNeutral() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("enable.spring=true")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.NEUTRAL); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring=true")); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test public void acceptWhenHasHigherEnableFalseExactEnableTrueShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("enable.spring=false", "enable.spring.boot=true")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.NEUTRAL); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test public void acceptWhenHasHigherEnableTrueExactEnableFalseShouldReturnDeny() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("enable.spring=true", "enable.spring.boot=false")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.DENY); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test public void acceptWhenHasAllEnableFalseShouldReturnDeny() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("enable.all=false")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.DENY); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.all=false")); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test public void acceptWhenHasAllEnableFalseButHigherEnableTrueShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("enable.all=false", "enable.spring=true")); - assertThat(filter.accept(createMeterId("spring.boot"))) - .isEqualTo(MeterFilterReply.NEUTRAL); + assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test public void configureWhenHasHistogramTrueShouldSetPercentilesHistogramToTrue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=true")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isTrue(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isTrue(); } @Test public void configureWhenHasHistogramFalseShouldSetPercentilesHistogramToFalse() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=false")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isFalse(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isFalse(); } @Test public void configureWhenHasHigherHistogramTrueShouldSetPercentilesHistogramToTrue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=true")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isTrue(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isTrue(); } @Test public void configureWhenHasHigherHistogramFalseShouldSetPercentilesHistogramToFalse() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=false")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isFalse(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isFalse(); } @Test @@ -167,8 +150,8 @@ public class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=true", "distribution.percentiles-histogram.spring.boot=false")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isFalse(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isFalse(); } @Test @@ -176,79 +159,73 @@ public class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=false", "distribution.percentiles-histogram.spring.boot=true")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isTrue(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isTrue(); } @Test public void configureWhenAllHistogramTrueSetPercentilesHistogramToTrue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.all=true")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).isPercentileHistogram()).isTrue(); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .isPercentileHistogram()).isTrue(); } @Test public void configureWhenHasPercentilesShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring.boot=1,1.5,2")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getPercentiles()).containsExactly(1, - 1.5, 2); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) + .containsExactly(1, 1.5, 2); } @Test public void configureWhenHasHigherPercentilesShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring=1,1.5,2")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getPercentiles()).containsExactly(1, - 1.5, 2); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) + .containsExactly(1, 1.5, 2); } @Test public void configureWhenHasHigherPercentilesAndLowerShouldSetPercentilesToHigher() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("distribution.percentiles.spring=1,1.5,2", - "distribution.percentiles.spring.boot=3,3.5,4")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getPercentiles()).containsExactly(3, - 3.5, 4); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( + "distribution.percentiles.spring=1,1.5,2", "distribution.percentiles.spring.boot=3,3.5,4")); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) + .containsExactly(3, 3.5, 4); } @Test public void configureWhenAllPercentilesSetShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.all=1,1.5,2")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getPercentiles()).containsExactly(1, - 1.5, 2); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) + .containsExactly(1, 1.5, 2); } @Test public void configureWhenHasSlaShouldSetSlaToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.sla.spring.boot=1,2,3")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) + assertThat( + filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) .containsExactly(1000000, 2000000, 3000000); } @Test public void configureWhenHasHigherSlaShouldSetPercentilesToValue() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("distribution.sla.spring=1,2,3")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.sla.spring=1,2,3")); + assertThat( + filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) .containsExactly(1000000, 2000000, 3000000); } @Test public void configureWhenHasHigherSlaAndLowerShouldSetSlaToHigher() { - PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( - "distribution.sla.spring=1,2,3", "distribution.sla.spring.boot=4,5,6")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) + PropertiesMeterFilter filter = new PropertiesMeterFilter( + createProperties("distribution.sla.spring=1,2,3", "distribution.sla.spring.boot=4,5,6")); + assertThat( + filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) .containsExactly(4000000, 5000000, 6000000); } @@ -256,46 +233,40 @@ public class PropertiesMeterFilterTests { public void configureWhenHasMinimumExpectedValueShouldSetMinimumExpectedToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring.boot=10")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getMinimumExpectedValue()) - .isEqualTo(Duration.ofMillis(10).toNanos()); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .getMinimumExpectedValue()).isEqualTo(Duration.ofMillis(10).toNanos()); } @Test public void configureWhenHasHigherMinimumExpectedValueShouldSetMinimumExpectedValueToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring=10")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getMinimumExpectedValue()) - .isEqualTo(Duration.ofMillis(10).toNanos()); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .getMinimumExpectedValue()).isEqualTo(Duration.ofMillis(10).toNanos()); } @Test public void configureWhenHasHigherMinimumExpectedValueAndLowerShouldSetMinimumExpectedValueToHigher() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("distribution.minimum-expected-value.spring=10", - "distribution.minimum-expected-value.spring.boot=50")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getMinimumExpectedValue()) - .isEqualTo(Duration.ofMillis(50).toNanos()); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( + "distribution.minimum-expected-value.spring=10", "distribution.minimum-expected-value.spring.boot=50")); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .getMinimumExpectedValue()).isEqualTo(Duration.ofMillis(50).toNanos()); } @Test public void configureWhenHasMaximumExpectedValueShouldSetMaximumExpectedToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring.boot=5000")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getMaximumExpectedValue()) - .isEqualTo(Duration.ofMillis(5000).toNanos()); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .getMaximumExpectedValue()).isEqualTo(Duration.ofMillis(5000).toNanos()); } @Test public void configureWhenHasHigherMaximumExpectedValueShouldSetMaximumExpectedValueToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring=5000")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getMaximumExpectedValue()) - .isEqualTo(Duration.ofMillis(5000).toNanos()); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .getMaximumExpectedValue()).isEqualTo(Duration.ofMillis(5000).toNanos()); } @Test @@ -303,9 +274,8 @@ public class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring=5000", "distribution.maximum-expected-value.spring.boot=10000")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getMaximumExpectedValue()) - .isEqualTo(Duration.ofMillis(10000).toNanos()); + assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) + .getMaximumExpectedValue()).isEqualTo(Duration.ofMillis(10000).toNanos()); } private Id createMeterId(String name) { @@ -315,16 +285,14 @@ public class PropertiesMeterFilterTests { private Id createMeterId(String name, Meter.Type meterType) { TestMeterRegistry registry = new TestMeterRegistry(); - return Meter.builder(name, meterType, Collections.emptyList()).register(registry) - .getId(); + return Meter.builder(name, meterType, Collections.emptyList()).register(registry).getId(); } private MetricsProperties createProperties(String... properties) { MockEnvironment environment = new MockEnvironment(); TestPropertyValues.of(properties).applyTo(environment); Binder binder = Binder.get(environment); - return binder.bind("", Bindable.of(MetricsProperties.class)) - .orElseGet(MetricsProperties::new); + return binder.bind("", Bindable.of(MetricsProperties.class)).orElseGet(MetricsProperties::new); } private static class TestMeterRegistry extends SimpleMeterRegistry { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java index 331d7b989d8..1e240d93e7b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java @@ -42,8 +42,7 @@ public class ServiceLevelAgreementBoundaryTests { @Test public void getValueForTimerWhenFromDurationStringShouldReturnDurationNanos() { - ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary - .valueOf("123ms"); + ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary.valueOf("123ms"); assertThat(sla.getValue(Type.TIMER)).isEqualTo(123000000); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java index 0fd43d369b2..a3e5737dc9f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java @@ -37,50 +37,41 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SystemMetricsAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); @Test public void autoConfiguresUptimeMetrics() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(UptimeMetrics.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(UptimeMetrics.class)); } @Test public void allowsCustomUptimeMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(UptimeMetrics.class) - .hasBean("customUptimeMetrics")); + this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class).run( + (context) -> assertThat(context).hasSingleBean(UptimeMetrics.class).hasBean("customUptimeMetrics")); } @Test public void autoConfiguresProcessorMetrics() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class)); } @Test public void allowsCustomProcessorMetricsToBeUsed() { - this.contextRunner - .withUserConfiguration(CustomProcessorMetricsConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ProcessorMetrics.class) + this.contextRunner.withUserConfiguration(CustomProcessorMetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class) .hasBean("customProcessorMetrics")); } @Test public void autoConfiguresFileDescriptorMetrics() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(FileDescriptorMetrics.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class)); } @Test public void allowsCustomFileDescriptorMetricsToBeUsed() { - this.contextRunner - .withUserConfiguration(CustomFileDescriptorMetricsConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(FileDescriptorMetrics.class) + this.contextRunner.withUserConfiguration(CustomFileDescriptorMetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class) .hasBean("customFileDescriptorMetrics")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java index ccb979ab84d..08b789db073 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java @@ -33,9 +33,9 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class RabbitMetricsAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of( - RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration( + AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); @Test public void autoConfiguredConnectionFactoryIsInstrumented() { @@ -47,11 +47,10 @@ public class RabbitMetricsAutoConfigurationTests { @Test public void rabbitmqNativeConnectionFactoryInstrumentationCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.rabbitmq=false") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("rabbitmq.connections").meter()).isNull(); - }); + this.contextRunner.withPropertyValues("management.metrics.enable.rabbitmq=false").run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("rabbitmq.connections").meter()).isNull(); + }); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java index 82f80b5df8b..334925de6d8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java @@ -35,41 +35,36 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class CacheMetricsAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withUserConfiguration(CachingConfiguration.class) - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, - CacheMetricsAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withUserConfiguration(CachingConfiguration.class).withConfiguration( + AutoConfigurations.of(CacheAutoConfiguration.class, CacheMetricsAutoConfiguration.class)); @Test public void autoConfiguredCacheManagerIsInstrumented() { - this.contextRunner.withPropertyValues("spring.cache.type=caffeine", - "spring.cache.cache-names=cache1,cache2").run((context) -> { + this.contextRunner.withPropertyValues("spring.cache.type=caffeine", "spring.cache.cache-names=cache1,cache2") + .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("cache.gets").tags("name", "cache1") - .tags("cacheManager", "cacheManager").meter(); - registry.get("cache.gets").tags("name", "cache2") - .tags("cacheManager", "cacheManager").meter(); + registry.get("cache.gets").tags("name", "cache1").tags("cacheManager", "cacheManager").meter(); + registry.get("cache.gets").tags("name", "cache2").tags("cacheManager", "cacheManager").meter(); }); } @Test public void autoConfiguredNonSupportedCacheManagerIsIgnored() { - this.contextRunner.withPropertyValues("spring.cache.type=simple", - "spring.cache.cache-names=cache1,cache2").run((context) -> { + this.contextRunner.withPropertyValues("spring.cache.type=simple", "spring.cache.cache-names=cache1,cache2") + .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("cache.gets").tags("name", "cache1") - .tags("cacheManager", "cacheManager").meter()).isNull(); - assertThat(registry.find("cache.gets").tags("name", "cache2") - .tags("cacheManager", "cacheManager").meter()).isNull(); + assertThat(registry.find("cache.gets").tags("name", "cache1").tags("cacheManager", "cacheManager") + .meter()).isNull(); + assertThat(registry.find("cache.gets").tags("name", "cache2").tags("cacheManager", "cacheManager") + .meter()).isNull(); }); } @Test public void cacheInstrumentationCanBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.enable.cache=false", - "spring.cache.type=caffeine", "spring.cache.cache-names=cache1") - .run((context) -> { + this.contextRunner.withPropertyValues("management.metrics.enable.cache=false", "spring.cache.type=caffeine", + "spring.cache.cache-names=cache1").run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("cache.requests").tags("name", "cache1") .tags("cacheManager", "cacheManager").meter()).isNull(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java index 1e71df211a4..c3845dddee8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java @@ -37,59 +37,48 @@ import static org.assertj.core.api.Assertions.assertThat; public class AppOpticsMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(AppOpticsMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class)); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner - .withPropertyValues("management.metrics.export.appoptics.api-token=abcde") - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AppOpticsMeterRegistry.class) - .hasSingleBean(AppOpticsConfig.class)); + this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") + .withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(AppOpticsMeterRegistry.class).hasSingleBean(AppOpticsConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.appoptics.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(AppOpticsMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) .doesNotHaveBean(AppOpticsConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AppOpticsMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) .hasSingleBean(AppOpticsConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner - .withPropertyValues("management.metrics.export.appoptics.api-token=abcde") + this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") .withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AppOpticsMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(AppOpticsConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner - .withPropertyValues("management.metrics.export.appoptics.api-token=abcde") + this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") .withUserConfiguration(BaseConfiguration.class).run((context) -> { - AppOpticsMeterRegistry registry = context - .getBean(AppOpticsMeterRegistry.class); + AppOpticsMeterRegistry registry = context.getBean(AppOpticsMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); context.close(); assertThat(registry.isClosed()).isTrue(); @@ -122,8 +111,7 @@ public class AppOpticsMetricsExportAutoConfigurationTests { static class CustomRegistryConfiguration { @Bean - public AppOpticsMeterRegistry customRegistry(AppOpticsConfig config, - Clock clock) { + public AppOpticsMeterRegistry customRegistry(AppOpticsConfig config, Clock clock) { return new AppOpticsMeterRegistry(config, clock); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java index f1a7d84401b..68641989592 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java @@ -27,8 +27,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AppOpticsPropertiesConfigAdapterTests extends - StepRegistryPropertiesConfigAdapterTests { +public class AppOpticsPropertiesConfigAdapterTests + extends StepRegistryPropertiesConfigAdapterTests { @Override protected AppOpticsProperties createProperties() { @@ -36,8 +36,7 @@ public class AppOpticsPropertiesConfigAdapterTests extends } @Override - protected AppOpticsPropertiesConfigAdapter createConfigAdapter( - AppOpticsProperties properties) { + protected AppOpticsPropertiesConfigAdapter createConfigAdapter(AppOpticsProperties properties) { return new AppOpticsPropertiesConfigAdapter(properties); } @@ -45,8 +44,7 @@ public class AppOpticsPropertiesConfigAdapterTests extends public void whenPropertiesUrisIsSetAdapterUriReturnsIt() { AppOpticsProperties properties = createProperties(); properties.setUri("https://appoptics.example.com/v1/measurements"); - assertThat(createConfigAdapter(properties).uri()) - .isEqualTo("https://appoptics.example.com/v1/measurements"); + assertThat(createConfigAdapter(properties).uri()).isEqualTo("https://appoptics.example.com/v1/measurements"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java index a8fc696d027..1465c893f9a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java @@ -37,58 +37,47 @@ import static org.assertj.core.api.Assertions.assertThat; public class AtlasMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(AtlasMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class)); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class) - .hasSingleBean(AtlasConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.atlas.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(AtlasMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) .doesNotHaveBean(AtlasConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class) - .hasSingleBean(AtlasConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasBean("customRegistry") - .hasSingleBean(AtlasConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(AtlasMeterRegistry.class).hasBean("customRegistry").hasSingleBean(AtlasConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - AtlasMeterRegistry registry = context - .getBean(AtlasMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + AtlasMeterRegistry registry = context.getBean(AtlasMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java index dbbdbea41a0..7d424a58d57 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java @@ -41,8 +41,7 @@ public class AtlasPropertiesTests { assertThat(properties.getUri()).isEqualTo(config.uri()); assertThat(properties.getMeterTimeToLive()).isEqualTo(config.meterTTL()); assertThat(properties.isLwcEnabled()).isEqualTo(config.lwcEnabled()); - assertThat(properties.getConfigRefreshFrequency()) - .isEqualTo(config.configRefreshFrequency()); + assertThat(properties.getConfigRefreshFrequency()).isEqualTo(config.configRefreshFrequency()); assertThat(properties.getConfigTimeToLive()).isEqualTo(config.configTTL()); assertThat(properties.getConfigUri()).isEqualTo(config.configUri()); assertThat(properties.getEvalUri()).isEqualTo(config.evalUri()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java index f2f4907a3ce..581e24d9a41 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java @@ -37,13 +37,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class DatadogMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(DatadogMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class)); } @Test @@ -56,8 +54,7 @@ public class DatadogMetricsExportAutoConfigurationTests { public void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.datadog.api-key=abcde") - .run((context) -> assertThat(context) - .hasSingleBean(DatadogMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) .hasSingleBean(DatadogConfig.class)); } @@ -65,35 +62,29 @@ public class DatadogMetricsExportAutoConfigurationTests { public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.datadog.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(DatadogMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) .doesNotHaveBean(DatadogConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(DatadogMeterRegistry.class) - .hasSingleBean(DatadogConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(DatadogMeterRegistry.class).hasSingleBean(DatadogConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .withPropertyValues("management.metrics.export.datadog.api-key=abcde") - .run((context) -> assertThat(context) - .hasSingleBean(DatadogMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(DatadogConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.datadog.api-key=abcde") - .run((context) -> { - DatadogMeterRegistry registry = context - .getBean(DatadogMeterRegistry.class); + .withPropertyValues("management.metrics.export.datadog.api-key=abcde").run((context) -> { + DatadogMeterRegistry registry = context.getBean(DatadogMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); context.close(); assertThat(registry.isClosed()).isTrue(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java index 6125426bc87..ad549f82b7d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java @@ -40,13 +40,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class DynatraceMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(DynatraceMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class)); } @Test @@ -57,10 +55,8 @@ public class DynatraceMetricsExportAutoConfigurationTests { @Test public void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .with(mandatoryProperties()) - .run((context) -> assertThat(context) - .hasSingleBean(DynatraceMeterRegistry.class) + this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(mandatoryProperties()) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) .hasSingleBean(DynatraceConfig.class)); } @@ -68,38 +64,32 @@ public class DynatraceMetricsExportAutoConfigurationTests { public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.dynatrace.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(DynatraceMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) .doesNotHaveBean(DynatraceConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(DynatraceMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) .hasSingleBean(DynatraceConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .with(mandatoryProperties()) - .run((context) -> assertThat(context) - .hasSingleBean(DynatraceMeterRegistry.class) + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).with(mandatoryProperties()) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(DynatraceConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .with(mandatoryProperties()).run((context) -> { - DynatraceMeterRegistry registry = context - .getBean(DynatraceMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(mandatoryProperties()).run((context) -> { + DynatraceMeterRegistry registry = context.getBean(DynatraceMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } private Function mandatoryProperties() { @@ -146,8 +136,7 @@ public class DynatraceMetricsExportAutoConfigurationTests { static class CustomRegistryConfiguration { @Bean - public DynatraceMeterRegistry customRegistry(DynatraceConfig config, - Clock clock) { + public DynatraceMeterRegistry customRegistry(DynatraceConfig config, Clock clock) { return new DynatraceMeterRegistry(config, clock); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java index 67a27d3e113..3e3802c1165 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java @@ -31,32 +31,28 @@ public class DynatracePropertiesConfigAdapterTests { public void whenPropertiesUriIsSetAdapterUriReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setUri("https://dynatrace.example.com"); - assertThat(new DynatracePropertiesConfigAdapter(properties).uri()) - .isEqualTo("https://dynatrace.example.com"); + assertThat(new DynatracePropertiesConfigAdapter(properties).uri()).isEqualTo("https://dynatrace.example.com"); } @Test public void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setApiToken("123ABC"); - assertThat(new DynatracePropertiesConfigAdapter(properties).apiToken()) - .isEqualTo("123ABC"); + assertThat(new DynatracePropertiesConfigAdapter(properties).apiToken()).isEqualTo("123ABC"); } @Test public void whenPropertiesDeviceIdIsSetAdapterDeviceIdReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setDeviceId("dev-1"); - assertThat(new DynatracePropertiesConfigAdapter(properties).deviceId()) - .isEqualTo("dev-1"); + assertThat(new DynatracePropertiesConfigAdapter(properties).deviceId()).isEqualTo("dev-1"); } @Test public void whenPropertiesTechnologyTypeIsSetAdapterTechnologyTypeReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setTechnologyType("tech-1"); - assertThat(new DynatracePropertiesConfigAdapter(properties).technologyType()) - .isEqualTo("tech-1"); + assertThat(new DynatracePropertiesConfigAdapter(properties).technologyType()).isEqualTo("tech-1"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java index df532cf4743..db5fd8c4c65 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java @@ -37,59 +37,49 @@ import static org.assertj.core.api.Assertions.assertThat; public class ElasticMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ElasticMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class)); } @Test public void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class) - .hasSingleBean(ElasticConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.elastic.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ElasticMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) .doesNotHaveBean(ElasticConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class) - .hasSingleBean(ElasticConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(ElasticConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - ElasticMeterRegistry registry = context - .getBean(ElasticMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + ElasticMeterRegistry registry = context.getBean(ElasticMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java index 80fd302edef..a05d66d2bb2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java @@ -31,56 +31,49 @@ public class ElasticPropertiesConfigAdapterTests { public void whenPropertiesHostsIsSetAdapterHostsReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setHost("https://elastic.example.com"); - assertThat(new ElasticPropertiesConfigAdapter(properties).host()) - .isEqualTo("https://elastic.example.com"); + assertThat(new ElasticPropertiesConfigAdapter(properties).host()).isEqualTo("https://elastic.example.com"); } @Test public void whenPropertiesIndexIsSetAdapterIndexReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setIndex("test-metrics"); - assertThat(new ElasticPropertiesConfigAdapter(properties).index()) - .isEqualTo("test-metrics"); + assertThat(new ElasticPropertiesConfigAdapter(properties).index()).isEqualTo("test-metrics"); } @Test public void whenPropertiesIndexDateFormatIsSetAdapterIndexDateFormatReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setIndexDateFormat("yyyy"); - assertThat(new ElasticPropertiesConfigAdapter(properties).indexDateFormat()) - .isEqualTo("yyyy"); + assertThat(new ElasticPropertiesConfigAdapter(properties).indexDateFormat()).isEqualTo("yyyy"); } @Test public void whenPropertiesTimestampFieldNameIsSetAdapterTimestampFieldNameReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setTimestampFieldName("@test"); - assertThat(new ElasticPropertiesConfigAdapter(properties).timestampFieldName()) - .isEqualTo("@test"); + assertThat(new ElasticPropertiesConfigAdapter(properties).timestampFieldName()).isEqualTo("@test"); } @Test public void whenPropertiesAutoCreateIndexIsSetAdapterAutoCreateIndexReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setAutoCreateIndex(false); - assertThat(new ElasticPropertiesConfigAdapter(properties).autoCreateIndex()) - .isFalse(); + assertThat(new ElasticPropertiesConfigAdapter(properties).autoCreateIndex()).isFalse(); } @Test public void whenPropertiesUserNameIsSetAdapterUserNameReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setUserName("alice"); - assertThat(new ElasticPropertiesConfigAdapter(properties).userName()) - .isEqualTo("alice"); + assertThat(new ElasticPropertiesConfigAdapter(properties).userName()).isEqualTo("alice"); } @Test public void whenPropertiesPasswordIsSetAdapterPasswordReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setPassword("secret"); - assertThat(new ElasticPropertiesConfigAdapter(properties).password()) - .isEqualTo("secret"); + assertThat(new ElasticPropertiesConfigAdapter(properties).password()).isEqualTo("secret"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java index d5b8dca9ebe..af097088bc4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java @@ -39,8 +39,7 @@ public class ElasticPropertiesTests extends StepRegistryPropertiesTests { assertThat(properties.getIndex()).isEqualTo(config.index()); assertThat(properties.getIndexDateFormat()).isEqualTo(config.indexDateFormat()); assertThat(properties.getPassword()).isEqualTo(config.password()); - assertThat(properties.getTimestampFieldName()) - .isEqualTo(config.timestampFieldName()); + assertThat(properties.getTimestampFieldName()).isEqualTo(config.timestampFieldName()); assertThat(properties.getUserName()).isEqualTo(config.userName()); assertThat(properties.isAutoCreateIndex()).isEqualTo(config.autoCreateIndex()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java index 70907151b4e..1f90b35f5a4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java @@ -37,58 +37,48 @@ import static org.assertj.core.api.Assertions.assertThat; public class GangliaMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(GangliaMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class)); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class) - .hasSingleBean(GangliaConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.ganglia.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(GangliaMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) .doesNotHaveBean(GangliaConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class) - .hasSingleBean(GangliaConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(GangliaConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - GangliaMeterRegistry registry = context - .getBean(GangliaMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + GangliaMeterRegistry registry = context.getBean(GangliaMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java index d4c2a959d8d..024ad86867c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java @@ -39,73 +39,60 @@ import static org.assertj.core.api.Assertions.assertThat; public class GraphiteMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(GraphiteMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class)); } @Test public void autoConfiguresUseTagsAsPrefix() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues( - "management.metrics.export.graphite.tags-as-prefix=app") - .run((context) -> { + .withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app").run((context) -> { assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); - GraphiteMeterRegistry registry = context - .getBean(GraphiteMeterRegistry.class); + GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); registry.counter("test.count", Tags.of("app", "myapp")); - assertThat(registry.getDropwizardRegistry().getMeters()) - .containsOnlyKeys("myapp.testCount"); + assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("myapp.testCount"); }); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(GraphiteMeterRegistry.class) - .hasSingleBean(GraphiteConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(GraphiteMeterRegistry.class).hasSingleBean(GraphiteConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.graphite.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(GraphiteMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) .doesNotHaveBean(GraphiteConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(GraphiteMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) .hasSingleBean(GraphiteConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(GraphiteMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(GraphiteConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - GraphiteMeterRegistry registry = context - .getBean(GraphiteMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java index 7fcf9716cef..f08f1243afe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java @@ -38,59 +38,48 @@ import static org.assertj.core.api.Assertions.assertThat; public class HumioMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(HumioMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class)); } @Test public void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class) - .hasSingleBean(HumioConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.humio.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HumioMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) .doesNotHaveBean(HumioConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class) - .hasSingleBean(HumioConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasBean("customRegistry") - .hasSingleBean(HumioConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(HumioMeterRegistry.class).hasBean("customRegistry").hasSingleBean(HumioConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - HumioMeterRegistry registry = context - .getBean(HumioMeterRegistry.class); - new JvmMemoryMetrics().bindTo(registry); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + HumioMeterRegistry registry = context.getBean(HumioMeterRegistry.class); + new JvmMemoryMetrics().bindTo(registry); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java index 9034fb5ab73..0182af7bf04 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java @@ -33,16 +33,14 @@ public class HumioPropertiesConfigAdapterTests { public void whenApiTokenIsSetAdapterApiTokenReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setApiToken("ABC123"); - assertThat(new HumioPropertiesConfigAdapter(properties).apiToken()) - .isEqualTo("ABC123"); + assertThat(new HumioPropertiesConfigAdapter(properties).apiToken()).isEqualTo("ABC123"); } @Test public void whenPropertiesRepositoryIsSetAdapterRepositoryReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setRepository("test"); - assertThat(new HumioPropertiesConfigAdapter(properties).repository()) - .isEqualTo("test"); + assertThat(new HumioPropertiesConfigAdapter(properties).repository()).isEqualTo("test"); } @Test @@ -57,8 +55,7 @@ public class HumioPropertiesConfigAdapterTests { public void whenPropertiesUriIsSetAdapterUriReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setUri("https://humio.example.com"); - assertThat(new HumioPropertiesConfigAdapter(properties).uri()) - .isEqualTo("https://humio.example.com"); + assertThat(new HumioPropertiesConfigAdapter(properties).uri()).isEqualTo("https://humio.example.com"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java index 2e41a05d5f2..3bc0f1d9ea1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java @@ -37,58 +37,47 @@ import static org.assertj.core.api.Assertions.assertThat; public class InfluxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(InfluxMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class)); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class) - .hasSingleBean(InfluxConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.influx.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(InfluxMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) .doesNotHaveBean(InfluxConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class) - .hasSingleBean(InfluxConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(InfluxConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(InfluxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(InfluxConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - InfluxMeterRegistry registry = context - .getBean(InfluxMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + InfluxMeterRegistry registry = context.getBean(InfluxMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java index 9fdec4e0288..44f9cf0d0f9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java @@ -40,12 +40,9 @@ public class InfluxPropertiesTests extends StepRegistryPropertiesTests { assertThat(properties.getUserName()).isEqualTo(config.userName()); assertThat(properties.getPassword()).isEqualTo(config.password()); assertThat(properties.getRetentionPolicy()).isEqualTo(config.retentionPolicy()); - assertThat(properties.getRetentionDuration()) - .isEqualTo(config.retentionDuration()); - assertThat(properties.getRetentionReplicationFactor()) - .isEqualTo(config.retentionReplicationFactor()); - assertThat(properties.getRetentionShardDuration()) - .isEqualTo(config.retentionShardDuration()); + assertThat(properties.getRetentionDuration()).isEqualTo(config.retentionDuration()); + assertThat(properties.getRetentionReplicationFactor()).isEqualTo(config.retentionReplicationFactor()); + assertThat(properties.getRetentionShardDuration()).isEqualTo(config.retentionShardDuration()); assertThat(properties.getUri()).isEqualTo(config.uri()); assertThat(properties.isCompressed()).isEqualTo(config.compressed()); assertThat(properties.isAutoCreateDb()).isEqualTo(config.autoCreateDb()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java index b1d7da1af49..db221dc3851 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java @@ -37,57 +37,46 @@ import static org.assertj.core.api.Assertions.assertThat; public class JmxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class)); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class) - .hasSingleBean(JmxConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run( + (context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.jmx.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(JmxMeterRegistry.class) - .doesNotHaveBean(JmxConfig.class)); + .withPropertyValues("management.metrics.export.jmx.enabled=false").run((context) -> assertThat(context) + .doesNotHaveBean(JmxMeterRegistry.class).doesNotHaveBean(JmxConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class) - .hasSingleBean(JmxConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class).hasBean("customRegistry") - .hasSingleBean(JmxConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(JmxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(JmxConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - JmxMeterRegistry registry = context.getBean(JmxMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + JmxMeterRegistry registry = context.getBean(JmxMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java index 057a1469407..769b2a8590d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java @@ -37,58 +37,47 @@ import static org.assertj.core.api.Assertions.assertThat; public class KairosMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(KairosMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class)); } @Test public void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class) - .hasSingleBean(KairosConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.kairos.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(KairosMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) .doesNotHaveBean(KairosConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class) - .hasSingleBean(KairosConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(KairosConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(KairosMeterRegistry.class).hasBean("customRegistry").hasSingleBean(KairosConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - KairosMeterRegistry registry = context - .getBean(KairosMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + KairosMeterRegistry registry = context.getBean(KairosMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java index 99b00dc012d..28795b1c5fa 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java @@ -27,8 +27,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class KairosPropertiesConfigAdapterTests extends - StepRegistryPropertiesConfigAdapterTests { +public class KairosPropertiesConfigAdapterTests + extends StepRegistryPropertiesConfigAdapterTests { @Override protected KairosProperties createProperties() { @@ -36,8 +36,7 @@ public class KairosPropertiesConfigAdapterTests extends } @Override - protected KairosPropertiesConfigAdapter createConfigAdapter( - KairosProperties properties) { + protected KairosPropertiesConfigAdapter createConfigAdapter(KairosProperties properties) { return new KairosPropertiesConfigAdapter(properties); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java index 9b623a89039..18d641267ec 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java @@ -36,10 +36,8 @@ public class KairosPropertiesTests extends StepRegistryPropertiesTests { KairosConfig config = KairosConfig.DEFAULT; assertStepRegistryDefaultValues(properties, config); assertThat(properties.getUri()).isEqualToIgnoringWhitespace(config.uri()); - assertThat(properties.getUserName()) - .isEqualToIgnoringWhitespace(config.userName()); - assertThat(properties.getPassword()) - .isEqualToIgnoringWhitespace(config.password()); + assertThat(properties.getUserName()).isEqualToIgnoringWhitespace(config.userName()); + assertThat(properties.getPassword()).isEqualToIgnoringWhitespace(config.password()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java index 45c0e9de9e2..a1cfe81d780 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java @@ -38,13 +38,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class NewRelicMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(NewRelicMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class)); } @Test @@ -66,8 +64,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context) - .hasSingleBean(NewRelicMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); } @@ -75,8 +72,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(NewRelicMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) .doesNotHaveBean(NewRelicConfig.class)); } @@ -85,8 +81,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicConfig.class) - .hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(NewRelicConfig.class).hasBean("customConfig")); } @Test @@ -94,8 +89,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context) - .hasSingleBean(NewRelicMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) .hasBean("customRegistry")); } @@ -105,8 +99,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=abcde") .withUserConfiguration(BaseConfiguration.class).run((context) -> { - NewRelicMeterRegistry registry = context - .getBean(NewRelicMeterRegistry.class); + NewRelicMeterRegistry registry = context.getBean(NewRelicMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); context.close(); assertThat(registry.isClosed()).isTrue(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java index d1de8bc6e8d..f95e8edfd99 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java @@ -47,118 +47,88 @@ import static org.assertj.core.api.Assertions.assertThat; public class PrometheusMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(PrometheusMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PrometheusMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(PrometheusMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class)); } @Test public void autoConfiguresItsConfigCollectorRegistryAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(PrometheusMeterRegistry.class) - .hasSingleBean(CollectorRegistry.class) - .hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class)); } @Test public void autoConfigurationCanBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.export.prometheus.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(PrometheusMeterRegistry.class) - .doesNotHaveBean(CollectorRegistry.class) - .doesNotHaveBean(PrometheusConfig.class)); + this.contextRunner.withPropertyValues("management.metrics.export.prometheus.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) + .doesNotHaveBean(CollectorRegistry.class).doesNotHaveBean(PrometheusConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(PrometheusMeterRegistry.class) - .hasSingleBean(CollectorRegistry.class) - .hasSingleBean(PrometheusConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class) + .hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(PrometheusMeterRegistry.class) + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(CollectorRegistry.class) .hasSingleBean(PrometheusConfig.class)); } @Test public void allowsCustomCollectorRegistryToBeUsed() { - this.contextRunner - .withUserConfiguration(CustomCollectorRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(PrometheusMeterRegistry.class) - .hasBean("customCollectorRegistry") - .hasSingleBean(CollectorRegistry.class) + this.contextRunner.withUserConfiguration(CustomCollectorRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasBean("customCollectorRegistry").hasSingleBean(CollectorRegistry.class) .hasSingleBean(PrometheusConfig.class)); } @Test public void addsScrapeEndpointToManagementContext() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class) - .withPropertyValues( - "management.endpoints.web.exposure.include=prometheus") - .run((context) -> assertThat(context) - .hasSingleBean(PrometheusScrapeEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=prometheus") + .run((context) -> assertThat(context).hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test public void scrapeEndpointNotAddedToManagementContextWhenNotExposed() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(PrometheusScrapeEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test public void scrapeEndpointCanBeDisabled() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues( - "management.endpoints.web.exposure.include=prometheus") + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include=prometheus") .withPropertyValues("management.endpoint.prometheus.enabled=false") .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(PrometheusScrapeEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test public void allowsCustomScrapeEndpointToBeUsed() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(CustomEndpointConfiguration.class) - .run((context) -> assertThat(context).hasBean("customEndpoint") - .hasSingleBean(PrometheusScrapeEndpoint.class)); + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + .withUserConfiguration(CustomEndpointConfiguration.class).run((context) -> assertThat(context) + .hasBean("customEndpoint").hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test public void withPushGatewayEnabled(CapturedOutput capturedOutput) { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues( - "management.metrics.export.prometheus.pushgateway.enabled=true") + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") .withUserConfiguration(BaseConfiguration.class).run((context) -> { - assertThat(capturedOutput) - .doesNotContain("Invalid PushGateway base url"); + assertThat(capturedOutput).doesNotContain("Invalid PushGateway base url"); hasGatewayURL(context, "http://localhost:9091/metrics/job/"); }); } @@ -166,36 +136,27 @@ public class PrometheusMetricsExportAutoConfigurationTests { @Test @Deprecated public void withCustomLegacyPushGatewayURL(CapturedOutput capturedOutput) { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues( - "management.metrics.export.prometheus.pushgateway.enabled=true", + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", "management.metrics.export.prometheus.pushgateway.base-url=localhost:9090") .withUserConfiguration(BaseConfiguration.class).run((context) -> { - assertThat(capturedOutput).contains("Invalid PushGateway base url") - .contains("localhost:9090"); + assertThat(capturedOutput).contains("Invalid PushGateway base url").contains("localhost:9090"); hasGatewayURL(context, "http://localhost:9090/metrics/job/"); }); } @Test public void withCustomPushGatewayURL() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues( - "management.metrics.export.prometheus.pushgateway.enabled=true", + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", "management.metrics.export.prometheus.pushgateway.base-url=https://example.com:8080") .withUserConfiguration(BaseConfiguration.class) - .run((context) -> hasGatewayURL(context, - "https://example.com:8080/metrics/job/")); + .run((context) -> hasGatewayURL(context, "https://example.com:8080/metrics/job/")); } private void hasGatewayURL(AssertableApplicationContext context, String url) { assertThat(context).hasSingleBean(PrometheusPushGatewayManager.class); - PrometheusPushGatewayManager gatewayManager = context - .getBean(PrometheusPushGatewayManager.class); + PrometheusPushGatewayManager gatewayManager = context.getBean(PrometheusPushGatewayManager.class); Object pushGateway = ReflectionTestUtils.getField(gatewayManager, "pushGateway"); assertThat(pushGateway).hasFieldOrPropertyWithValue("gatewayBaseURL", url); } @@ -226,8 +187,8 @@ public class PrometheusMetricsExportAutoConfigurationTests { static class CustomRegistryConfiguration { @Bean - public PrometheusMeterRegistry customRegistry(PrometheusConfig config, - CollectorRegistry collectorRegistry, Clock clock) { + public PrometheusMeterRegistry customRegistry(PrometheusConfig config, CollectorRegistry collectorRegistry, + Clock clock) { return new PrometheusMeterRegistry(config, collectorRegistry, clock); } @@ -249,8 +210,7 @@ public class PrometheusMetricsExportAutoConfigurationTests { static class CustomEndpointConfiguration { @Bean - public PrometheusScrapeEndpoint customEndpoint( - CollectorRegistry collectorRegistry) { + public PrometheusScrapeEndpoint customEndpoint(CollectorRegistry collectorRegistry) { return new PrometheusScrapeEndpoint(collectorRegistry); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java index 52934d316ae..43f9744c554 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java @@ -40,8 +40,7 @@ public abstract class StepRegistryPropertiesConfigAdapterTests

assertThat(context) - .doesNotHaveBean(SignalFxMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class)); } @Test @@ -55,10 +53,8 @@ public class SignalFxMetricsExportAutoConfigurationTests { @Test public void autoConfiguresWithAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues( - "management.metrics.export.signalfx.access-token=abcde") - .run((context) -> assertThat(context) - .hasSingleBean(SignalFxMeterRegistry.class) + .withPropertyValues("management.metrics.export.signalfx.access-token=abcde") + .run((context) -> assertThat(context).hasSingleBean(SignalFxMeterRegistry.class) .hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class)); } @@ -66,42 +62,32 @@ public class SignalFxMetricsExportAutoConfigurationTests { public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.signalfx.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(SignalFxMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) .doesNotHaveBean(SignalFxConfig.class)); } @Test public void allowsConfigToBeCustomized() { - this.contextRunner - .withPropertyValues( - "management.metrics.export.signalfx.access-token=abcde") + this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(SignalFxMeterRegistry.class) - .hasSingleBean(SignalFxConfig.class).hasBean("customConfig")); + .hasSingleBean(SignalFxMeterRegistry.class).hasSingleBean(SignalFxConfig.class) + .hasBean("customConfig")); } @Test public void allowsRegistryToBeCustomized() { - this.contextRunner - .withPropertyValues( - "management.metrics.export.signalfx.access-token=abcde") + this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(SignalFxConfig.class) - .hasSingleBean(SignalFxMeterRegistry.class) - .hasBean("customRegistry")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class) + .hasSingleBean(SignalFxMeterRegistry.class).hasBean("customRegistry")); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner - .withPropertyValues( - "management.metrics.export.signalfx.access-token=abcde") + this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .withUserConfiguration(BaseConfiguration.class).run((context) -> { - SignalFxMeterRegistry registry = context - .getBean(SignalFxMeterRegistry.class); + SignalFxMeterRegistry registry = context.getBean(SignalFxMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); context.close(); assertThat(registry.isClosed()).isTrue(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java index 7e91cf85535..a086d08b15e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java @@ -40,38 +40,32 @@ import static org.mockito.Mockito.mock; public class SimpleMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); @Test public void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(SimpleMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(SimpleConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(SimpleMeterRegistry.class).hasSingleBean(Clock.class).hasSingleBean(SimpleConfig.class)); } @Test public void backsOffWhenSpecificallyDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.simple.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(SimpleMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) .doesNotHaveBean(SimpleConfig.class)); } @Test public void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class) - .hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig")); } @Test public void backsOffEntirelyWithCustomMeterRegistry() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MeterRegistry.class) - .hasBean("customRegistry").doesNotHaveBean(SimpleConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(MeterRegistry.class).hasBean("customRegistry").doesNotHaveBean(SimpleConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java index 03562d2aa27..abbc5c44ab2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java @@ -38,59 +38,47 @@ import static org.assertj.core.api.Assertions.assertThat; public class StatsdMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(StatsdMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class)); } @Test public void autoConfiguresItsConfigMeterRegistryAndMetrics() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class) - .hasSingleBean(StatsdConfig.class) - .hasSingleBean(StatsdMetrics.class)); + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasSingleBean(StatsdConfig.class).hasSingleBean(StatsdMetrics.class)); } @Test public void autoConfigurationCanBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.export.statsd.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(StatsdMeterRegistry.class) + this.contextRunner.withPropertyValues("management.metrics.export.statsd.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) .doesNotHaveBean(StatsdConfig.class)); } @Test public void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class) - .hasSingleBean(StatsdConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(StatsdMeterRegistry.class).hasSingleBean(StatsdConfig.class).hasBean("customConfig")); } @Test public void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(StatsdConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(StatsdMeterRegistry.class).hasBean("customRegistry").hasSingleBean(StatsdConfig.class)); } @Test public void stopsMeterRegistryWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - StatsdMeterRegistry registry = context - .getBean(StatsdMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + StatsdMeterRegistry registry = context.getBean(StatsdMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java index 47ccbdef842..932f86db600 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java @@ -38,8 +38,7 @@ public class StatsdPropertiesTests { assertThat(properties.getPort()).isEqualTo(config.port()); assertThat(properties.getMaxPacketLength()).isEqualTo(config.maxPacketLength()); assertThat(properties.getPollingFrequency()).isEqualTo(config.pollingFrequency()); - assertThat(properties.isPublishUnchangedMeters()) - .isEqualTo(config.publishUnchangedMeters()); + assertThat(properties.isPublishUnchangedMeters()).isEqualTo(config.publishUnchangedMeters()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java index ec7ac0fede8..e17fca046e2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java @@ -37,13 +37,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class WavefrontMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WavefrontMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WavefrontMetricsExportAutoConfiguration.class)); @Test public void backsOffWithoutAClock() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(WavefrontMeterRegistry.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class)); } @Test @@ -56,8 +54,7 @@ public class WavefrontMetricsExportAutoConfigurationTests { public void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.wavefront.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(WavefrontMeterRegistry.class) + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) .doesNotHaveBean(WavefrontConfig.class)); } @@ -65,27 +62,23 @@ public class WavefrontMetricsExportAutoConfigurationTests { public void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(WavefrontMeterRegistry.class) - .hasSingleBean(WavefrontConfig.class).hasBean("customConfig")); + .hasSingleBean(WavefrontMeterRegistry.class).hasSingleBean(WavefrontConfig.class) + .hasBean("customConfig")); } @Test public void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(WavefrontConfig.class) - .hasSingleBean(WavefrontMeterRegistry.class) - .hasBean("customRegistry")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(WavefrontConfig.class) + .hasSingleBean(WavefrontMeterRegistry.class).hasBean("customRegistry")); } @Test public void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") - .run((context) -> { - WavefrontMeterRegistry registry = context - .getBean(WavefrontMeterRegistry.class); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde").run((context) -> { + WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); context.close(); assertThat(registry.isClosed()).isTrue(); @@ -128,8 +121,7 @@ public class WavefrontMetricsExportAutoConfigurationTests { static class CustomRegistryConfiguration { @Bean - public WavefrontMeterRegistry customRegistry(WavefrontConfig config, - Clock clock) { + public WavefrontMeterRegistry customRegistry(WavefrontConfig config, Clock clock) { return new WavefrontMeterRegistry(config, clock); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java index f1aa52a23be..5b6675e12cf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java @@ -29,8 +29,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class WavefrontPropertiesConfigAdapterTests extends - StepRegistryPropertiesConfigAdapterTests { +public class WavefrontPropertiesConfigAdapterTests + extends StepRegistryPropertiesConfigAdapterTests { @Override protected WavefrontProperties createProperties() { @@ -38,8 +38,7 @@ public class WavefrontPropertiesConfigAdapterTests extends } @Override - protected WavefrontPropertiesConfigAdapter createConfigAdapter( - WavefrontProperties properties) { + protected WavefrontPropertiesConfigAdapter createConfigAdapter(WavefrontProperties properties) { return new WavefrontPropertiesConfigAdapter(properties); } @@ -47,8 +46,7 @@ public class WavefrontPropertiesConfigAdapterTests extends public void whenPropertiesUriIsSetAdapterUriReturnsIt() { WavefrontProperties properties = createProperties(); properties.setUri(URI.create("https://wavefront.example.com")); - assertThat(createConfigAdapter(properties).uri()) - .isEqualTo("https://wavefront.example.com"); + assertThat(createConfigAdapter(properties).uri()).isEqualTo("https://wavefront.example.com"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java index ee6d44d0ea4..da2fd1dc8a5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java @@ -54,62 +54,45 @@ import static org.assertj.core.api.Assertions.assertThat; public class DataSourcePoolMetricsAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") - .with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(DataSourcePoolMetricsAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true").with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(DataSourcePoolMetricsAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class); @Test public void autoConfiguredDataSourceIsInstrumented() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .run((context) -> { context.getBean(DataSource.class).getConnection().getMetaData(); MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "dataSource") - .meter(); + registry.get("jdbc.connections.max").tags("name", "dataSource").meter(); }); } @Test public void dataSourceInstrumentationCanBeDisabled() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("management.metrics.enable.jdbc=false") - .run((context) -> { + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("management.metrics.enable.jdbc=false").run((context) -> { context.getBean(DataSource.class).getConnection().getMetaData(); MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("jdbc.connections.max") - .tags("name", "dataSource").meter()).isNull(); + assertThat(registry.find("jdbc.connections.max").tags("name", "dataSource").meter()).isNull(); }); } @Test public void allDataSourcesCanBeInstrumented() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(TwoDataSourcesConfiguration.class) - .run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection() - .getMetaData(); - context.getBean("secondOne", DataSource.class).getConnection() - .getMetaData(); + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withUserConfiguration(TwoDataSourcesConfiguration.class).run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); + context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); MeterRegistry registry = context.getBean(MeterRegistry.class); registry.get("jdbc.connections.max").tags("name", "first").meter(); - registry.get("jdbc.connections.max").tags("name", "secondOne") - .meter(); + registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); }); } @Test public void autoConfiguredHikariDataSourceIsInstrumented() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .run((context) -> { context.getBean(DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -119,12 +102,8 @@ public class DataSourcePoolMetricsAutoConfigurationTests { @Test public void autoConfiguredHikariDataSourceIsInstrumentedWhenUsingDataSourceInitialization() { - this.contextRunner - .withPropertyValues( - "spring.datasource.schema:db/create-custom-schema.sql") - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.schema:db/create-custom-schema.sql") + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean(DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); registry.get("hikaricp.connections").meter(); @@ -134,9 +113,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { @Test public void hikariCanBeInstrumentedAfterThePoolHasBeenSealed() { this.contextRunner.withUserConfiguration(HikariSealingConfiguration.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { assertThat(context).hasNotFailed(); context.getBean(DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -147,9 +124,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { @Test public void hikariDataSourceInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.hikaricp=false") - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean(DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("hikaricp.connections").meter()).isNull(); @@ -159,71 +134,53 @@ public class DataSourcePoolMetricsAutoConfigurationTests { @Test public void allHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(TwoHikariDataSourcesConfiguration.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean("firstDataSource", DataSource.class).getConnection(); context.getBean("secondOne", DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource") - .meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne") - .meter(); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); }); } @Test public void someHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(MixedDataSourcesConfiguration.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean("firstDataSource", DataSource.class).getConnection(); context.getBean("secondOne", DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.get("hikaricp.connections").meter().getId() - .getTags()) - .containsExactly(Tag.of("pool", "firstDataSource")); + assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) + .containsExactly(Tag.of("pool", "firstDataSource")); }); } @Test public void hikariProxiedDataSourceCanBeInstrumented() { - this.contextRunner - .withUserConfiguration(ProxiedHikariDataSourcesConfiguration.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - context.getBean("proxiedDataSource", DataSource.class) - .getConnection(); - context.getBean("delegateDataSource", DataSource.class) - .getConnection(); + this.contextRunner.withUserConfiguration(ProxiedHikariDataSourcesConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { + context.getBean("proxiedDataSource", DataSource.class).getConnection(); + context.getBean("delegateDataSource", DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource") - .meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne") - .meter(); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); }); } @Test public void hikariDataSourceIsInstrumentedWithoutMetadataProvider() { - this.contextRunner.withUserConfiguration(OneHikariDataSourceConfiguration.class) - .run((context) -> { - assertThat(context) - .doesNotHaveBean(DataSourcePoolMetadataProvider.class); - context.getBean("hikariDataSource", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.get("hikaricp.connections").meter().getId() - .getTags()) - .containsExactly(Tag.of("pool", "hikariDataSource")); - }); + this.contextRunner.withUserConfiguration(OneHikariDataSourceConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean(DataSourcePoolMetadataProvider.class); + context.getBean("hikariDataSource", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) + .containsExactly(Tag.of("pool", "hikariDataSource")); + }); } private static HikariDataSource createHikariDataSource(String poolName) { String url = "jdbc:hsqldb:mem:test-" + UUID.randomUUID(); - HikariDataSource hikariDataSource = DataSourceBuilder.create().url(url) - .type(HikariDataSource.class).build(); + HikariDataSource hikariDataSource = DataSourceBuilder.create().url(url).type(HikariDataSource.class).build(); hikariDataSource.setPoolName(poolName); return hikariDataSource; } @@ -278,8 +235,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { @Bean public DataSource proxiedDataSource() { - return (DataSource) new ProxyFactory( - createHikariDataSource("firstDataSource")).getProxy(); + return (DataSource) new ProxyFactory(createHikariDataSource("firstDataSource")).getProxy(); } @Bean @@ -314,16 +270,15 @@ public class DataSourcePoolMetricsAutoConfigurationTests { private HikariDataSource createHikariDataSource(String poolName) { String url = "jdbc:hsqldb:mem:test-" + UUID.randomUUID(); - HikariDataSource hikariDataSource = DataSourceBuilder.create().url(url) - .type(HikariDataSource.class).build(); + HikariDataSource hikariDataSource = DataSourceBuilder.create().url(url).type(HikariDataSource.class) + .build(); hikariDataSource.setPoolName(poolName); return hikariDataSource; } private org.apache.tomcat.jdbc.pool.DataSource createTomcatDataSource() { String url = "jdbc:hsqldb:mem:test-" + UUID.randomUUID(); - return DataSourceBuilder.create().url(url) - .type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); + return DataSourceBuilder.create().url(url).type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } } @@ -344,8 +299,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof HikariDataSource) { try { ((HikariDataSource) bean).getConnection().close(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java index 72ee78f6bc4..ca0fad58fee 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java @@ -58,40 +58,31 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class JerseyServerMetricsAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); private final WebApplicationContextRunner webContextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(JerseyAutoConfiguration.class, - JerseyServerMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, - MetricsAutoConfiguration.class)) - .withUserConfiguration(ResourceConfiguration.class) - .withPropertyValues("server.port:0"); + .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class, + JerseyServerMetricsAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class, MetricsAutoConfiguration.class)) + .withUserConfiguration(ResourceConfiguration.class).withPropertyValues("server.port:0"); @Test public void shouldOnlyBeActiveInWebApplicationContext() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ResourceConfigCustomizer.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ResourceConfigCustomizer.class)); } @Test public void shouldProvideAllNecessaryBeans() { - this.webContextRunner.run((context) -> assertThat(context) - .hasSingleBean(DefaultJerseyTagsProvider.class) + this.webContextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyTagsProvider.class) .hasSingleBean(ResourceConfigCustomizer.class)); } @Test public void shouldHonorExistingTagProvider() { - this.webContextRunner - .withUserConfiguration(CustomJerseyTagsProviderConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(CustomJerseyTagsProvider.class)); + this.webContextRunner.withUserConfiguration(CustomJerseyTagsProviderConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(CustomJerseyTagsProvider.class)); } @Test @@ -99,17 +90,14 @@ public class JerseyServerMetricsAutoConfigurationTests { this.webContextRunner.run((context) -> { doRequest(context); MeterRegistry registry = context.getBean(MeterRegistry.class); - Timer timer = registry.get("http.server.requests").tag("uri", "/users/{id}") - .timer(); + Timer timer = registry.get("http.server.requests").tag("uri", "/users/{id}").timer(); assertThat(timer.count()).isEqualTo(1); }); } @Test public void noHttpRequestsTimedWhenJerseyInstrumentationMissingFromClasspath() { - this.webContextRunner - .withClassLoader( - new FilteredClassLoader(MetricsApplicationEventListener.class)) + this.webContextRunner.withClassLoader(new FilteredClassLoader(MetricsApplicationEventListener.class)) .run((context) -> { doRequest(context); @@ -119,13 +107,10 @@ public class JerseyServerMetricsAutoConfigurationTests { } private static void doRequest(AssertableWebApplicationContext context) { - int port = context - .getSourceApplicationContext( - AnnotationConfigServletWebServerApplicationContext.class) + int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) .getWebServer().getPort(); RestTemplate restTemplate = new RestTemplate(); - restTemplate.getForEntity(URI.create("http://localhost:" + port + "/users/3"), - String.class); + restTemplate.getForEntity(URI.create("http://localhost:" + port + "/users/3"), String.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java index f210a8e23fc..1dda84788a7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java @@ -58,33 +58,25 @@ import static org.mockito.Mockito.mock; */ public class HibernateMetricsAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()) + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - HibernateMetricsAutoConfiguration.class)) + HibernateJpaAutoConfiguration.class, HibernateMetricsAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class); @Test public void autoConfiguredEntityManagerFactoryWithStatsIsInstrumented() { - this.contextRunner - .withPropertyValues( - "spring.jpa.properties.hibernate.generate_statistics:true") + this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements") - .tags("entityManagerFactory", "entityManagerFactory").meter(); + registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); }); } @Test public void autoConfiguredEntityManagerFactoryWithoutStatsIsNotInstrumented() { - this.contextRunner - .withPropertyValues( - "spring.jpa.properties.hibernate.generate_statistics:false") + this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:false") .run((context) -> { - context.getBean(EntityManagerFactory.class) - .unwrap(SessionFactory.class); + context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("hibernate.statements").meter()).isNull(); }); @@ -92,12 +84,9 @@ public class HibernateMetricsAutoConfigurationTests { @Test public void entityManagerFactoryInstrumentationCanBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.enable.hibernate=false", - "spring.jpa.properties.hibernate.generate_statistics:true") - .run((context) -> { - context.getBean(EntityManagerFactory.class) - .unwrap(SessionFactory.class); + this.contextRunner.withPropertyValues("management.metrics.enable.hibernate=false", + "spring.jpa.properties.hibernate.generate_statistics:true").run((context) -> { + context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("hibernate.statements").meter()).isNull(); }); @@ -105,35 +94,24 @@ public class HibernateMetricsAutoConfigurationTests { @Test public void allEntityManagerFactoriesCanBeInstrumented() { - this.contextRunner - .withPropertyValues( - "spring.jpa.properties.hibernate.generate_statistics:true") - .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class) - .run((context) -> { - context.getBean("firstEntityManagerFactory", - EntityManagerFactory.class).unwrap(SessionFactory.class); - context.getBean("secondOne", EntityManagerFactory.class) + this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") + .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class).run((context) -> { + context.getBean("firstEntityManagerFactory", EntityManagerFactory.class) .unwrap(SessionFactory.class); + context.getBean("secondOne", EntityManagerFactory.class).unwrap(SessionFactory.class); MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements") - .tags("entityManagerFactory", "first").meter(); - registry.get("hibernate.statements") - .tags("entityManagerFactory", "secondOne").meter(); + registry.get("hibernate.statements").tags("entityManagerFactory", "first").meter(); + registry.get("hibernate.statements").tags("entityManagerFactory", "secondOne").meter(); }); } @Test public void entityManagerFactoryInstrumentationIsDisabledIfNotHibernateSessionFactory() { - this.contextRunner - .withPropertyValues( - "spring.jpa.properties.hibernate.generate_statistics:true") - .withUserConfiguration( - NonHibernateEntityManagerFactoryConfiguration.class) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") + .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { // ensure EntityManagerFactory is not a Hibernate SessionFactory - assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class) - .unwrap(SessionFactory.class)) - .isInstanceOf(PersistenceException.class); + assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class)) + .isInstanceOf(PersistenceException.class); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("hibernate.statements").meter()).isNull(); }); @@ -142,11 +120,8 @@ public class HibernateMetricsAutoConfigurationTests { @Test public void entityManagerFactoryInstrumentationIsDisabledIfHibernateIsNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader(SessionFactory.class)) - .withUserConfiguration( - NonHibernateEntityManagerFactoryConfiguration.class) - .run((context) -> { - assertThat(context) - .doesNotHaveBean(HibernateMetricsAutoConfiguration.class); + .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean(HibernateMetricsAutoConfiguration.class); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("hibernate.statements").meter()).isNull(); }); @@ -174,13 +149,11 @@ public class HibernateMetricsAutoConfigurationTests { @Configuration(proxyBeanMethods = false) static class TwoEntityManagerFactoriesConfiguration { - private static final Class[] PACKAGE_CLASSES = new Class[] { - MyEntity.class }; + private static final Class[] PACKAGE_CLASSES = new Class[] { MyEntity.class }; @Primary @Bean - public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory( - DataSource ds) { + public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory(DataSource ds) { return createSessionFactory(ds); } @@ -189,12 +162,11 @@ public class HibernateMetricsAutoConfigurationTests { return createSessionFactory(ds); } - private LocalContainerEntityManagerFactoryBean createSessionFactory( - DataSource ds) { + private LocalContainerEntityManagerFactoryBean createSessionFactory(DataSource ds) { Map jpaProperties = new HashMap<>(); jpaProperties.put("hibernate.generate_statistics", "true"); - return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), - jpaProperties, null).dataSource(ds).packages(PACKAGE_CLASSES).build(); + return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), jpaProperties, null).dataSource(ds) + .packages(PACKAGE_CLASSES).build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java index e98552b7ebf..5685be8ce79 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java @@ -81,8 +81,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Jon Schneider */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - classes = MetricsIntegrationTests.MetricsApp.class, +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = MetricsIntegrationTests.MetricsApp.class, properties = "management.metrics.use-global-registry=false") public class MetricsIntegrationTests { @@ -101,29 +100,23 @@ public class MetricsIntegrationTests { @SuppressWarnings("unchecked") @Test public void restTemplateIsInstrumented() { - MockRestServiceServer server = MockRestServiceServer.bindTo(this.external) - .build(); - server.expect(once(), requestTo("/api/external")) - .andExpect(method(HttpMethod.GET)).andRespond(withSuccess( - "{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); - assertThat(this.external.getForObject("/api/external", Map.class)) - .containsKey("message"); - assertThat(this.registry.get("http.client.requests").timer().count()) - .isEqualTo(1); + MockRestServiceServer server = MockRestServiceServer.bindTo(this.external).build(); + server.expect(once(), requestTo("/api/external")).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess("{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); + assertThat(this.external.getForObject("/api/external", Map.class)).containsKey("message"); + assertThat(this.registry.get("http.client.requests").timer().count()).isEqualTo(1); } @Test public void requestMappingIsInstrumented() { this.loopback.getForObject("/api/people", Set.class); - assertThat(this.registry.get("http.server.requests").timer().count()) - .isEqualTo(1); + assertThat(this.registry.get("http.server.requests").timer().count()).isEqualTo(1); } @Test public void automaticallyRegisteredBinders() { assertThat(this.context.getBeansOfType(MeterBinder.class).values()) - .hasAtLeastOneElementOfType(LogbackMetrics.class) - .hasAtLeastOneElementOfType(JvmMemoryMetrics.class); + .hasAtLeastOneElementOfType(LogbackMetrics.class).hasAtLeastOneElementOfType(JvmMemoryMetrics.class); } @Test @@ -132,26 +125,21 @@ public class MetricsIntegrationTests { Map filterRegistrations = this.context .getBeansOfType(FilterRegistrationBean.class); assertThat(filterRegistrations).containsKey("webMvcMetricsFilter"); - FilterRegistrationBean registration = filterRegistrations - .get("webMvcMetricsFilter"); + FilterRegistrationBean registration = filterRegistrations.get("webMvcMetricsFilter"); assertThat(registration.getFilter()).isInstanceOf(WebMvcMetricsFilter.class); - assertThat((Set) ReflectionTestUtils.getField(registration, - "dispatcherTypes")).containsExactlyInAnyOrder(DispatcherType.REQUEST, - DispatcherType.ASYNC); + assertThat((Set) ReflectionTestUtils.getField(registration, "dispatcherTypes")) + .containsExactlyInAnyOrder(DispatcherType.REQUEST, DispatcherType.ASYNC); } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ MetricsAutoConfiguration.class, - JvmMetricsAutoConfiguration.class, LogbackMetricsAutoConfiguration.class, - SystemMetricsAutoConfiguration.class, RabbitMetricsAutoConfiguration.class, - CacheMetricsAutoConfiguration.class, - DataSourcePoolMetricsAutoConfiguration.class, - HibernateMetricsAutoConfiguration.class, - HttpClientMetricsAutoConfiguration.class, - WebFluxMetricsAutoConfiguration.class, WebMvcMetricsAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - RestTemplateAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, + @ImportAutoConfiguration({ MetricsAutoConfiguration.class, JvmMetricsAutoConfiguration.class, + LogbackMetricsAutoConfiguration.class, SystemMetricsAutoConfiguration.class, + RabbitMetricsAutoConfiguration.class, CacheMetricsAutoConfiguration.class, + DataSourcePoolMetricsAutoConfiguration.class, HibernateMetricsAutoConfiguration.class, + HttpClientMetricsAutoConfiguration.class, WebFluxMetricsAutoConfiguration.class, + WebMvcMetricsAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, RestTemplateAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class }) @Import(PersonController.class) static class MetricsApp { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java index 117e83a927e..a2a50519e67 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,7 @@ public final class MetricsRun { EXPORT_AUTO_CONFIGURATIONS = Collections.unmodifiableSet(implementations); } - private static final AutoConfigurations AUTO_CONFIGURATIONS = AutoConfigurations.of( - MetricsAutoConfiguration.class, + private static final AutoConfigurations AUTO_CONFIGURATIONS = AutoConfigurations.of(MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class); private MetricsRun() { @@ -94,14 +93,13 @@ public final class MetricsRun { } @SuppressWarnings("unchecked") - private static > T apply( - T contextRunner, Class[] exportAutoConfigurations) { + private static > T apply(T contextRunner, + Class[] exportAutoConfigurations) { for (Class configuration : exportAutoConfigurations) { Assert.state(EXPORT_AUTO_CONFIGURATIONS.contains(configuration), () -> "Unknown export auto-configuration " + configuration.getName()); } - return (T) contextRunner - .withPropertyValues("management.metrics.use-global-registry=false") + return (T) contextRunner.withPropertyValues("management.metrics.use-global-registry=false") .withConfiguration(AUTO_CONFIGURATIONS) .withConfiguration(AutoConfigurations.of(exportAutoConfigurations)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java index b3991f812ef..18699e119cd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java @@ -50,8 +50,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat @ExtendWith(OutputCaptureExtension.class) public class RestTemplateMetricsConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()) + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); @@ -77,60 +76,48 @@ public class RestTemplateMetricsConfigurationTests { @Test public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { - this.contextRunner - .withPropertyValues("management.metrics.web.client.max-uri-tags=2") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.client.requests").meters()).hasSize(2); - assertThat(capturedOutput).contains( - "Reached the maximum number of URI tags for 'http.client.requests'.") - .contains("Are you using 'uriVariables'?"); - }); + this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.client.requests").meters()).hasSize(2); + assertThat(capturedOutput).contains("Reached the maximum number of URI tags for 'http.client.requests'.") + .contains("Are you using 'uriVariables'?"); + }); } @Test public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { - this.contextRunner - .withPropertyValues("management.metrics.web.client.max-uri-tags=5") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.client.requests").meters()).hasSize(3); - assertThat(capturedOutput).doesNotContain( - "Reached the maximum number of URI tags for 'http.client.requests'.") - .doesNotContain("Are you using 'uriVariables'?"); - }); + this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.client.requests").meters()).hasSize(3); + assertThat(capturedOutput) + .doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") + .doesNotContain("Are you using 'uriVariables'?"); + }); } @Test public void autoTimeRequestsCanBeConfigured() { - this.contextRunner.withPropertyValues( - "management.metrics.web.client.request.autotime.enabled=true", + this.contextRunner.withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", - "management.metrics.web.client.request.autotime.percentiles-histogram=true") - .run((context) -> { + "management.metrics.web.client.request.autotime.percentiles-histogram=true").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); Timer timer = registry.get("http.client.requests").timer(); HistogramSnapshot snapshot = timer.takeSnapshot(); assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()) - .isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()) - .isEqualTo(0.7); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); }); } @Test public void backsOffWhenRestTemplateBuilderIsMissing() { new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(HttpClientMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) + .withConfiguration(AutoConfigurations.of(HttpClientMetricsAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) .doesNotHaveBean(MetricsRestTemplateCustomizer.class)); } - private MeterRegistry getInitializedMeterRegistry( - AssertableApplicationContext context) { + private MeterRegistry getInitializedMeterRegistry(AssertableApplicationContext context) { MeterRegistry registry = context.getBean(MeterRegistry.class); RestTemplate restTemplate = context.getBean(RestTemplateBuilder.class).build(); MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); @@ -143,22 +130,18 @@ public class RestTemplateMetricsConfigurationTests { return registry; } - private void validateRestTemplate(RestTemplateBuilder builder, - MeterRegistry registry) { + private void validateRestTemplate(RestTemplateBuilder builder, MeterRegistry registry) { RestTemplate restTemplate = mockRestTemplate(builder); assertThat(registry.find("http.client.requests").meter()).isNull(); - assertThat(restTemplate - .getForEntity("/projects/{project}", Void.class, "spring-boot") - .getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(registry.get("http.client.requests").tags("uri", "/projects/{project}") - .meter()).isNotNull(); + assertThat(restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot").getStatusCode()) + .isEqualTo(HttpStatus.OK); + assertThat(registry.get("http.client.requests").tags("uri", "/projects/{project}").meter()).isNotNull(); } private RestTemplate mockRestTemplate(RestTemplateBuilder builder) { RestTemplate restTemplate = builder.build(); MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); - server.expect(requestTo("/projects/spring-boot")) - .andRespond(withStatus(HttpStatus.OK)); + server.expect(requestTo("/projects/spring-boot")).andRespond(withStatus(HttpStatus.OK)); return restTemplate; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java index e5ca1169ad2..c0ce0b7c067 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java @@ -54,10 +54,9 @@ import static org.mockito.Mockito.mock; @ExtendWith(OutputCaptureExtension.class) public class WebClientMetricsConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(WebClientAutoConfiguration.class, - HttpClientMetricsAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration( + AutoConfigurations.of(WebClientAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); @Test public void webClientCreatedWithBuilderIsInstrumented() { @@ -70,63 +69,50 @@ public class WebClientMetricsConfigurationTests { @Test public void shouldNotOverrideCustomTagsProvider() { - this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class) - .run((context) -> assertThat(context) - .getBeans(WebClientExchangeTagsProvider.class).hasSize(1) - .containsKey("customTagsProvider")); + this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class).run((context) -> assertThat(context) + .getBeans(WebClientExchangeTagsProvider.class).hasSize(1).containsKey("customTagsProvider")); } @Test public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { - this.contextRunner - .withPropertyValues("management.metrics.web.client.max-uri-tags=2") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.client.requests").meters()).hasSize(2); - assertThat(capturedOutput).contains( - "Reached the maximum number of URI tags for 'http.client.requests'.") - .contains("Are you using 'uriVariables'?"); - }); + this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.client.requests").meters()).hasSize(2); + assertThat(capturedOutput).contains("Reached the maximum number of URI tags for 'http.client.requests'.") + .contains("Are you using 'uriVariables'?"); + }); } @Test public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { - this.contextRunner - .withPropertyValues("management.metrics.web.client.max-uri-tags=5") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.client.requests").meters()).hasSize(3); - assertThat(capturedOutput).doesNotContain( - "Reached the maximum number of URI tags for 'http.client.requests'.") - .doesNotContain("Are you using 'uriVariables'?"); - }); + this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.client.requests").meters()).hasSize(3); + assertThat(capturedOutput) + .doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") + .doesNotContain("Are you using 'uriVariables'?"); + }); } @Test public void autoTimeRequestsCanBeConfigured() { - this.contextRunner.withPropertyValues( - "management.metrics.web.client.request.autotime.enabled=true", + this.contextRunner.withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", - "management.metrics.web.client.request.autotime.percentiles-histogram=true") - .run((context) -> { + "management.metrics.web.client.request.autotime.percentiles-histogram=true").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); Timer timer = registry.get("http.client.requests").timer(); HistogramSnapshot snapshot = timer.takeSnapshot(); assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()) - .isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()) - .isEqualTo(0.7); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); }); } - private MeterRegistry getInitializedMeterRegistry( - AssertableApplicationContext context) { + private MeterRegistry getInitializedMeterRegistry(AssertableApplicationContext context) { WebClient webClient = mockWebClient(context.getBean(WebClient.Builder.class)); MeterRegistry registry = context.getBean(MeterRegistry.class); for (int i = 0; i < 3; i++) { - webClient.get().uri("https://example.org/projects/" + i).exchange() - .block(Duration.ofSeconds(30)); + webClient.get().uri("https://example.org/projects/" + i).exchange().block(Duration.ofSeconds(30)); } return registry; } @@ -134,16 +120,14 @@ public class WebClientMetricsConfigurationTests { private void validateWebClient(WebClient.Builder builder, MeterRegistry registry) { WebClient webClient = mockWebClient(builder); assertThat(registry.find("http.client.requests").meter()).isNull(); - webClient.get().uri("https://example.org/projects/{project}", "spring-boot") - .exchange().block(Duration.ofSeconds(30)); - assertThat(registry.find("http.client.requests") - .tags("uri", "/projects/{project}").meter()).isNotNull(); + webClient.get().uri("https://example.org/projects/{project}", "spring-boot").exchange() + .block(Duration.ofSeconds(30)); + assertThat(registry.find("http.client.requests").tags("uri", "/projects/{project}").meter()).isNotNull(); } private WebClient mockWebClient(WebClient.Builder builder) { ClientHttpConnector connector = mock(ClientHttpConnector.class); - given(connector.connect(any(), any(), any())) - .willReturn(Mono.just(new MockClientHttpResponse(HttpStatus.OK))); + given(connector.connect(any(), any(), any())).willReturn(Mono.just(new MockClientHttpResponse(HttpStatus.OK))); return builder.clientConnector(connector).build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java index 86e7603c449..04db0852313 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java @@ -48,55 +48,38 @@ public class JettyMetricsAutoConfigurationTests { @Test public void autoConfiguresThreadPoolMetricsWithEmbeddedServletJetty() { - new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, - MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent( - new ApplicationStartedEvent(new SpringApplication(), - null, context.getSourceApplicationContext())); - assertThat(context).hasSingleBean( - JettyServerThreadPoolMetricsBinder.class); - SimpleMeterRegistry registry = context - .getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.threads.config.min").meter()) - .isNotNull(); - }); + new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, + context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); + }); } @Test public void autoConfiguresThreadPoolMetricsWithEmbeddedReactiveJetty() { - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, - MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent( - new ApplicationStartedEvent(new SpringApplication(), - null, context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context - .getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.threads.config.min").meter()) - .isNotNull(); - }); + new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, + context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); + }); } @Test public void allowsCustomJettyServerThreadPoolMetricsBinderToBeUsed() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) - .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, - MeterRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(JettyServerThreadPoolMetricsBinder.class) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) + .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class) .hasBean("customJettyServerThreadPoolMetricsBinder")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java index 49e919c5740..d3d90bcb5f7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java @@ -48,8 +48,7 @@ import static org.mockito.Mockito.mock; public class WebFluxMetricsAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(WebFluxMetricsAutoConfiguration.class)); + .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(WebFluxMetricsAutoConfiguration.class)); @Test public void shouldProvideWebFluxMetricsBeans() { @@ -62,47 +61,39 @@ public class WebFluxMetricsAutoConfigurationTests { @Test public void shouldNotOverrideCustomTagsProvider() { this.contextRunner.withUserConfiguration(CustomWebFluxTagsProviderConfig.class) - .run((context) -> assertThat(context).getBeans(WebFluxTagsProvider.class) - .hasSize(1).containsKey("customWebFluxTagsProvider")); + .run((context) -> assertThat(context).getBeans(WebFluxTagsProvider.class).hasSize(1) + .containsKey("customWebFluxTagsProvider")); } @Test public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { - this.contextRunner - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2") - .run((context) -> { + .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.server.requests").meters()).hasSize(2); assertThat(capturedOutput) - .contains("Reached the maximum number of URI tags " - + "for 'http.server.requests'"); + .contains("Reached the maximum number of URI tags " + "for 'http.server.requests'"); }); } @Test public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { - this.contextRunner - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5") - .run((context) -> { + .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.server.requests").meters()).hasSize(3); - assertThat(capturedOutput).doesNotContain( - "Reached the maximum number of URI tags for 'http.server.requests'"); + assertThat(capturedOutput) + .doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); }); } @Test public void metricsAreNotRecordedIfAutoTimeRequestsIsDisabled() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) - .withPropertyValues( - "management.metrics.web.server.request.autotime.enabled=false") - .run((context) -> { + .withPropertyValues("management.metrics.web.server.request.autotime.enabled=false").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.find("http.server.requests").meter()).isNull(); }); @@ -111,21 +102,16 @@ public class WebFluxMetricsAutoConfigurationTests { @Test @Deprecated public void metricsAreNotRecordedIfAutoTimeRequestsIsDisabledWithDeprecatedProperty() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) - .withPropertyValues( - "management.metrics.web.server.auto-time-requests=false") - .run((context) -> { + .withPropertyValues("management.metrics.web.server.auto-time-requests=false").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.find("http.server.requests").meter()).isNull(); }); } - private MeterRegistry getInitializedMeterRegistry( - AssertableReactiveWebApplicationContext context) { - WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context) - .build(); + private MeterRegistry getInitializedMeterRegistry(AssertableReactiveWebApplicationContext context) { + WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); for (int i = 0; i < 3; i++) { webTestClient.get().uri("/test" + i).exchange().expectStatus().isOk(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java index a72026551eb..f115035f308 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java @@ -66,17 +66,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ExtendWith(OutputCaptureExtension.class) public class WebMvcMetricsAutoConfigurationTests { - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); @Test public void backsOffWhenMeterRegistryIsMissing() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(WebMvcTagsProvider.class)); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(WebMvcTagsProvider.class)); } @Test @@ -91,18 +87,16 @@ public class WebMvcMetricsAutoConfigurationTests { @Test public void tagsProviderBacksOff() { - this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(DefaultWebMvcTagsProvider.class); - assertThat(context).hasSingleBean(TestWebMvcTagsProvider.class); - }); + this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean(DefaultWebMvcTagsProvider.class); + assertThat(context).hasSingleBean(TestWebMvcTagsProvider.class); + }); } @Test public void filterRegistrationHasExpectedDispatcherTypesAndOrder() { this.contextRunner.run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC)); assertThat(registration.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1); @@ -112,40 +106,32 @@ public class WebMvcMetricsAutoConfigurationTests { @Test public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2") - .run((context) -> { + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.server.requests").meters()).hasSize(2); assertThat(capturedOutput) - .contains("Reached the maximum number of URI tags " - + "for 'http.server.requests'"); + .contains("Reached the maximum number of URI tags " + "for 'http.server.requests'"); }); } @Test public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5") - .run((context) -> { + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.server.requests").meters()).hasSize(3); assertThat(capturedOutput) - .doesNotContain("Reached the maximum number of URI tags " - + "for 'http.server.requests'"); + .doesNotContain("Reached the maximum number of URI tags " + "for 'http.server.requests'"); }); } @Test public void autoTimeRequestsCanBeConfigured() { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - WebMvcAutoConfiguration.class)) - .withPropertyValues( - "management.metrics.web.server.request.autotime.enabled=true", + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.request.autotime.enabled=true", "management.metrics.web.server.request.autotime.percentiles=0.5,0.7", "management.metrics.web.server.request.autotime.percentiles-histogram=true") .run((context) -> { @@ -153,10 +139,8 @@ public class WebMvcMetricsAutoConfigurationTests { Timer timer = registry.get("http.server.requests").timer(); HistogramSnapshot snapshot = timer.takeSnapshot(); assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()) - .isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()) - .isEqualTo(0.7); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); }); } @@ -164,25 +148,19 @@ public class WebMvcMetricsAutoConfigurationTests { @SuppressWarnings("rawtypes") public void longTaskTimingInterceptorIsRegistered() { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - WebMvcAutoConfiguration.class)) - .run((context) -> assertThat( - context.getBean(RequestMappingHandlerMapping.class)) - .extracting("interceptors").element(0).asList() - .extracting((item) -> (Class) item.getClass()) - .contains(LongTaskTimingHandlerInterceptor.class)); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(RequestMappingHandlerMapping.class)) + .extracting("interceptors").element(0).asList().extracting((item) -> (Class) item.getClass()) + .contains(LongTaskTimingHandlerInterceptor.class)); } - private MeterRegistry getInitializedMeterRegistry( - AssertableWebApplicationContext context) throws Exception { + private MeterRegistry getInitializedMeterRegistry(AssertableWebApplicationContext context) throws Exception { assertThat(context).hasSingleBean(FilterRegistrationBean.class); Filter filter = context.getBean(FilterRegistrationBean.class).getFilter(); assertThat(filter).isInstanceOf(WebMvcMetricsFilter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(filter) - .build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(filter).build(); for (int i = 0; i < 3; i++) { - mockMvc.perform(MockMvcRequestBuilders.get("/test" + i)) - .andExpect(status().isOk()); + mockMvc.perform(MockMvcRequestBuilders.get("/test" + i)).andExpect(status().isOk()); } return context.getBean(MeterRegistry.class); } @@ -200,14 +178,13 @@ public class WebMvcMetricsAutoConfigurationTests { private static final class TestWebMvcTagsProvider implements WebMvcTagsProvider { @Override - public Iterable getTags(HttpServletRequest request, - HttpServletResponse response, Object handler, Throwable exception) { + public Iterable getTags(HttpServletRequest request, HttpServletResponse response, Object handler, + Throwable exception) { return Collections.emptyList(); } @Override - public Iterable getLongRequestTags(HttpServletRequest request, - Object handler) { + public Iterable getLongRequestTags(HttpServletRequest request, Object handler) { return Collections.emptyList(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java index 56e9b5dd347..ef568e8dde9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java @@ -56,92 +56,63 @@ public class TomcatMetricsAutoConfigurationTests { @Test public void autoConfiguresTomcatMetricsWithEmbeddedServletTomcat() { resetTomcatState(); - new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of( - TomcatMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, - MeterRegistryConfiguration.class) - .withPropertyValues("server.tomcat.mbeanregistry.enabled=true") - .run((context) -> { - context.publishEvent( - new ApplicationStartedEvent(new SpringApplication(), - null, context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(TomcatMetricsBinder.class); - SimpleMeterRegistry registry = context - .getBean(SimpleMeterRegistry.class); - assertThat( - registry.find("tomcat.sessions.active.max").meter()) - .isNotNull(); - assertThat(registry.find("tomcat.threads.current").meter()) - .isNotNull(); - }); + new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.tomcat.mbeanregistry.enabled=true").run((context) -> { + context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, + context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(TomcatMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test public void autoConfiguresTomcatMetricsWithEmbeddedReactiveTomcat() { resetTomcatState(); - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of( - TomcatMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, - MeterRegistryConfiguration.class) - .withPropertyValues("server.tomcat.mbeanregistry.enabled=true") - .run((context) -> { - context.publishEvent( - new ApplicationStartedEvent(new SpringApplication(), - null, context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context - .getBean(SimpleMeterRegistry.class); - assertThat( - registry.find("tomcat.sessions.active.max").meter()) - .isNotNull(); - assertThat(registry.find("tomcat.threads.current").meter()) - .isNotNull(); - }); + new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.tomcat.mbeanregistry.enabled=true").run((context) -> { + context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, + context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test public void autoConfiguresTomcatMetricsWithStandaloneTomcat() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) .withUserConfiguration(MeterRegistryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(TomcatMetricsBinder.class)); + .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class)); } @Test public void allowsCustomTomcatMetricsBinderToBeUsed() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class, - CustomTomcatMetricsBinder.class) - .run((context) -> assertThat(context) - .hasSingleBean(TomcatMetricsBinder.class) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) + .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetricsBinder.class) + .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class) .hasBean("customTomcatMetricsBinder")); } @Test public void allowsCustomTomcatMetricsToBeUsed() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class, - CustomTomcatMetrics.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(TomcatMetricsBinder.class) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) + .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetrics.class) + .run((context) -> assertThat(context).doesNotHaveBean(TomcatMetricsBinder.class) .hasBean("customTomcatMetrics")); } private void resetTomcatState() { ReflectionTestUtils.setField(Registry.class, "registry", null); - AtomicInteger containerCounter = (AtomicInteger) ReflectionTestUtils - .getField(TomcatWebServer.class, "containerCounter"); + AtomicInteger containerCounter = (AtomicInteger) ReflectionTestUtils.getField(TomcatWebServer.class, + "containerCounter"); containerCounter.set(-1); } @@ -194,8 +165,7 @@ public class TomcatMetricsAutoConfigurationTests { static class CustomTomcatMetricsBinder { @Bean - public TomcatMetricsBinder customTomcatMetricsBinder( - MeterRegistry meterRegistry) { + public TomcatMetricsBinder customTomcatMetricsBinder(MeterRegistry meterRegistry) { return new TomcatMetricsBinder(meterRegistry); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java index 2ee1a44ad66..d007c67a0c6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java @@ -36,23 +36,19 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(MongoHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoHealthIndicator.class) + .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(MongoHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(MongoHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java index f6c153fce09..bc8c4a74e91 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java @@ -39,28 +39,21 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, - MongoReactiveHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(MongoReactiveHealthIndicator.class) - .doesNotHaveBean(MongoHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) + .doesNotHaveBean(MongoHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(MongoReactiveHealthIndicator.class) - .doesNotHaveBean(MongoHealthIndicator.class) - .hasSingleBean(ApplicationHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) + .doesNotHaveBean(MongoHealthIndicator.class).hasSingleBean(ApplicationHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java index b8008990f2f..85a6b09f041 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java @@ -42,34 +42,30 @@ import static org.mockito.Mockito.mock; public class Neo4jHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Neo4jConfiguration.class).withConfiguration( - AutoConfigurations.of(Neo4jHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withUserConfiguration(Neo4jConfiguration.class).withConfiguration(AutoConfigurations + .of(Neo4jHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(Neo4jHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Neo4jHealthIndicator.class) + .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.neo4j.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(Neo4jHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } @Test public void defaultIndicatorCanBeReplaced() { - this.contextRunner.withUserConfiguration(CustomIndicatorConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Neo4jHealthIndicator.class); - assertThat(context).doesNotHaveBean(ApplicationHealthIndicator.class); - Health health = context.getBean(Neo4jHealthIndicator.class).health(); - assertThat(health.getDetails()).containsOnly(entry("test", true)); - }); + this.contextRunner.withUserConfiguration(CustomIndicatorConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(Neo4jHealthIndicator.class); + assertThat(context).doesNotHaveBean(ApplicationHealthIndicator.class); + Health health = context.getBean(Neo4jHealthIndicator.class).health(); + assertThat(health.getDetails()).containsOnly(entry("test", true)); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java index 9874ac46fdc..56694f741da 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,22 +42,18 @@ public class RedisHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + RedisHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(RedisHealthIndicator.class) - .doesNotHaveBean(RedisReactiveHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RedisHealthIndicator.class) + .doesNotHaveBean(RedisReactiveHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(RedisHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(RedisHealthIndicator.class) .doesNotHaveBean(RedisReactiveHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java index 3c66691c8e6..eec9a8872b0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java @@ -37,24 +37,20 @@ public class RedisReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + RedisReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(RedisReactiveHealthIndicatorAutoConfiguration.class) - .doesNotHaveBean(RedisHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicatorAutoConfiguration.class) + .doesNotHaveBean(RedisHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(RedisReactiveHealthIndicator.class) - .doesNotHaveBean(RedisHealthIndicator.class) - .hasSingleBean(ApplicationHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RedisReactiveHealthIndicator.class) + .doesNotHaveBean(RedisHealthIndicator.class).hasSingleBean(ApplicationHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java index 42688735cd9..9e4eb761ed1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java @@ -36,38 +36,29 @@ import static org.assertj.core.api.Assertions.assertThat; public class ScheduledTasksEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); @Test public void endpointIsAutoConfigured() { - this.contextRunner - .withPropertyValues( - "management.endpoints.web.exposure.include=scheduledtasks") - .run((context) -> assertThat(context) - .hasSingleBean(ScheduledTasksEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=scheduledtasks") + .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class)); } @Test public void endpointNotAutoConfiguredWhenNotExposed() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ScheduledTasksEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); } @Test public void endpointCanBeDisabled() { - this.contextRunner - .withPropertyValues("management.endpoint.scheduledtasks.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ScheduledTasksEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.scheduledtasks.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); } @Test public void endpointBacksOffWhenUserProvidedEndpointIsPresent() { - this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ScheduledTasksEndpoint.class) - .hasBean("customEndpoint")); + this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class).run( + (context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class).hasBean("customEndpoint")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java index 7d8503a0793..449718e1340 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java @@ -128,14 +128,13 @@ public class EndpointRequestTests { @Test public void excludeByClassShouldNotMatchExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() - .excluding(FooEndpoint.class, BazServletEndpoint.class); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, + BazServletEndpoint.class); List> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); endpoints.add(mockEndpoint(EndpointId.of("bar"), "bar")); endpoints.add(mockEndpoint(EndpointId.of("baz"), "baz")); - PathMappedEndpoints pathMappedEndpoints = new PathMappedEndpoints("/actuator", - () -> endpoints); + PathMappedEndpoints pathMappedEndpoints = new PathMappedEndpoints("/actuator", () -> endpoints); assertMatcher(matcher, pathMappedEndpoints).doesNotMatch("/actuator/foo"); assertMatcher(matcher, pathMappedEndpoints).doesNotMatch("/actuator/baz"); assertMatcher(matcher).matches("/actuator/bar"); @@ -144,16 +143,15 @@ public class EndpointRequestTests { @Test public void excludeByClassShouldNotMatchLinksIfExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() - .excludingLinks().excluding(FooEndpoint.class); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks() + .excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test public void excludeByIdShouldNotMatchExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() - .excluding("foo"); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); assertMatcher(matcher).matches("/actuator"); @@ -161,16 +159,14 @@ public class EndpointRequestTests { @Test public void excludeByIdShouldNotMatchLinksIfExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() - .excludingLinks().excluding("foo"); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test public void excludeLinksShouldNotMatchBasePath() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() - .excludingLinks(); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); assertMatcher(matcher).doesNotMatch("/actuator"); assertMatcher(matcher).matches("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); @@ -178,8 +174,7 @@ public class EndpointRequestTests { @Test public void excludeLinksShouldNotMatchBasePathIfEmptyAndExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() - .excludingLinks(); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); assertMatcher.matches("/foo"); @@ -197,8 +192,7 @@ public class EndpointRequestTests { return assertMatcher(matcher, mockPathMappedEndpoints("/actuator")); } - private RequestMatcherAssert assertMatcher(ServerWebExchangeMatcher matcher, - String basePath) { + private RequestMatcherAssert assertMatcher(ServerWebExchangeMatcher matcher, String basePath) { return assertMatcher(matcher, mockPathMappedEndpoints(basePath)); } @@ -222,8 +216,7 @@ public class EndpointRequestTests { context.registerBean(WebEndpointProperties.class); if (pathMappedEndpoints != null) { context.registerBean(PathMappedEndpoints.class, () -> pathMappedEndpoints); - WebEndpointProperties properties = context - .getBean(WebEndpointProperties.class); + WebEndpointProperties properties = context.getBean(WebEndpointProperties.class); if (!properties.getBasePath().equals(pathMappedEndpoints.getBasePath())) { properties.setBasePath(pathMappedEndpoints.getBasePath()); } @@ -237,40 +230,35 @@ public class EndpointRequestTests { private final ServerWebExchangeMatcher matcher; - RequestMatcherAssert(StaticApplicationContext context, - ServerWebExchangeMatcher matcher) { + RequestMatcherAssert(StaticApplicationContext context, ServerWebExchangeMatcher matcher) { this.context = context; this.matcher = matcher; } void matches(String path) { - ServerWebExchange exchange = webHandler().createExchange( - MockServerHttpRequest.get(path).build(), + ServerWebExchange exchange = webHandler().createExchange(MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); matches(exchange); } private void matches(ServerWebExchange exchange) { - assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)) - .isMatch()).as("Matches " + getRequestPath(exchange)).isTrue(); + assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) + .as("Matches " + getRequestPath(exchange)).isTrue(); } void doesNotMatch(String path) { - ServerWebExchange exchange = webHandler().createExchange( - MockServerHttpRequest.get(path).build(), + ServerWebExchange exchange = webHandler().createExchange(MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); doesNotMatch(exchange); } private void doesNotMatch(ServerWebExchange exchange) { - assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)) - .isMatch()).as("Does not match " + getRequestPath(exchange)) - .isFalse(); + assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) + .as("Does not match " + getRequestPath(exchange)).isFalse(); } private TestHttpWebHandlerAdapter webHandler() { - TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter( - mock(WebHandler.class)); + TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(mock(WebHandler.class)); adapter.setApplicationContext(this.context); return adapter; } @@ -288,8 +276,7 @@ public class EndpointRequestTests { } @Override - protected ServerWebExchange createExchange(ServerHttpRequest request, - ServerHttpResponse response) { + protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { return super.createExchange(request, response); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java index b183caafe07..b640a097112 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java @@ -65,108 +65,83 @@ import static org.mockito.Mockito.mock; public class ReactiveManagementWebSecurityAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, - InfoEndpointAutoConfiguration.class, - EnvironmentEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, - ReactiveManagementWebSecurityAutoConfiguration.class)); + .withConfiguration( + AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + InfoEndpointAutoConfiguration.class, EnvironmentEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class, ReactiveUserDetailsServiceAutoConfiguration.class, + ReactiveManagementWebSecurityAutoConfiguration.class)); @Test public void permitAllForHealth() { - this.contextRunner.run(( - context) -> assertThat(getAuthenticateHeader(context, "/actuator/health")) - .isNull()); + this.contextRunner.run((context) -> assertThat(getAuthenticateHeader(context, "/actuator/health")).isNull()); } @Test public void permitAllForInfo() { - this.contextRunner.run( - (context) -> assertThat(getAuthenticateHeader(context, "/actuator/info")) - .isNull()); + this.contextRunner.run((context) -> assertThat(getAuthenticateHeader(context, "/actuator/info")).isNull()); } @Test public void securesEverythingElse() { this.contextRunner.run((context) -> { - assertThat(getAuthenticateHeader(context, "/actuator").get(0)) - .contains("Basic realm="); - assertThat(getAuthenticateHeader(context, "/foo").toString()) - .contains("Basic realm="); + assertThat(getAuthenticateHeader(context, "/actuator").get(0)).contains("Basic realm="); + assertThat(getAuthenticateHeader(context, "/foo").toString()).contains("Basic realm="); }); } @Test public void usesMatchersBasedOffConfiguredActuatorBasePath() { - this.contextRunner.withPropertyValues("management.endpoints.web.base-path=/") - .run((context) -> { - assertThat(getAuthenticateHeader(context, "/health")).isNull(); - assertThat(getAuthenticateHeader(context, "/foo").get(0)) - .contains("Basic realm="); - }); + this.contextRunner.withPropertyValues("management.endpoints.web.base-path=/").run((context) -> { + assertThat(getAuthenticateHeader(context, "/health")).isNull(); + assertThat(getAuthenticateHeader(context, "/foo").get(0)).contains("Basic realm="); + }); } @Test public void backsOffIfCustomSecurityIsAdded() { - this.contextRunner.withUserConfiguration(CustomSecurityConfiguration.class) - .run((context) -> { - assertThat(getLocationHeader(context, "/actuator/health").toString()) - .contains("/login"); - assertThat(getLocationHeader(context, "/foo")).isNull(); - }); + this.contextRunner.withUserConfiguration(CustomSecurityConfiguration.class).run((context) -> { + assertThat(getLocationHeader(context, "/actuator/health").toString()).contains("/login"); + assertThat(getLocationHeader(context, "/foo")).isNull(); + }); } @Test public void backOffIfReactiveOAuth2ResourceServerAutoConfigurationPresent() { - this.contextRunner - .withConfiguration(AutoConfigurations - .of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") - .run((context) -> assertThat(context).doesNotHaveBean( - ReactiveManagementWebSecurityAutoConfiguration.class)); + this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") + .run((context) -> assertThat(context) + .doesNotHaveBean(ReactiveManagementWebSecurityAutoConfiguration.class)); } @Test public void backsOffWhenWebFilterChainProxyBeanPresent() { - this.contextRunner.withUserConfiguration(WebFilterChainProxyConfiguration.class) - .run((context) -> { - assertThat(getLocationHeader(context, "/actuator/health").toString()) - .contains("/login"); - assertThat(getLocationHeader(context, "/foo").toString()) - .contains("/login"); - }); + this.contextRunner.withUserConfiguration(WebFilterChainProxyConfiguration.class).run((context) -> { + assertThat(getLocationHeader(context, "/actuator/health").toString()).contains("/login"); + assertThat(getLocationHeader(context, "/foo").toString()).contains("/login"); + }); } - private List getAuthenticateHeader( - AssertableReactiveWebApplicationContext context, String path) { + private List getAuthenticateHeader(AssertableReactiveWebApplicationContext context, String path) { ServerWebExchange exchange = performFilter(context, path); return exchange.getResponse().getHeaders().get(HttpHeaders.WWW_AUTHENTICATE); } - private ServerWebExchange performFilter( - AssertableReactiveWebApplicationContext context, String path) { - ServerWebExchange exchange = webHandler(context).createExchange( - MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); + private ServerWebExchange performFilter(AssertableReactiveWebApplicationContext context, String path) { + ServerWebExchange exchange = webHandler(context).createExchange(MockServerHttpRequest.get(path).build(), + new MockServerHttpResponse()); WebFilterChainProxy proxy = context.getBean(WebFilterChainProxy.class); - proxy.filter(exchange, (serverWebExchange) -> Mono.empty()) - .block(Duration.ofSeconds(30)); + proxy.filter(exchange, (serverWebExchange) -> Mono.empty()).block(Duration.ofSeconds(30)); return exchange; } - private URI getLocationHeader(AssertableReactiveWebApplicationContext context, - String path) { + private URI getLocationHeader(AssertableReactiveWebApplicationContext context, String path) { ServerWebExchange exchange = performFilter(context, path); return exchange.getResponse().getHeaders().getLocation(); } - private TestHttpWebHandlerAdapter webHandler( - AssertableReactiveWebApplicationContext context) { - TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter( - mock(WebHandler.class)); + private TestHttpWebHandlerAdapter webHandler(AssertableReactiveWebApplicationContext context) { + TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(mock(WebHandler.class)); adapter.setApplicationContext(context); return adapter; } @@ -178,8 +153,7 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { } @Override - protected ServerWebExchange createExchange(ServerHttpRequest request, - ServerHttpResponse response) { + protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { return super.createExchange(request, response); } @@ -190,8 +164,8 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - return http.authorizeExchange().pathMatchers("/foo").permitAll().anyExchange() - .authenticated().and().formLogin().and().build(); + return http.authorizeExchange().pathMatchers("/foo").permitAll().anyExchange().authenticated().and() + .formLogin().and().build(); } } @@ -210,24 +184,21 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { } @Bean - public TestServerHttpSecurity http( - ReactiveAuthenticationManager authenticationManager) { + public TestServerHttpSecurity http(ReactiveAuthenticationManager authenticationManager) { TestServerHttpSecurity httpSecurity = new TestServerHttpSecurity(); httpSecurity.authenticationManager(authenticationManager); return httpSecurity; } private List getFilterChains(ServerHttpSecurity http) { - return Collections.singletonList(http.authorizeExchange().anyExchange() - .authenticated().and().formLogin().and().build()); + return Collections.singletonList( + http.authorizeExchange().anyExchange().authenticated().and().formLogin().and().build()); } - private static class TestServerHttpSecurity extends ServerHttpSecurity - implements ApplicationContextAware { + private static class TestServerHttpSecurity extends ServerHttpSecurity implements ApplicationContextAware { @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { super.setApplicationContext(applicationContext); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java index 14c9f687cff..5ae2c88a1fe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java @@ -61,16 +61,11 @@ public abstract class AbstractEndpointRequestIntegrationTests { @Test public void toAllEndpointsShouldMatch() { - getContextRunner() - .withInitializer( - new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) - .withPropertyValues("spring.security.user.password=password") - .run((context) -> { + getContextRunner().withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) + .withPropertyValues("spring.security.user.password=password").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/actuator/e2").exchange().expectStatus() - .isUnauthorized(); - webTestClient.get().uri("/actuator/e2") - .header("Authorization", getBasicAuth()).exchange() + webTestClient.get().uri("/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get().uri("/actuator/e2").header("Authorization", getBasicAuth()).exchange() .expectStatus().isOk(); }); } @@ -85,9 +80,7 @@ public abstract class AbstractEndpointRequestIntegrationTests { } protected WebTestClient getWebTestClient(AssertableWebApplicationContext context) { - int port = context - .getSourceApplicationContext( - AnnotationConfigServletWebServerApplicationContext.class) + int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) .getWebServer().getPort(); return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build(); } @@ -162,8 +155,7 @@ public abstract class AbstractEndpointRequestIntegrationTests { } - public interface TestPathMappedEndpoint - extends ExposableEndpoint, PathMappedEndpoint { + public interface TestPathMappedEndpoint extends ExposableEndpoint, PathMappedEndpoint { } @@ -175,12 +167,10 @@ public abstract class AbstractEndpointRequestIntegrationTests { return new WebSecurityConfigurerAdapter() { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().requestMatchers(EndpointRequest.toLinks()) - .permitAll() - .requestMatchers(EndpointRequest.to(TestEndpoint1.class)) - .permitAll().requestMatchers(EndpointRequest.toAnyEndpoint()) - .authenticated().anyRequest().hasRole("ADMIN").and() - .httpBasic(); + http.authorizeRequests().requestMatchers(EndpointRequest.toLinks()).permitAll() + .requestMatchers(EndpointRequest.to(TestEndpoint1.class)).permitAll() + .requestMatchers(EndpointRequest.toAnyEndpoint()).authenticated().anyRequest() + .hasRole("ADMIN").and().httpBasic(); } }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java index ed5225482d1..59585f61602 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java @@ -139,14 +139,12 @@ public class EndpointRequestTests { @Test public void excludeByClassShouldNotMatchExcluded() { - RequestMatcher matcher = EndpointRequest.toAnyEndpoint() - .excluding(FooEndpoint.class, BazServletEndpoint.class); + RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, BazServletEndpoint.class); List> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); endpoints.add(mockEndpoint(EndpointId.of("bar"), "bar")); endpoints.add(mockEndpoint(EndpointId.of("baz"), "baz")); - PathMappedEndpoints pathMappedEndpoints = new PathMappedEndpoints("/actuator", - () -> endpoints); + PathMappedEndpoints pathMappedEndpoints = new PathMappedEndpoints("/actuator", () -> endpoints); assertMatcher(matcher, pathMappedEndpoints).doesNotMatch("/actuator/foo"); assertMatcher(matcher, pathMappedEndpoints).doesNotMatch("/actuator/baz"); assertMatcher(matcher).matches("/actuator/bar"); @@ -155,8 +153,7 @@ public class EndpointRequestTests { @Test public void excludeByClassShouldNotMatchLinksIfExcluded() { - RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks() - .excluding(FooEndpoint.class); + RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @@ -171,8 +168,7 @@ public class EndpointRequestTests { @Test public void excludeByIdShouldNotMatchLinksIfExcluded() { - RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks() - .excluding("foo"); + RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @@ -198,8 +194,8 @@ public class EndpointRequestTests { public void endpointRequestMatcherShouldUseCustomRequestMatcherProvider() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); RequestMatcher mockRequestMatcher = (request) -> false; - RequestMatcherAssert assertMatcher = assertMatcher(matcher, - mockPathMappedEndpoints(""), (pattern) -> mockRequestMatcher); + RequestMatcherAssert assertMatcher = assertMatcher(matcher, mockPathMappedEndpoints(""), + (pattern) -> mockRequestMatcher); assertMatcher.doesNotMatch("/foo"); assertMatcher.doesNotMatch("/bar"); } @@ -208,8 +204,8 @@ public class EndpointRequestTests { public void linksRequestMatcherShouldUseCustomRequestMatcherProvider() { RequestMatcher matcher = EndpointRequest.toLinks(); RequestMatcher mockRequestMatcher = (request) -> false; - RequestMatcherAssert assertMatcher = assertMatcher(matcher, - mockPathMappedEndpoints("/actuator"), (pattern) -> mockRequestMatcher); + RequestMatcherAssert assertMatcher = assertMatcher(matcher, mockPathMappedEndpoints("/actuator"), + (pattern) -> mockRequestMatcher); assertMatcher.doesNotMatch("/actuator"); } @@ -242,20 +238,17 @@ public class EndpointRequestTests { return endpoint; } - private RequestMatcherAssert assertMatcher(RequestMatcher matcher, - PathMappedEndpoints pathMappedEndpoints) { + private RequestMatcherAssert assertMatcher(RequestMatcher matcher, PathMappedEndpoints pathMappedEndpoints) { return assertMatcher(matcher, pathMappedEndpoints, null); } - private RequestMatcherAssert assertMatcher(RequestMatcher matcher, - PathMappedEndpoints pathMappedEndpoints, + private RequestMatcherAssert assertMatcher(RequestMatcher matcher, PathMappedEndpoints pathMappedEndpoints, RequestMatcherProvider matcherProvider) { StaticWebApplicationContext context = new StaticWebApplicationContext(); context.registerBean(WebEndpointProperties.class); if (pathMappedEndpoints != null) { context.registerBean(PathMappedEndpoints.class, () -> pathMappedEndpoints); - WebEndpointProperties properties = context - .getBean(WebEndpointProperties.class); + WebEndpointProperties properties = context.getBean(WebEndpointProperties.class); if (!properties.getBasePath().equals(pathMappedEndpoints.getBasePath())) { properties.setBasePath(pathMappedEndpoints.getBasePath()); } @@ -282,8 +275,7 @@ public class EndpointRequestTests { } private void matches(HttpServletRequest request) { - assertThat(this.matcher.matches(request)) - .as("Matches " + getRequestPath(request)).isTrue(); + assertThat(this.matcher.matches(request)).as("Matches " + getRequestPath(request)).isTrue(); } public void doesNotMatch(String servletPath) { @@ -291,15 +283,12 @@ public class EndpointRequestTests { } private void doesNotMatch(HttpServletRequest request) { - assertThat(this.matcher.matches(request)) - .as("Does not match " + getRequestPath(request)).isFalse(); + assertThat(this.matcher.matches(request)).as("Does not match " + getRequestPath(request)).isFalse(); } private MockHttpServletRequest mockRequest(String servletPath) { MockServletContext servletContext = new MockServletContext(); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); if (servletPath != null) { request.setServletPath(servletPath); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java index d88aa8fc736..1bc716e4cfc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java @@ -56,56 +56,45 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Madhura Bhave */ -public class JerseyEndpointRequestIntegrationTests - extends AbstractEndpointRequestIntegrationTests { +public class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrationTests { @Override protected WebApplicationContextRunner getContextRunner() { - return new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withClassLoader(new FilteredClassLoader( - "org.springframework.web.servlet.DispatcherServlet")) - .withUserConfiguration(JerseyEndpointConfiguration.class, - SecurityConfiguration.class, BaseConfiguration.class) - .withConfiguration(AutoConfigurations.of( - SecurityAutoConfiguration.class, - UserDetailsServiceAutoConfiguration.class, - SecurityRequestMatcherProviderAutoConfiguration.class, - JacksonAutoConfiguration.class, - JerseyAutoConfiguration.class)); + return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) + .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .withUserConfiguration(JerseyEndpointConfiguration.class, SecurityConfiguration.class, + BaseConfiguration.class) + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, + UserDetailsServiceAutoConfiguration.class, + SecurityRequestMatcherProviderAutoConfiguration.class, JacksonAutoConfiguration.class, + JerseyAutoConfiguration.class)); } @Test public void toLinksWhenApplicationPathSetShouldMatch() { - getContextRunner().withPropertyValues("spring.jersey.application-path=/admin") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/").exchange().expectStatus() - .isOk(); - webTestClient.get().uri("/admin/actuator").exchange().expectStatus() - .isOk(); - }); + getContextRunner().withPropertyValues("spring.jersey.application-path=/admin").run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/").exchange().expectStatus().isOk(); + webTestClient.get().uri("/admin/actuator").exchange().expectStatus().isOk(); + }); } @Test public void toEndpointWhenApplicationPathSetShouldMatch() { - getContextRunner().withPropertyValues("spring.jersey.application-path=/admin") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e1").exchange() - .expectStatus().isOk(); - }); + getContextRunner().withPropertyValues("spring.jersey.application-path=/admin").run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e1").exchange().expectStatus().isOk(); + }); } @Test public void toAnyEndpointWhenApplicationPathSetShouldMatch() { - getContextRunner().withPropertyValues("spring.jersey.application-path=/admin", - "spring.security.user.password=password").run((context) -> { + getContextRunner() + .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password") + .run((context) -> { WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e2").exchange() - .expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/e2") - .header("Authorization", getBasicAuth()).exchange() + webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get().uri("/admin/actuator/e2").header("Authorization", getBasicAuth()).exchange() .expectStatus().isOk(); }); } @@ -136,19 +125,15 @@ public class JerseyEndpointRequestIntegrationTests } private void customize(ResourceConfig config) { - List mediaTypes = Arrays.asList( - javax.ws.rs.core.MediaType.APPLICATION_JSON, + List mediaTypes = Arrays.asList(javax.ws.rs.core.MediaType.APPLICATION_JSON, ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, - mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer( - this.applicationContext, new ConversionServiceParameterValueMapper(), - endpointMediaTypes, Arrays.asList(EndpointId::toString), - Collections.emptyList(), Collections.emptyList()); - Collection resources = new JerseyEndpointResourceFactory() - .createEndpointResources(new EndpointMapping("/actuator"), - discoverer.getEndpoints(), endpointMediaTypes, - new EndpointLinksResolver(discoverer.getEndpoints())); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, + Arrays.asList(EndpointId::toString), Collections.emptyList(), Collections.emptyList()); + Collection resources = new JerseyEndpointResourceFactory().createEndpointResources( + new EndpointMapping("/actuator"), discoverer.getEndpoints(), endpointMediaTypes, + new EndpointLinksResolver(discoverer.getEndpoints())); config.registerResources(new HashSet<>(resources)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java index c48d82055e1..0b1b4ec9281 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java @@ -51,15 +51,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ManagementWebSecurityAutoConfigurationTests { - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, - InfoEndpointAutoConfiguration.class, - EnvironmentEndpointAutoConfiguration.class, + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( + AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + InfoEndpointAutoConfiguration.class, EnvironmentEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - SecurityAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class)); + SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class)); @Test public void permitAllForHealth() { @@ -89,42 +85,35 @@ public class ManagementWebSecurityAutoConfigurationTests { @Test public void usesMatchersBasedOffConfiguredActuatorBasePath() { - this.contextRunner.withPropertyValues("management.endpoints.web.base-path=/") - .run((context) -> { - HttpStatus status = getResponseStatus(context, "/health"); - assertThat(status).isEqualTo(HttpStatus.OK); - }); + this.contextRunner.withPropertyValues("management.endpoints.web.base-path=/").run((context) -> { + HttpStatus status = getResponseStatus(context, "/health"); + assertThat(status).isEqualTo(HttpStatus.OK); + }); } @Test public void backOffIfCustomSecurityIsAdded() { - this.contextRunner.withUserConfiguration(CustomSecurityConfiguration.class) - .run((context) -> { - HttpStatus status = getResponseStatus(context, "/actuator/health"); - assertThat(status).isEqualTo(HttpStatus.UNAUTHORIZED); - status = getResponseStatus(context, "/foo"); - assertThat(status).isEqualTo(HttpStatus.OK); - }); + this.contextRunner.withUserConfiguration(CustomSecurityConfiguration.class).run((context) -> { + HttpStatus status = getResponseStatus(context, "/actuator/health"); + assertThat(status).isEqualTo(HttpStatus.UNAUTHORIZED); + status = getResponseStatus(context, "/foo"); + assertThat(status).isEqualTo(HttpStatus.OK); + }); } @Test public void backOffIfOAuth2ResourceServerAutoConfigurationPresent() { - this.contextRunner - .withConfiguration(AutoConfigurations - .of(OAuth2ResourceServerAutoConfiguration.class)) - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") - .run((context) -> assertThat(context) - .doesNotHaveBean(ManagementWebSecurityConfigurerAdapter.class)); + this.contextRunner.withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") + .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityConfigurerAdapter.class)); } - private HttpStatus getResponseStatus(AssertableWebApplicationContext context, - String path) throws IOException, javax.servlet.ServletException { + private HttpStatus getResponseStatus(AssertableWebApplicationContext context, String path) + throws IOException, javax.servlet.ServletException { FilterChainProxy filterChainProxy = context.getBean(FilterChainProxy.class); MockServletContext servletContext = new MockServletContext(); MockHttpServletResponse response = new MockHttpServletResponse(); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setServletPath(path); request.setMethod("GET"); @@ -137,8 +126,8 @@ public class ManagementWebSecurityAutoConfigurationTests { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/foo").permitAll().anyRequest() - .authenticated().and().formLogin().and().httpBasic(); + http.authorizeRequests().antMatchers("/foo").permitAll().anyRequest().authenticated().and().formLogin() + .and().httpBasic(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java index 0b5d59b7355..f2949ef0386 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java @@ -54,58 +54,46 @@ import org.springframework.web.cors.CorsConfiguration; * * @author Madhura Bhave */ -public class MvcEndpointRequestIntegrationTests - extends AbstractEndpointRequestIntegrationTests { +public class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrationTests { @Test public void toLinksWhenServletPathSetShouldMatch() { - getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/").exchange().expectStatus() - .isOk(); - webTestClient.get().uri("/admin/actuator").exchange().expectStatus() - .isOk(); - }); + getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin").run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/").exchange().expectStatus().isOk(); + webTestClient.get().uri("/admin/actuator").exchange().expectStatus().isOk(); + }); } @Test public void toEndpointWhenServletPathSetShouldMatch() { - getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e1").exchange() - .expectStatus().isOk(); - }); + getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin").run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e1").exchange().expectStatus().isOk(); + }); } @Test public void toAnyEndpointWhenServletPathSetShouldMatch() { - getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin", - "spring.security.user.password=password").run((context) -> { + getContextRunner() + .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password") + .run((context) -> { WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e2").exchange() - .expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/e2") - .header("Authorization", getBasicAuth()).exchange() + webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get().uri("/admin/actuator/e2").header("Authorization", getBasicAuth()).exchange() .expectStatus().isOk(); }); } @Override protected WebApplicationContextRunner getContextRunner() { - return new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withUserConfiguration(WebMvcEndpointConfiguration.class, - SecurityConfiguration.class, BaseConfiguration.class) - .withConfiguration(AutoConfigurations.of( - SecurityAutoConfiguration.class, - UserDetailsServiceAutoConfiguration.class, - WebMvcAutoConfiguration.class, - SecurityRequestMatcherProviderAutoConfiguration.class, - JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - DispatcherServletAutoConfiguration.class)); + return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) + .withUserConfiguration(WebMvcEndpointConfiguration.class, SecurityConfiguration.class, + BaseConfiguration.class) + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, + UserDetailsServiceAutoConfiguration.class, WebMvcAutoConfiguration.class, + SecurityRequestMatcherProviderAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class)); } @Configuration(proxyBeanMethods = false) @@ -125,18 +113,13 @@ public class MvcEndpointRequestIntegrationTests @Bean public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping() { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, - ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, - mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer( - this.applicationContext, new ConversionServiceParameterValueMapper(), - endpointMediaTypes, Arrays.asList(EndpointId::toString), - Collections.emptyList(), Collections.emptyList()); - return new WebMvcEndpointHandlerMapping(new EndpointMapping("/actuator"), - discoverer.getEndpoints(), endpointMediaTypes, - new CorsConfiguration(), - new EndpointLinksResolver(discoverer.getEndpoints())); + List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, + Arrays.asList(EndpointId::toString), Collections.emptyList(), Collections.emptyList()); + return new WebMvcEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), + endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java index 1190187813d..fb1f94705fc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java @@ -36,30 +36,24 @@ import static org.mockito.Mockito.mock; public class SessionsEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) .withUserConfiguration(SessionConfiguration.class); @Test public void runShouldHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=sessions") - .run((context) -> assertThat(context) - .hasSingleBean(SessionsEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sessions") + .run((context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.sessions.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(SessionsEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.sessions.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java index a1b412ce8b2..4ac714b15ba 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java @@ -36,21 +36,18 @@ public class SolrHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class, - SolrHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + SolrHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(SolrHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(SolrHealthIndicator.class) + .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.solr.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(SolrHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(SolrHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java index df62b48b524..b0aa833af8a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java @@ -35,44 +35,35 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DiskSpaceHealthIndicatorAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DiskSpaceHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations + .of(DiskSpaceHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test public void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(DiskSpaceHealthIndicator.class) + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test public void thresholdMustBePositive() { - this.contextRunner - .withPropertyValues("management.health.diskspace.threshold=-10MB") + this.contextRunner.withPropertyValues("management.health.diskspace.threshold=-10MB") .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining( - "Failed to bind properties under 'management.health.diskspace'")); + .hasMessageContaining("Failed to bind properties under 'management.health.diskspace'")); } @Test public void thresholdCanBeCustomized() { - this.contextRunner - .withPropertyValues("management.health.diskspace.threshold=20MB") - .run((context) -> { - assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class); - assertThat(context.getBean(DiskSpaceHealthIndicator.class)) - .hasFieldOrPropertyWithValue("threshold", - DataSize.ofMegabytes(20)); - }); + this.contextRunner.withPropertyValues("management.health.diskspace.threshold=20MB").run((context) -> { + assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class); + assertThat(context.getBean(DiskSpaceHealthIndicator.class)).hasFieldOrPropertyWithValue("threshold", + DataSize.ofMegabytes(20)); + }); } @Test public void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.diskspace.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(DiskSpaceHealthIndicator.class) + .run((context) -> assertThat(context).doesNotHaveBean(DiskSpaceHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java index d0cda496a1f..d4e7b5e0de4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java @@ -34,17 +34,14 @@ public class ManagementContextConfigurationTests { @Test public void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes( - DefaultManagementContextConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test public void proxyBeanMethodsCanBeDisabled() { - AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes( - NoBeanMethodProxyingManagementContextConfiguration.class, - Configuration.class); + AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes( + NoBeanMethodProxyingManagementContextConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java index 8d184354a38..582d3aee94b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java @@ -53,29 +53,25 @@ public class JerseyChildManagementContextConfigurationTests { @Test public void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(JerseySameManagementContextConfiguration.class)); - contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test public void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test public void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { - this.contextRunner.withUserConfiguration(CustomizerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ResourceConfig.class); - ResourceConfig config = context.getBean(ResourceConfig.class); - ResourceConfigCustomizer customizer = context - .getBean(ResourceConfigCustomizer.class); - verify(customizer).customize(config); - }); + this.contextRunner.withUserConfiguration(CustomizerConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(ResourceConfig.class); + ResourceConfig config = context.getBean(ResourceConfig.class); + ResourceConfigCustomizer customizer = context.getBean(ResourceConfigCustomizer.class); + verify(customizer).customize(config); + }); } @Test @@ -90,16 +86,14 @@ public class JerseyChildManagementContextConfigurationTests { @SuppressWarnings("unchecked") public void servletRegistrationBeanIsAutoConfigured() { this.contextRunner.run((context) -> { - ServletRegistrationBean bean = context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean bean = context.getBean(ServletRegistrationBean.class); assertThat(bean.getUrlMappings()).containsExactly("/*"); }); } @Test public void resourceConfigCustomizerBeanIsNotRequired() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(ResourceConfig.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ResourceConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java index 11c4f530b8f..344f2301c8a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java @@ -47,72 +47,62 @@ import static org.mockito.Mockito.verify; public class JerseySameManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); @Test public void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(JerseySameManagementContextConfiguration.class)); - contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test public void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test public void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { - this.contextRunner.withUserConfiguration(CustomizerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ResourceConfig.class); - ResourceConfig config = context.getBean(ResourceConfig.class); - ResourceConfigCustomizer customizer = context - .getBean(ResourceConfigCustomizer.class); - verify(customizer).customize(config); - }); + this.contextRunner.withUserConfiguration(CustomizerConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(ResourceConfig.class); + ResourceConfig config = context.getBean(ResourceConfig.class); + ResourceConfigCustomizer customizer = context.getBean(ResourceConfigCustomizer.class); + verify(customizer).customize(config); + }); } @Test public void jerseyApplicationPathIsAutoConfiguredWhenNeeded() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(DefaultJerseyApplicationPath.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyApplicationPath.class)); } @Test public void jerseyApplicationPathIsConditionalOnMissingBean() { - this.contextRunner.withUserConfiguration(ConfigWithJerseyApplicationPath.class) - .run((context) -> { - assertThat(context).hasSingleBean(JerseyApplicationPath.class); - assertThat(context).hasBean("testJerseyApplicationPath"); - }); + this.contextRunner.withUserConfiguration(ConfigWithJerseyApplicationPath.class).run((context) -> { + assertThat(context).hasSingleBean(JerseyApplicationPath.class); + assertThat(context).hasBean("testJerseyApplicationPath"); + }); } @Test public void existingResourceConfigBeanShouldNotAutoConfigureRelatedBeans() { - this.contextRunner.withUserConfiguration(ConfigWithResourceConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(ResourceConfig.class); - assertThat(context).doesNotHaveBean(JerseyApplicationPath.class); - assertThat(context).doesNotHaveBean(ServletRegistrationBean.class); - assertThat(context).hasBean("customResourceConfig"); - }); + this.contextRunner.withUserConfiguration(ConfigWithResourceConfig.class).run((context) -> { + assertThat(context).hasSingleBean(ResourceConfig.class); + assertThat(context).doesNotHaveBean(JerseyApplicationPath.class); + assertThat(context).doesNotHaveBean(ServletRegistrationBean.class); + assertThat(context).hasBean("customResourceConfig"); + }); } @Test @SuppressWarnings("unchecked") public void servletRegistrationBeanIsAutoConfiguredWhenNeeded() { - this.contextRunner.withPropertyValues("spring.jersey.application-path=/jersey") - .run((context) -> { - ServletRegistrationBean bean = context - .getBean(ServletRegistrationBean.class); - assertThat(bean.getUrlMappings()).containsExactly("/jersey/*"); - }); + this.contextRunner.withPropertyValues("spring.jersey.application-path=/jersey").run((context) -> { + ServletRegistrationBean bean = context.getBean(ServletRegistrationBean.class); + assertThat(bean.getUrlMappings()).containsExactly("/jersey/*"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java index 841680ef2cd..fd1d26ce4e9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java @@ -45,13 +45,11 @@ public class ReactiveManagementContextFactoryTests { this.parent.register(ParentConfiguration.class); this.parent.refresh(); AnnotationConfigReactiveWebServerApplicationContext childContext = (AnnotationConfigReactiveWebServerApplicationContext) this.factory - .createManagementContext(this.parent, TestConfiguration1.class, - TestConfiguration2.class); + .createManagementContext(this.parent, TestConfiguration1.class, TestConfiguration2.class); childContext.refresh(); assertThat(childContext.getBean(TestConfiguration1.class)).isNotNull(); assertThat(childContext.getBean(TestConfiguration2.class)).isNotNull(); - assertThat(childContext.getBean(ReactiveWebServerFactoryAutoConfiguration.class)) - .isNotNull(); + assertThat(childContext.getBean(ReactiveWebServerFactoryAutoConfiguration.class)).isNotNull(); childContext.close(); this.parent.close(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java index e648e9deabc..c22b8375eae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java @@ -43,19 +43,15 @@ import static org.assertj.core.api.Assertions.assertThat; public class ManagementContextAutoConfigurationTests { @Test - public void childManagementContextShouldStartForEmbeddedServer( - CapturedOutput capturedOutput) { + public void childManagementContextShouldStartForEmbeddedServer(CapturedOutput capturedOutput) { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of( - ManagementContextAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, - WebEndpointAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class)); contextRunner.withPropertyValues("server.port=0", "management.server.port=0") - .run((context) -> assertThat(tomcatStartedOccurencesIn(capturedOutput)) - .isEqualTo(2)); + .run((context) -> assertThat(tomcatStartedOccurencesIn(capturedOutput)).isEqualTo(2)); } private int tomcatStartedOccurencesIn(CharSequence output) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java index 99e49074656..3b73b81663a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java @@ -39,29 +39,23 @@ public class ManagementContextConfigurationImportSelectorTests { @Test public void selectImportsShouldOrderResult() { - String[] imports = new TestManagementContextConfigurationsImportSelector(C.class, - A.class, D.class, B.class).selectImports( - AnnotationMetadata.introspect(EnableChildContext.class)); - assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), - C.class.getName(), D.class.getName()); + String[] imports = new TestManagementContextConfigurationsImportSelector(C.class, A.class, D.class, B.class) + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), C.class.getName(), D.class.getName()); } @Test public void selectImportsFiltersChildOnlyConfigurationWhenUsingSameContext() { - String[] imports = new TestManagementContextConfigurationsImportSelector( - ChildOnly.class, SameOnly.class, A.class).selectImports( - AnnotationMetadata.introspect(EnableSameContext.class)); - assertThat(imports).containsExactlyInAnyOrder(SameOnly.class.getName(), - A.class.getName()); + String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, + A.class).selectImports(AnnotationMetadata.introspect(EnableSameContext.class)); + assertThat(imports).containsExactlyInAnyOrder(SameOnly.class.getName(), A.class.getName()); } @Test public void selectImportsFiltersSameOnlyConfigurationWhenUsingChildContext() { - String[] imports = new TestManagementContextConfigurationsImportSelector( - ChildOnly.class, SameOnly.class, A.class).selectImports( - AnnotationMetadata.introspect(EnableChildContext.class)); - assertThat(imports).containsExactlyInAnyOrder(ChildOnly.class.getName(), - A.class.getName()); + String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, + A.class).selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + assertThat(imports).containsExactlyInAnyOrder(ChildOnly.class.getName(), A.class.getName()); } private static final class TestManagementContextConfigurationsImportSelector @@ -70,8 +64,7 @@ public class ManagementContextConfigurationImportSelectorTests { private final List factoryNames; private TestManagementContextConfigurationsImportSelector(Class... classes) { - this.factoryNames = Stream.of(classes).map(Class::getName) - .collect(Collectors.toList()); + this.factoryNames = Stream.of(classes).map(Class::getName).collect(Collectors.toList()); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java index f6de31dee63..d60081205ea 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java @@ -52,8 +52,8 @@ public class CompositeHandlerExceptionResolverTests { load(TestConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); - ModelAndView resolved = resolver.resolveException(this.request, this.response, - null, new HttpRequestMethodNotSupportedException("POST")); + ModelAndView resolved = resolver.resolveException(this.request, this.response, null, + new HttpRequestMethodNotSupportedException("POST")); assertThat(resolved.getViewName()).isEqualTo("test-view"); } @@ -62,8 +62,8 @@ public class CompositeHandlerExceptionResolverTests { load(BaseConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); - ModelAndView resolved = resolver.resolveException(this.request, this.response, - null, new HttpRequestMethodNotSupportedException("POST")); + ModelAndView resolved = resolver.resolveException(this.request, this.response, null, + new HttpRequestMethodNotSupportedException("POST")); assertThat(resolved).isNotNull(); } @@ -98,8 +98,8 @@ public class CompositeHandlerExceptionResolverTests { static class TestHandlerExceptionResolver implements HandlerExceptionResolver { @Override - public ModelAndView resolveException(HttpServletRequest request, - HttpServletResponse response, Object handler, Exception ex) { + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) { return new ModelAndView("test-view"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java index 46beac7790b..8fe8cf82c55 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory @Override public WebServer getWebServer(ServletContextInitializer... initializers) { - this.webServer = spy( - new MockServletWebServer(mergeInitializers(initializers), getPort())); + this.webServer = spy(new MockServletWebServer(mergeInitializers(initializers), getPort())); return this.webServer; } @@ -56,22 +55,18 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory } public RegisteredServlet getRegisteredServlet(int index) { - return (getWebServer() != null) ? getWebServer().getRegisteredServlet(index) - : null; + return (getWebServer() != null) ? getWebServer().getRegisteredServlet(index) : null; } public RegisteredFilter getRegisteredFilter(int index) { - return (getWebServer() != null) ? getWebServer().getRegisteredFilters(index) - : null; + return (getWebServer() != null) ? getWebServer().getRegisteredFilters(index) : null; } public static class MockServletWebServer - extends org.springframework.boot.testsupport.web.servlet.MockServletWebServer - implements WebServer { + extends org.springframework.boot.testsupport.web.servlet.MockServletWebServer implements WebServer { public MockServletWebServer(ServletContextInitializer[] initializers, int port) { - super(Arrays.stream(initializers) - .map((initializer) -> (Initializer) initializer::onStartup) + super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup) .toArray(Initializer[]::new), port); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java index cbe9fd5f7c5..7ad8dfdd609 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java @@ -39,16 +39,14 @@ public class WebMvcEndpointChildContextConfigurationTests { @Test public void contextShouldConfigureRequestContextFilter() { - this.contextRunner - .withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(OrderedRequestContextFilter.class)); + this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); } @Test public void contextShouldNotConfigureRequestContextFilterWhenPresent() { - this.contextRunner.withUserConfiguration(ExistingConfig.class, - WebMvcEndpointChildContextConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(ExistingConfig.class, WebMvcEndpointChildContextConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(RequestContextFilter.class); assertThat(context).hasBean("testRequestContextFilter"); }); @@ -59,18 +57,14 @@ public class WebMvcEndpointChildContextConfigurationTests { this.contextRunner.withUserConfiguration(RequestContextListenerConfig.class, WebMvcEndpointChildContextConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(RequestContextListener.class); - assertThat(context) - .doesNotHaveBean(OrderedRequestContextFilter.class); + assertThat(context).doesNotHaveBean(OrderedRequestContextFilter.class); }); } @Test public void contextShouldConfigureDispatcherServletPathWithRootPath() { - this.contextRunner - .withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) - .run((context) -> assertThat( - context.getBean(DispatcherServletPath.class).getPath()) - .isEqualTo("/")); + this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) + .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()).isEqualTo("/")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java index e0bf832b7ca..661794f84e6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java @@ -51,20 +51,17 @@ public class HttpTraceAutoConfigurationTests { @Test public void autoConfigurationIsDisabledByDefault() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(HttpTraceAutoConfiguration.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(HttpTraceAutoConfiguration.class)); } @Test public void autoConfigurationIsEnabledWhenHttpTraceRepositoryBeanPresent() { - this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(HttpExchangeTracer.class); - assertThat(context).hasSingleBean(HttpTraceFilter.class); - assertThat(context).hasSingleBean(HttpTraceRepository.class); - assertThat(context.getBean(HttpTraceRepository.class)) - .isInstanceOf(CustomHttpTraceRepository.class); - }); + this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(HttpExchangeTracer.class); + assertThat(context).hasSingleBean(HttpTraceFilter.class); + assertThat(context).hasSingleBean(HttpTraceRepository.class); + assertThat(context.getBean(HttpTraceRepository.class)).isInstanceOf(CustomHttpTraceRepository.class); + }); } @Test @@ -72,30 +69,25 @@ public class HttpTraceAutoConfigurationTests { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withUserConfiguration(CustomTracerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpExchangeTracer.class); - assertThat(context.getBean(HttpExchangeTracer.class)) - .isInstanceOf(CustomHttpExchangeTracer.class); + assertThat(context.getBean(HttpExchangeTracer.class)).isInstanceOf(CustomHttpExchangeTracer.class); }); } @Test public void usesUserProvidedWebFilterWhenReactiveContext() { new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) .withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withUserConfiguration(CustomWebFilterConfiguration.class) - .run((context) -> { + .withUserConfiguration(CustomWebFilterConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpTraceWebFilter.class); - assertThat(context.getBean(HttpTraceWebFilter.class)) - .isInstanceOf(CustomHttpTraceWebFilter.class); + assertThat(context.getBean(HttpTraceWebFilter.class)).isInstanceOf(CustomHttpTraceWebFilter.class); }); } @Test public void configuresServletFilter() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(HttpTraceFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpTraceFilter.class)); } @Test @@ -103,8 +95,7 @@ public class HttpTraceAutoConfigurationTests { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withUserConfiguration(CustomFilterConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpTraceFilter.class); - assertThat(context.getBean(HttpTraceFilter.class)) - .isInstanceOf(CustomHttpTraceFilter.class); + assertThat(context.getBean(HttpTraceFilter.class)).isInstanceOf(CustomHttpTraceFilter.class); }); } @@ -112,10 +103,8 @@ public class HttpTraceAutoConfigurationTests { public void backsOffWhenDisabled() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withPropertyValues("management.trace.http.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(InMemoryHttpTraceRepository.class) - .doesNotHaveBean(HttpExchangeTracer.class) - .doesNotHaveBean(HttpTraceFilter.class)); + .run((context) -> assertThat(context).doesNotHaveBean(InMemoryHttpTraceRepository.class) + .doesNotHaveBean(HttpExchangeTracer.class).doesNotHaveBean(HttpTraceFilter.class)); } private static class CustomHttpTraceRepository implements HttpTraceRepository { @@ -162,8 +151,8 @@ public class HttpTraceAutoConfigurationTests { private static final class CustomHttpTraceWebFilter extends HttpTraceWebFilter { - private CustomHttpTraceWebFilter(HttpTraceRepository repository, - HttpExchangeTracer tracer, Set includes) { + private CustomHttpTraceWebFilter(HttpTraceRepository repository, HttpExchangeTracer tracer, + Set includes) { super(repository, tracer, includes); } @@ -173,18 +162,16 @@ public class HttpTraceAutoConfigurationTests { static class CustomWebFilterConfiguration { @Bean - public CustomHttpTraceWebFilter customWebFilter(HttpTraceRepository repository, - HttpExchangeTracer tracer, HttpTraceProperties properties) { - return new CustomHttpTraceWebFilter(repository, tracer, - properties.getInclude()); + public CustomHttpTraceWebFilter customWebFilter(HttpTraceRepository repository, HttpExchangeTracer tracer, + HttpTraceProperties properties) { + return new CustomHttpTraceWebFilter(repository, tracer, properties.getInclude()); } } private static final class CustomHttpTraceFilter extends HttpTraceFilter { - private CustomHttpTraceFilter(HttpTraceRepository repository, - HttpExchangeTracer tracer) { + private CustomHttpTraceFilter(HttpTraceRepository repository, HttpExchangeTracer tracer) { super(repository, tracer); } @@ -194,8 +181,7 @@ public class HttpTraceAutoConfigurationTests { static class CustomFilterConfiguration { @Bean - public CustomHttpTraceFilter customWebFilter(HttpTraceRepository repository, - HttpExchangeTracer tracer) { + public CustomHttpTraceFilter customWebFilter(HttpTraceRepository repository, HttpExchangeTracer tracer) { return new CustomHttpTraceFilter(repository, tracer); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java index f33b598a214..cc98226e56a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java @@ -37,23 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class HttpTraceEndpointAutoConfigurationTests { - private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class, - HttpTraceEndpointAutoConfiguration.class)); + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( + AutoConfigurations.of(HttpTraceAutoConfiguration.class, HttpTraceEndpointAutoConfiguration.class)); @Test public void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=httptrace") - .run((context) -> assertThat(context) - .hasSingleBean(HttpTraceEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpTraceEndpoint.class)); } @Test public void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(HttpTraceEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Test @@ -61,16 +58,13 @@ public class HttpTraceEndpointAutoConfigurationTests { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=httptrace") .withPropertyValues("management.endpoint.httptrace.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HttpTraceEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Test public void endpointBacksOffWhenRepositoryIsNotAvailable() { - this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=httptrace") - .run((context) -> assertThat(context) - .doesNotHaveBean(HttpTraceEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=httptrace") + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java index c7cf8f98d6f..2ce4a058b20 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,8 @@ public class RabbitHealthIndicator extends AbstractHealthIndicator { } private String getVersion() { - return this.rabbitTemplate.execute((channel) -> channel.getConnection() - .getServerProperties().get("version").toString()); + return this.rabbitTemplate + .execute((channel) -> channel.getConnection().getServerProperties().get("version").toString()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java index 135950a22d2..f35a32adedc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,8 +81,7 @@ public class AuditEvent implements Serializable { * @param type the event type * @param data the event data */ - public AuditEvent(Instant timestamp, String principal, String type, - Map data) { + public AuditEvent(Instant timestamp, String principal, String type, Map data) { Assert.notNull(timestamp, "Timestamp must not be null"); Assert.notNull(type, "Type must not be null"); this.timestamp = timestamp; @@ -140,8 +139,8 @@ public class AuditEvent implements Serializable { @Override public String toString() { - return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal - + ", type=" + this.type + ", data=" + this.data + "]"; + return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal + ", type=" + this.type + + ", data=" + this.data + "]"; } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEventsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEventsEndpoint.java index d57a95fbacd..50fc9760ced 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEventsEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEventsEndpoint.java @@ -42,10 +42,9 @@ public class AuditEventsEndpoint { } @ReadOperation - public AuditEventsDescriptor events(@Nullable String principal, - @Nullable OffsetDateTime after, @Nullable String type) { - List events = this.auditEventRepository.find(principal, - getInstant(after), type); + public AuditEventsDescriptor events(@Nullable String principal, @Nullable OffsetDateTime after, + @Nullable String type) { + List events = this.auditEventRepository.find(principal, getInstant(after), type); return new AuditEventsDescriptor(events); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepository.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepository.java index b0ae38cab9d..5bc6a16b9a5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepository.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,8 +83,7 @@ public class InMemoryAuditEventRepository implements AuditEventRepository { return events; } - private boolean isMatch(String principal, Instant after, String type, - AuditEvent event) { + private boolean isMatch(String principal, Instant after, String type, AuditEvent event) { boolean match = true; match = match && (principal == null || event.getPrincipal().equals(principal)); match = match && (after == null || event.getTimestamp().isAfter(after)); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java index f9c14f93f3d..d152bb6600b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.context.ApplicationListener; * @author Vedran Pavic * @since 1.4.0 */ -public abstract class AbstractAuditListener - implements ApplicationListener { +public abstract class AbstractAuditListener implements ApplicationListener { @Override public void onApplicationEvent(AuditApplicationEvent event) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java index 297a93dfa15..ff4531c8d32 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ public class AuditApplicationEvent extends ApplicationEvent { * @param data the event data * @see AuditEvent#AuditEvent(String, String, Map) */ - public AuditApplicationEvent(String principal, String type, - Map data) { + public AuditApplicationEvent(String principal, String type, Map data) { this(new AuditEvent(principal, type, data)); } @@ -66,8 +65,7 @@ public class AuditApplicationEvent extends ApplicationEvent { * @param data the event data * @see AuditEvent#AuditEvent(Instant, String, String, Map) */ - public AuditApplicationEvent(Instant timestamp, String principal, String type, - Map data) { + public AuditApplicationEvent(Instant timestamp, String principal, String type, Map data) { this(new AuditEvent(timestamp, principal, type, data)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/beans/BeansEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/beans/BeansEndpoint.java index 72110a799f6..a4a6cf945f8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/beans/BeansEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/beans/BeansEndpoint.java @@ -62,8 +62,7 @@ public class BeansEndpoint { return new ApplicationBeans(contexts); } - private static ConfigurableApplicationContext getConfigurableParent( - ConfigurableApplicationContext context) { + private static ConfigurableApplicationContext getConfigurableParent(ConfigurableApplicationContext context) { ApplicationContext parent = context.getParent(); if (parent instanceof ConfigurableApplicationContext) { return (ConfigurableApplicationContext) parent; @@ -117,12 +116,10 @@ public class BeansEndpoint { return null; } ConfigurableApplicationContext parent = getConfigurableParent(context); - return new ContextBeans(describeBeans(context.getBeanFactory()), - (parent != null) ? parent.getId() : null); + return new ContextBeans(describeBeans(context.getBeanFactory()), (parent != null) ? parent.getId() : null); } - private static Map describeBeans( - ConfigurableListableBeanFactory beanFactory) { + private static Map describeBeans(ConfigurableListableBeanFactory beanFactory) { Map beans = new HashMap<>(); for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition definition = beanFactory.getBeanDefinition(beanName); @@ -135,13 +132,11 @@ public class BeansEndpoint { private static BeanDescriptor describeBean(String name, BeanDefinition definition, ConfigurableListableBeanFactory factory) { - return new BeanDescriptor(factory.getAliases(name), definition.getScope(), - factory.getType(name), definition.getResourceDescription(), - factory.getDependenciesForBean(name)); + return new BeanDescriptor(factory.getAliases(name), definition.getScope(), factory.getType(name), + definition.getResourceDescription(), factory.getDependenciesForBean(name)); } - private static boolean isBeanEligible(String beanName, BeanDefinition bd, - ConfigurableBeanFactory bf) { + private static boolean isBeanEligible(String beanName, BeanDefinition bd, ConfigurableBeanFactory bf) { return (bd.getRole() != BeanDefinition.ROLE_INFRASTRUCTURE && (!bd.isLazyInit() || bf.containsSingleton(beanName))); } @@ -164,11 +159,9 @@ public class BeansEndpoint { private final String[] dependencies; - private BeanDescriptor(String[] aliases, String scope, Class type, - String resource, String[] dependencies) { + private BeanDescriptor(String[] aliases, String scope, Class type, String resource, String[] dependencies) { this.aliases = aliases; - this.scope = (StringUtils.hasText(scope) ? scope - : BeanDefinition.SCOPE_SINGLETON); + this.scope = (StringUtils.hasText(scope) ? scope : BeanDefinition.SCOPE_SINGLETON); this.type = type; this.resource = resource; this.dependencies = dependencies; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java index da58479578e..f4c9911c580 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java @@ -61,14 +61,12 @@ public class CachesEndpoint { getCacheEntries(matchAll(), matchAll()).forEach((entry) -> { String cacheName = entry.getName(); String cacheManager = entry.getCacheManager(); - Map cacheManagerDescriptors = descriptors - .computeIfAbsent(cacheManager, (key) -> new LinkedHashMap<>()); - cacheManagerDescriptors.put(cacheName, - new CacheDescriptor(entry.getTarget())); + Map cacheManagerDescriptors = descriptors.computeIfAbsent(cacheManager, + (key) -> new LinkedHashMap<>()); + cacheManagerDescriptors.put(cacheName, new CacheDescriptor(entry.getTarget())); }); Map cacheManagerDescriptors = new LinkedHashMap<>(); - descriptors.forEach((name, entries) -> cacheManagerDescriptors.put(name, - new CacheManagerDescriptor(entries))); + descriptors.forEach((name, entries) -> cacheManagerDescriptors.put(name, new CacheManagerDescriptor(entries))); return new CachesReport(cacheManagerDescriptors); } @@ -82,8 +80,7 @@ public class CachesEndpoint { */ @ReadOperation public CacheEntry cache(@Selector String cache, @Nullable String cacheManager) { - return extractUniqueCacheEntry(cache, - getCacheEntries((name) -> name.equals(cache), isNameMatch(cacheManager))); + return extractUniqueCacheEntry(cache, getCacheEntries((name) -> name.equals(cache), isNameMatch(cacheManager))); } /** @@ -113,25 +110,21 @@ public class CachesEndpoint { private List getCacheEntries(Predicate cacheNamePredicate, Predicate cacheManagerNamePredicate) { return this.cacheManagers.keySet().stream().filter(cacheManagerNamePredicate) - .flatMap((cacheManagerName) -> getCacheEntries(cacheManagerName, - cacheNamePredicate).stream()) + .flatMap((cacheManagerName) -> getCacheEntries(cacheManagerName, cacheNamePredicate).stream()) .collect(Collectors.toList()); } - private List getCacheEntries(String cacheManagerName, - Predicate cacheNamePredicate) { + private List getCacheEntries(String cacheManagerName, Predicate cacheNamePredicate) { CacheManager cacheManager = this.cacheManagers.get(cacheManagerName); - return cacheManager.getCacheNames().stream().filter(cacheNamePredicate) - .map(cacheManager::getCache).filter(Objects::nonNull) - .map((cache) -> new CacheEntry(cache, cacheManagerName)) + return cacheManager.getCacheNames().stream().filter(cacheNamePredicate).map(cacheManager::getCache) + .filter(Objects::nonNull).map((cache) -> new CacheEntry(cache, cacheManagerName)) .collect(Collectors.toList()); } private CacheEntry extractUniqueCacheEntry(String cache, List entries) { if (entries.size() > 1) { throw new NonUniqueCacheException(cache, - entries.stream().map(CacheEntry::getCacheManager).distinct() - .collect(Collectors.toList())); + entries.stream().map(CacheEntry::getCacheManager).distinct().collect(Collectors.toList())); } return (!entries.isEmpty() ? entries.get(0) : null); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpointWebExtension.java index bb0bca78c7b..3b4a8e70214 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpointWebExtension.java @@ -40,12 +40,10 @@ public class CachesEndpointWebExtension { } @ReadOperation - public WebEndpointResponse cache(@Selector String cache, - @Nullable String cacheManager) { + public WebEndpointResponse cache(@Selector String cache, @Nullable String cacheManager) { try { CacheEntry entry = this.delegate.cache(cache, cacheManager); - int status = (entry != null) ? WebEndpointResponse.STATUS_OK - : WebEndpointResponse.STATUS_NOT_FOUND; + int status = (entry != null) ? WebEndpointResponse.STATUS_OK : WebEndpointResponse.STATUS_NOT_FOUND; return new WebEndpointResponse<>(entry, status); } catch (NonUniqueCacheException ex) { @@ -54,12 +52,10 @@ public class CachesEndpointWebExtension { } @DeleteOperation - public WebEndpointResponse clearCache(@Selector String cache, - @Nullable String cacheManager) { + public WebEndpointResponse clearCache(@Selector String cache, @Nullable String cacheManager) { try { boolean cleared = this.delegate.clearCache(cache, cacheManager); - int status = (cleared ? WebEndpointResponse.STATUS_NO_CONTENT - : WebEndpointResponse.STATUS_NOT_FOUND); + int status = (cleared ? WebEndpointResponse.STATUS_NO_CONTENT : WebEndpointResponse.STATUS_NOT_FOUND); return new WebEndpointResponse<>(status); } catch (NonUniqueCacheException ex) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/NonUniqueCacheException.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/NonUniqueCacheException.java index c2f5e2e14d8..ac819b88070 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/NonUniqueCacheException.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/NonUniqueCacheException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,10 +31,9 @@ public class NonUniqueCacheException extends RuntimeException { private final Collection cacheManagerNames; - public NonUniqueCacheException(String cacheName, - Collection cacheManagerNames) { - super(String.format("Multiple caches named %s found, specify the 'cacheManager' " - + "to use: %s", cacheName, cacheManagerNames)); + public NonUniqueCacheException(String cacheName, Collection cacheManagerNames) { + super(String.format("Multiple caches named %s found, specify the 'cacheManager' " + "to use: %s", cacheName, + cacheManagerNames)); this.cacheName = cacheName; this.cacheManagerNames = Collections.unmodifiableCollection(cacheManagerNames); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicator.java index d3cdcb7fad9..bcaaae1bd86 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class CassandraHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { Select select = QueryBuilder.select("release_version").from("system", "local"); - ResultSet results = this.cassandraOperations.getCqlOperations() - .queryForResultSet(select); + ResultSet results = this.cassandraOperations.getCqlOperations().queryForResultSet(select); if (results.isExhausted()) { builder.up(); return; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicator.java index 0f5875ad7fb..f8843fbd941 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,20 +39,16 @@ public class CassandraReactiveHealthIndicator extends AbstractReactiveHealthIndi * Create a new {@link CassandraHealthIndicator} instance. * @param reactiveCassandraOperations the Cassandra operations */ - public CassandraReactiveHealthIndicator( - ReactiveCassandraOperations reactiveCassandraOperations) { - Assert.notNull(reactiveCassandraOperations, - "ReactiveCassandraOperations must not be null"); + public CassandraReactiveHealthIndicator(ReactiveCassandraOperations reactiveCassandraOperations) { + Assert.notNull(reactiveCassandraOperations, "ReactiveCassandraOperations must not be null"); this.reactiveCassandraOperations = reactiveCassandraOperations; } @Override protected Mono doHealthCheck(Health.Builder builder) { Select select = QueryBuilder.select("release_version").from("system", "local"); - return this.reactiveCassandraOperations.getReactiveCqlOperations() - .queryForObject(select, String.class) - .map((version) -> builder.up().withDetail("version", version).build()) - .single(); + return this.reactiveCassandraOperations.getReactiveCqlOperations().queryForObject(select, String.class) + .map((version) -> builder.up().withDetail("version", version).build()).single(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java index 7c235823924..2588da2a735 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java @@ -38,12 +38,10 @@ import org.springframework.context.ConfigurableApplicationContext; public class ShutdownEndpoint implements ApplicationContextAware { private static final Map NO_CONTEXT_MESSAGE = Collections - .unmodifiableMap( - Collections.singletonMap("message", "No context to shutdown.")); + .unmodifiableMap(Collections.singletonMap("message", "No context to shutdown.")); private static final Map SHUTDOWN_MESSAGE = Collections - .unmodifiableMap( - Collections.singletonMap("message", "Shutting down, bye...")); + .unmodifiableMap(Collections.singletonMap("message", "Shutting down, bye...")); private ConfigurableApplicationContext context; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java index d56d15d8776..9b0409fef6c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java @@ -100,31 +100,27 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext Map contextProperties = new HashMap<>(); ApplicationContext target = context; while (target != null) { - contextProperties.put(target.getId(), - describeConfigurationProperties(target, getObjectMapper())); + contextProperties.put(target.getId(), describeConfigurationProperties(target, getObjectMapper())); target = target.getParent(); } return new ApplicationConfigurationProperties(contextProperties); } - private ContextConfigurationProperties describeConfigurationProperties( - ApplicationContext context, ObjectMapper mapper) { - ConfigurationBeanFactoryMetadata beanFactoryMetadata = getBeanFactoryMetadata( - context); - Map beans = getConfigurationPropertiesBeans(context, - beanFactoryMetadata); + private ContextConfigurationProperties describeConfigurationProperties(ApplicationContext context, + ObjectMapper mapper) { + ConfigurationBeanFactoryMetadata beanFactoryMetadata = getBeanFactoryMetadata(context); + Map beans = getConfigurationPropertiesBeans(context, beanFactoryMetadata); Map beanDescriptors = new HashMap<>(); beans.forEach((beanName, bean) -> { String prefix = extractPrefix(context, beanFactoryMetadata, beanName); - beanDescriptors.put(beanName, new ConfigurationPropertiesBeanDescriptor( - prefix, sanitize(prefix, safeSerialize(mapper, bean, prefix)))); + beanDescriptors.put(beanName, new ConfigurationPropertiesBeanDescriptor(prefix, + sanitize(prefix, safeSerialize(mapper, bean, prefix)))); }); return new ContextConfigurationProperties(beanDescriptors, (context.getParent() != null) ? context.getParent().getId() : null); } - private ConfigurationBeanFactoryMetadata getBeanFactoryMetadata( - ApplicationContext context) { + private ConfigurationBeanFactoryMetadata getBeanFactoryMetadata(ApplicationContext context) { Map beans = context .getBeansOfType(ConfigurationBeanFactoryMetadata.class); if (beans.size() == 1) { @@ -133,14 +129,12 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext return null; } - private Map getConfigurationPropertiesBeans( - ApplicationContext context, + private Map getConfigurationPropertiesBeans(ApplicationContext context, ConfigurationBeanFactoryMetadata beanFactoryMetadata) { Map beans = new HashMap<>(); beans.putAll(context.getBeansWithAnnotation(ConfigurationProperties.class)); if (beanFactoryMetadata != null) { - beans.putAll(beanFactoryMetadata - .getBeansWithFactoryAnnotation(ConfigurationProperties.class)); + beans.putAll(beanFactoryMetadata.getBeansWithFactoryAnnotation(ConfigurationProperties.class)); } return beans; } @@ -154,14 +148,12 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext * @return the serialized instance */ @SuppressWarnings("unchecked") - private Map safeSerialize(ObjectMapper mapper, Object bean, - String prefix) { + private Map safeSerialize(ObjectMapper mapper, Object bean, String prefix) { try { return new HashMap<>(mapper.convertValue(bean, Map.class)); } catch (Exception ex) { - return new HashMap<>(Collections.singletonMap("error", - "Cannot serialize '" + prefix + "'")); + return new HashMap<>(Collections.singletonMap("error", "Cannot serialize '" + prefix + "'")); } } @@ -200,10 +192,9 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext } private void applyConfigurationPropertiesFilter(ObjectMapper mapper) { - mapper.setAnnotationIntrospector( - new ConfigurationPropertiesAnnotationIntrospector()); - mapper.setFilterProvider(new SimpleFilterProvider() - .setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); + mapper.setAnnotationIntrospector(new ConfigurationPropertiesAnnotationIntrospector()); + mapper.setFilterProvider( + new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); } /** @@ -214,13 +205,12 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext * @param beanName the bean name * @return the prefix */ - private String extractPrefix(ApplicationContext context, - ConfigurationBeanFactoryMetadata beanFactoryMetaData, String beanName) { - ConfigurationProperties annotation = context.findAnnotationOnBean(beanName, - ConfigurationProperties.class); + private String extractPrefix(ApplicationContext context, ConfigurationBeanFactoryMetadata beanFactoryMetaData, + String beanName) { + ConfigurationProperties annotation = context.findAnnotationOnBean(beanName, ConfigurationProperties.class); if (beanFactoryMetaData != null) { - ConfigurationProperties override = beanFactoryMetaData - .findFactoryAnnotation(beanName, ConfigurationProperties.class); + ConfigurationProperties override = beanFactoryMetaData.findFactoryAnnotation(beanName, + ConfigurationProperties.class); if (override != null) { // The @Bean-level @ConfigurationProperties overrides the one at type // level when binding. Arguably we should render them both, but this one @@ -279,8 +269,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext * properties. */ @SuppressWarnings("serial") - private static class ConfigurationPropertiesAnnotationIntrospector - extends JacksonAnnotationIntrospector { + private static class ConfigurationPropertiesAnnotationIntrospector extends JacksonAnnotationIntrospector { @Override public Object findFilterId(Annotated a) { @@ -303,11 +292,9 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext *

  • Properties that throw an exception when retrieving their value. * */ - private static class ConfigurationPropertiesPropertyFilter - extends SimpleBeanPropertyFilter { + private static class ConfigurationPropertiesPropertyFilter extends SimpleBeanPropertyFilter { - private static final Log logger = LogFactory - .getLog(ConfigurationPropertiesPropertyFilter.class); + private static final Log logger = LogFactory.getLog(ConfigurationPropertiesPropertyFilter.class); @Override protected boolean include(BeanPropertyWriter writer) { @@ -324,14 +311,13 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext } @Override - public void serializeAsField(Object pojo, JsonGenerator jgen, - SerializerProvider provider, PropertyWriter writer) throws Exception { + public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, + PropertyWriter writer) throws Exception { if (writer instanceof BeanPropertyWriter) { try { if (pojo == ((BeanPropertyWriter) writer).get(pojo)) { if (logger.isDebugEnabled()) { - logger.debug("Skipping '" + writer.getFullName() + "' on '" - + pojo.getClass().getName() + logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName() + "' as it is self-referential"); } return; @@ -339,9 +325,8 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext } catch (Exception ex) { if (logger.isDebugEnabled()) { - logger.debug("Skipping '" + writer.getFullName() + "' on '" - + pojo.getClass().getName() + "' as an exception " - + "was thrown when retrieving its value", ex); + logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName() + + "' as an exception " + "was thrown when retrieving its value", ex); } return; } @@ -357,8 +342,8 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext protected static class GenericSerializerModifier extends BeanSerializerModifier { @Override - public List changeProperties(SerializationConfig config, - BeanDescription beanDesc, List beanProperties) { + public List changeProperties(SerializationConfig config, BeanDescription beanDesc, + List beanProperties) { List result = new ArrayList<>(); for (BeanPropertyWriter writer : beanProperties) { boolean readable = isReadable(beanDesc, writer); @@ -379,15 +364,11 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext // should be kosher. Lists and Maps are also auto-detected by default since // that's what the metadata generator does. This filter is not used if there // is JSON metadata for the property, so it's mainly for user-defined beans. - return (setter != null) - || ClassUtils.getPackageName(parentType) - .equals(ClassUtils.getPackageName(type)) - || Map.class.isAssignableFrom(type) - || Collection.class.isAssignableFrom(type); + return (setter != null) || ClassUtils.getPackageName(parentType).equals(ClassUtils.getPackageName(type)) + || Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type); } - private AnnotatedMethod findSetter(BeanDescription beanDesc, - BeanPropertyWriter writer) { + private AnnotatedMethod findSetter(BeanDescription beanDesc, BeanPropertyWriter writer) { String name = "set" + determineAccessorSuffix(writer.getName()); Class type = writer.getType().getRawClass(); AnnotatedMethod setter = beanDesc.findMethod(name, new Class[] { type }); @@ -407,8 +388,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext * @return the accessor suffix for {@code propertyName} */ private String determineAccessorSuffix(String propertyName) { - if (propertyName.length() > 1 - && Character.isUpperCase(propertyName.charAt(1))) { + if (propertyName.length() > 1 && Character.isUpperCase(propertyName.charAt(1))) { return propertyName; } return StringUtils.capitalize(propertyName); @@ -425,8 +405,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private final Map contexts; - private ApplicationConfigurationProperties( - Map contexts) { + private ApplicationConfigurationProperties(Map contexts) { this.contexts = contexts; } @@ -447,8 +426,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private final String parentId; - private ContextConfigurationProperties( - Map beans, + private ContextConfigurationProperties(Map beans, String parentId) { this.beans = beans; this.parentId = parentId; @@ -474,8 +452,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private final Map properties; - private ConfigurationPropertiesBeanDescriptor(String prefix, - Map properties) { + private ConfigurationPropertiesBeanDescriptor(String prefix, Map properties) { this.prefix = prefix; this.properties = properties; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java index 945ac375379..ea33c912276 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ class CouchbaseHealth { void applyTo(Builder builder) { builder = isCouchbaseUp(this.diagnostics) ? builder.up() : builder.down(); builder.withDetail("sdk", this.diagnostics.sdk()); - builder.withDetail("endpoints", this.diagnostics.endpoints().stream() - .map(this::describe).collect(Collectors.toList())); + builder.withDetail("endpoints", + this.diagnostics.endpoints().stream().map(this::describe).collect(Collectors.toList())); } private boolean isCouchbaseUp(DiagnosticsReport diagnostics) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicator.java index 347a0fed073..93dac44a3a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicator.java @@ -55,10 +55,8 @@ public class ElasticsearchHealthIndicator extends AbstractHealthIndicator { * @param responseTimeout the request timeout in milliseconds * @param indices the indices to check */ - public ElasticsearchHealthIndicator(Client client, long responseTimeout, - List indices) { - this(client, responseTimeout, - (indices != null) ? StringUtils.toStringArray(indices) : null); + public ElasticsearchHealthIndicator(Client client, long responseTimeout, List indices) { + this(client, responseTimeout, (indices != null) ? StringUtils.toStringArray(indices) : null); } /** @@ -67,8 +65,7 @@ public class ElasticsearchHealthIndicator extends AbstractHealthIndicator { * @param responseTimeout the request timeout in milliseconds * @param indices the indices to check */ - public ElasticsearchHealthIndicator(Client client, long responseTimeout, - String... indices) { + public ElasticsearchHealthIndicator(Client client, long responseTimeout, String... indices) { super("Elasticsearch health check failed"); this.client = client; this.responseTimeout = responseTimeout; @@ -77,10 +74,9 @@ public class ElasticsearchHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - ClusterHealthRequest request = Requests.clusterHealthRequest( - ObjectUtils.isEmpty(this.indices) ? ALL_INDICES : this.indices); - ClusterHealthResponse response = this.client.admin().cluster().health(request) - .actionGet(this.responseTimeout); + ClusterHealthRequest request = Requests + .clusterHealthRequest(ObjectUtils.isEmpty(this.indices) ? ALL_INDICES : this.indices); + ClusterHealthResponse response = this.client.admin().cluster().health(request).actionGet(this.responseTimeout); switch (response.getStatus()) { case GREEN: case YELLOW: diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicator.java index 47c22824d01..47c55c6d71a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,15 +48,13 @@ public class ElasticsearchJestHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - JestResult healthResult = this.jestClient - .execute(new io.searchbox.cluster.Health.Builder().build()); + JestResult healthResult = this.jestClient.execute(new io.searchbox.cluster.Health.Builder().build()); if (healthResult.getResponseCode() != 200 || !healthResult.isSucceeded()) { builder.down(); builder.withDetail("statusCode", healthResult.getResponseCode()); } else { - Map response = this.jsonParser - .parseMap(healthResult.getJsonString()); + Map response = this.jsonParser.parseMap(healthResult.getJsonString()); String status = (String) response.get("status"); if (status.equals(io.searchbox.cluster.Health.Status.RED.getKey())) { builder.outOfService(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicator.java index de3549a581b..79626acd320 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicator.java @@ -57,8 +57,7 @@ public class ElasticsearchRestHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - Response response = this.client - .performRequest(new Request("GET", "/_cluster/health/")); + Response response = this.client.performRequest(new Request("GET", "/_cluster/health/")); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { builder.down(); @@ -67,8 +66,7 @@ public class ElasticsearchRestHealthIndicator extends AbstractHealthIndicator { return; } try (InputStream inputStream = response.getEntity().getContent()) { - doHealthCheck(builder, - StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8)); + doHealthCheck(builder, StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java index 950a783d7a8..e00161c3135 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.util.Assert; * @author Phillip Webb * @since 2.0.0 */ -public abstract class AbstractExposableEndpoint - implements ExposableEndpoint { +public abstract class AbstractExposableEndpoint implements ExposableEndpoint { private final EndpointId id; @@ -45,8 +44,7 @@ public abstract class AbstractExposableEndpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations */ - public AbstractExposableEndpoint(EndpointId id, boolean enabledByDefault, - Collection operations) { + public AbstractExposableEndpoint(EndpointId id, boolean enabledByDefault, Collection operations) { Assert.notNull(id, "ID must not be null"); Assert.notNull(operations, "Operations must not be null"); this.id = id; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointId.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointId.java index 42ee1a2ef14..b39d33e5420 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointId.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointId.java @@ -52,12 +52,9 @@ public final class EndpointId { private EndpointId(String value) { Assert.hasText(value, "Value must not be empty"); - Assert.isTrue(VALID_PATTERN.matcher(value).matches(), - "Value must only contain valid chars"); - Assert.isTrue(!Character.isDigit(value.charAt(0)), - "Value must not start with a number"); - Assert.isTrue(!Character.isUpperCase(value.charAt(0)), - "Value must not start with an uppercase letter"); + Assert.isTrue(VALID_PATTERN.matcher(value).matches(), "Value must only contain valid chars"); + Assert.isTrue(!Character.isDigit(value.charAt(0)), "Value must not start with a number"); + Assert.isTrue(!Character.isUpperCase(value.charAt(0)), "Value must not start with an uppercase letter"); if (WARNING_PATTERN.matcher(value).find()) { logWarning(value); } @@ -85,8 +82,7 @@ public final class EndpointId { if (obj == null || getClass() != obj.getClass()) { return false; } - return this.lowerCaseAlphaNumeric - .equals(((EndpointId) obj).lowerCaseAlphaNumeric); + return this.lowerCaseAlphaNumeric.equals(((EndpointId) obj).lowerCaseAlphaNumeric); } @Override @@ -132,8 +128,7 @@ public final class EndpointId { private static void logWarning(String value) { if (logger.isWarnEnabled() && loggedWarnings.add(value)) { - logger.warn("Endpoint ID '" + value - + "' contains invalid characters, please migrate to a valid format."); + logger.warn("Endpoint ID '" + value + "' contains invalid characters, please migrate to a valid format."); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvalidEndpointRequestException.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvalidEndpointRequestException.java index c6384b061fa..af2898febd7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvalidEndpointRequestException.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvalidEndpointRequestException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ public class InvalidEndpointRequestException extends RuntimeException { this.reason = reason; } - public InvalidEndpointRequestException(String message, String reason, - Throwable cause) { + public InvalidEndpointRequestException(String message, String reason, Throwable cause) { super(message, cause); this.reason = reason; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvocationContext.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvocationContext.java index 88fa35ab58b..1ea4430f6ff 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvocationContext.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/InvocationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public class InvocationContext { * @param securityContext the current security context. Never {@code null} * @param arguments the arguments available to the operation. Never {@code null} */ - public InvocationContext(SecurityContext securityContext, - Map arguments) { + public InvocationContext(SecurityContext securityContext, Map arguments) { Assert.notNull(securityContext, "SecurityContext must not be null"); Assert.notNull(arguments, "Arguments must not be null"); this.securityContext = securityContext; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java index 36b2721dabc..386b916df96 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ public class Sanitizer { private Pattern[] keysToSanitize; public Sanitizer() { - this("password", "secret", "key", "token", ".*credentials.*", "vcap_services", - "sun.java.command"); + this("password", "secret", "key", "token", ".*credentials.*", "vcap_services", "sun.java.command"); } public Sanitizer(String... keysToSanitize) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java index 4c73e51f955..9c053d306d7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ import org.springframework.util.Assert; * @author Phillip Webb * @since 2.0.0 */ -public abstract class AbstractDiscoveredEndpoint - extends AbstractExposableEndpoint implements DiscoveredEndpoint { +public abstract class AbstractDiscoveredEndpoint extends AbstractExposableEndpoint + implements DiscoveredEndpoint { private final EndpointDiscoverer discoverer; @@ -48,9 +48,8 @@ public abstract class AbstractDiscoveredEndpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations */ - public AbstractDiscoveredEndpoint(EndpointDiscoverer discoverer, - Object endpointBean, EndpointId id, boolean enabledByDefault, - Collection operations) { + public AbstractDiscoveredEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, + boolean enabledByDefault, Collection operations) { super(id, enabledByDefault, operations); Assert.notNull(discoverer, "Discoverer must not be null"); Assert.notNull(endpointBean, "EndpointBean must not be null"); @@ -70,8 +69,7 @@ public abstract class AbstractDiscoveredEndpoint @Override public String toString() { - ToStringCreator creator = new ToStringCreator(this) - .append("discoverer", this.discoverer.getClass().getName()) + ToStringCreator creator = new ToStringCreator(this).append("discoverer", this.discoverer.getClass().getName()) .append("endpointBean", this.endpointBean.getClass().getName()); appendFields(creator); return creator.toString(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java index 815bd7d581b..cfc7a0f184a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public abstract class AbstractDiscoveredOperation implements Operation { * @param operationMethod the method backing the operation * @param invoker the operation invoker to use */ - public AbstractDiscoveredOperation(DiscoveredOperationMethod operationMethod, - OperationInvoker invoker) { + public AbstractDiscoveredOperation(DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { this.operationMethod = operationMethod; this.invoker = invoker; } @@ -63,8 +62,7 @@ public abstract class AbstractDiscoveredOperation implements Operation { @Override public String toString() { - ToStringCreator creator = new ToStringCreator(this) - .append("operationMethod", this.operationMethod) + ToStringCreator creator = new ToStringCreator(this).append("operationMethod", this.operationMethod) .append("invoker", this.invoker); appendFields(creator); return creator.toString(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java index 98049f92eee..4414c80b227 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java @@ -51,8 +51,7 @@ abstract class DiscoveredOperationsFactory { private static final Map> OPERATION_TYPES; static { - Map> operationTypes = new EnumMap<>( - OperationType.class); + Map> operationTypes = new EnumMap<>(OperationType.class); operationTypes.put(OperationType.READ, ReadOperation.class); operationTypes.put(OperationType.WRITE, WriteOperation.class); operationTypes.put(OperationType.DELETE, DeleteOperation.class); @@ -70,45 +69,42 @@ abstract class DiscoveredOperationsFactory { } public Collection createOperations(EndpointId id, Object target) { - return MethodIntrospector.selectMethods(target.getClass(), - (MetadataLookup) (method) -> createOperation(id, target, method)) + return MethodIntrospector + .selectMethods(target.getClass(), (MetadataLookup) (method) -> createOperation(id, target, method)) .values(); } private O createOperation(EndpointId endpointId, Object target, Method method) { return OPERATION_TYPES.entrySet().stream() - .map((entry) -> createOperation(endpointId, target, method, - entry.getKey(), entry.getValue())) + .map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue())) .filter(Objects::nonNull).findFirst().orElse(null); } - private O createOperation(EndpointId endpointId, Object target, Method method, - OperationType operationType, Class annotationType) { - MergedAnnotation annotation = MergedAnnotations.from(method) - .get(annotationType); + private O createOperation(EndpointId endpointId, Object target, Method method, OperationType operationType, + Class annotationType) { + MergedAnnotation annotation = MergedAnnotations.from(method).get(annotationType); if (!annotation.isPresent()) { return null; } - DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, - operationType, annotation.asAnnotationAttributes()); - OperationInvoker invoker = new ReflectiveOperationInvoker(target, operationMethod, - this.parameterValueMapper); + DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, operationType, + annotation.asAnnotationAttributes()); + OperationInvoker invoker = new ReflectiveOperationInvoker(target, operationMethod, this.parameterValueMapper); invoker = applyAdvisors(endpointId, operationMethod, invoker); return createOperation(endpointId, operationMethod, invoker); } - private OperationInvoker applyAdvisors(EndpointId endpointId, - OperationMethod operationMethod, OperationInvoker invoker) { + private OperationInvoker applyAdvisors(EndpointId endpointId, OperationMethod operationMethod, + OperationInvoker invoker) { if (this.invokerAdvisors != null) { for (OperationInvokerAdvisor advisor : this.invokerAdvisors) { - invoker = advisor.apply(endpointId, operationMethod.getOperationType(), - operationMethod.getParameters(), invoker); + invoker = advisor.apply(endpointId, operationMethod.getOperationType(), operationMethod.getParameters(), + invoker); } } return invoker; } - protected abstract O createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker); + protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilter.java index 78b446e0d06..4d707536e11 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.util.Assert; * * @author Phillip Webb */ -public abstract class DiscovererEndpointFilter - implements EndpointFilter> { +public abstract class DiscovererEndpointFilter implements EndpointFilter> { private final Class> discoverer; @@ -34,8 +33,7 @@ public abstract class DiscovererEndpointFilter * Create a new {@link DiscovererEndpointFilter} instance. * @param discoverer the required discoverer */ - protected DiscovererEndpointFilter( - Class> discoverer) { + protected DiscovererEndpointFilter(Class> discoverer) { Assert.notNull(discoverer, "Discoverer must not be null"); this.discoverer = discoverer; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java index 263139fb307..59f87af8072 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java @@ -85,30 +85,25 @@ public abstract class EndpointDiscoverer, O exten * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ - public EndpointDiscoverer(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, - Collection invokerAdvisors, - Collection> filters) { + public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, + Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); - this.operationsFactory = getOperationsFactory(parameterValueMapper, - invokerAdvisors); + this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } - private DiscoveredOperationsFactory getOperationsFactory( - ParameterValueMapper parameterValueMapper, + private DiscoveredOperationsFactory getOperationsFactory(ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override - protected O createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { - return EndpointDiscoverer.this.createOperation(endpointId, - operationMethod, invoker); + protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { + return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; @@ -130,17 +125,14 @@ public abstract class EndpointDiscoverer, O exten private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); - String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( - this.applicationContext, Endpoint.class); + String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.applicationContext, + Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); - EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), - endpointBean); - Assert.state(previous == null, - () -> "Found two endpoints with the id '" + endpointBean.getId() - + "': '" + endpointBean.getBeanName() + "' and '" - + previous.getBeanName() + "'"); + EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); + Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); @@ -154,15 +146,13 @@ public abstract class EndpointDiscoverer, O exten private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); - String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( - this.applicationContext, EndpointExtension.class); + String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.applicationContext, + EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); - Assert.state(endpointBean != null, - () -> ("Invalid extension '" + extensionBean.getBeanName() - + "': no endpoint found with id '" - + extensionBean.getEndpointId() + "'")); + Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } @@ -172,13 +162,10 @@ public abstract class EndpointDiscoverer, O exten return new ExtensionBean(beanName, bean); } - private void addExtensionBean(EndpointBean endpointBean, - ExtensionBean extensionBean) { + private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { - Assert.state( - isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), - () -> "Endpoint bean '" + endpointBean.getBeanName() - + "' cannot support the extension bean '" + Assert.state(isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), + () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } @@ -199,25 +186,22 @@ public abstract class EndpointDiscoverer, O exten EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { - String extensionBeans = endpointBean.getExtensions().stream() - .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); - throw new IllegalStateException( - "Found multiple extensions for the endpoint bean " - + endpointBean.getBeanName() + " (" + extensionBeans + ")"); + String extensionBeans = endpointBean.getExtensions().stream().map(ExtensionBean::getBeanName) + .collect(Collectors.joining(", ")); + throw new IllegalStateException("Found multiple extensions for the endpoint bean " + + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); - List operations = indexed.values().stream().map(this::getLast) - .filter(Objects::nonNull).collect(Collectors.collectingAndThen( - Collectors.toList(), Collections::unmodifiableList)); - return createEndpoint(endpointBean.getBean(), id, - endpointBean.isEnabledByDefault(), operations); + List operations = indexed.values().stream().map(this::getLast).filter(Objects::nonNull) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); + return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } - private void addOperations(MultiValueMap indexed, EndpointId id, - Object target, boolean replaceLast) { + private void addOperations(MultiValueMap indexed, EndpointId id, Object target, + boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { @@ -234,27 +218,21 @@ public abstract class EndpointDiscoverer, O exten return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } - private void assertNoDuplicateOperations(EndpointBean endpointBean, - MultiValueMap indexed) { - List duplicates = indexed.entrySet().stream() - .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) - .collect(Collectors.toList()); + private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { + List duplicates = indexed.entrySet().stream().filter((entry) -> entry.getValue().size() > 1) + .map(Map.Entry::getKey).collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); - String extensionBeanNames = extensions.stream() - .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); - throw new IllegalStateException( - "Unable to map duplicate endpoint operations: " - + duplicates.toString() + " to " + endpointBean.getBeanName() - + (extensions.isEmpty() ? "" - : " (" + extensionBeanNames + ")")); + String extensionBeanNames = extensions.stream().map(ExtensionBean::getBeanName) + .collect(Collectors.joining(", ")); + throw new IllegalStateException("Unable to map duplicate endpoint operations: " + duplicates.toString() + + " to " + endpointBean.getBeanName() + + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } - private boolean isExtensionExposed(EndpointBean endpointBean, - ExtensionBean extensionBean) { - return isFilterMatch(extensionBean.getFilter(), endpointBean) - && isExtensionExposed(extensionBean.getBean()); + private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { + return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** @@ -268,8 +246,7 @@ public abstract class EndpointDiscoverer, O exten } private boolean isEndpointExposed(EndpointBean endpointBean) { - return isFilterMatch(endpointBean.getFilter(), endpointBean) - && !isEndpointFiltered(endpointBean) + return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } @@ -301,11 +278,9 @@ public abstract class EndpointDiscoverer, O exten return true; } E endpoint = getFilterEndpoint(endpointBean); - Class generic = ResolvableType.forClass(EndpointFilter.class, filter) - .resolveGeneric(0); + Class generic = ResolvableType.forClass(EndpointFilter.class, filter).resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { - EndpointFilter instance = (EndpointFilter) BeanUtils - .instantiateClass(filter); + EndpointFilter instance = (EndpointFilter) BeanUtils.instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; @@ -318,16 +293,15 @@ public abstract class EndpointDiscoverer, O exten @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { - return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) - .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) - .get(); + return LambdaSafe.callback(EndpointFilter.class, filter, endpoint).withLogger(EndpointDiscoverer.class) + .invokeAnd((f) -> f.match(endpoint)).get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { - endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), - endpointBean.isEnabledByDefault(), Collections.emptySet()); + endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), + Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; @@ -335,8 +309,7 @@ public abstract class EndpointDiscoverer, O exten @SuppressWarnings("unchecked") protected Class getEndpointType() { - return (Class) ResolvableType - .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); + return (Class) ResolvableType.forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** @@ -347,8 +320,8 @@ public abstract class EndpointDiscoverer, O exten * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ - protected abstract E createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations); + protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, + Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. @@ -357,8 +330,8 @@ public abstract class EndpointDiscoverer, O exten * @param invoker the invoker to use * @return a created operation */ - protected abstract O createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker); + protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. @@ -430,12 +403,11 @@ public abstract class EndpointDiscoverer, O exten private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { - MergedAnnotation annotation = MergedAnnotations - .from(bean.getClass(), SearchStrategy.EXHAUSTIVE).get(Endpoint.class); + MergedAnnotation annotation = MergedAnnotations.from(bean.getClass(), SearchStrategy.EXHAUSTIVE) + .get(Endpoint.class); String id = annotation.getString("id"); Assert.state(StringUtils.hasText(id), - () -> "No @Endpoint id attribute specified for " - + bean.getClass().getName()); + () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); @@ -494,13 +466,13 @@ public abstract class EndpointDiscoverer, O exten ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; - MergedAnnotation extensionAnnotation = MergedAnnotations - .from(bean.getClass()).get(EndpointExtension.class); + MergedAnnotation extensionAnnotation = MergedAnnotations.from(bean.getClass()) + .get(EndpointExtension.class); Class endpointType = extensionAnnotation.getClass("endpoint"); MergedAnnotation endpointAnnotation = MergedAnnotations .from(endpointType, SearchStrategy.EXHAUSTIVE).get(Endpoint.class); - Assert.state(endpointAnnotation.isPresent(), () -> "Extension " - + endpointType.getName() + " does not specify an endpoint"); + Assert.state(endpointAnnotation.isPresent(), + () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAnnotation.getString("id")); this.filter = extensionAnnotation.getClass("filter"); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/MissingParametersException.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/MissingParametersException.java index d09169aa7f9..5d7e839fc53 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/MissingParametersException.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/MissingParametersException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,12 +35,10 @@ public final class MissingParametersException extends InvalidEndpointRequestExce private final Set missingParameters; public MissingParametersException(Set missingParameters) { - super("Failed to invoke operation because the following required " - + "parameters were missing: " + super("Failed to invoke operation because the following required " + "parameters were missing: " + StringUtils.collectionToCommaDelimitedString(missingParameters), "Missing parameters: " - + missingParameters.stream().map(OperationParameter::getName) - .collect(Collectors.joining(","))); + + missingParameters.stream().map(OperationParameter::getName).collect(Collectors.joining(","))); this.missingParameters = missingParameters; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/OperationInvokerAdvisor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/OperationInvokerAdvisor.java index 9f52d64f183..acd50214718 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/OperationInvokerAdvisor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/OperationInvokerAdvisor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ public interface OperationInvokerAdvisor { * @param invoker the invoker to advise * @return an potentially new operation invoker with support for additional features */ - OperationInvoker apply(EndpointId endpointId, OperationType operationType, - OperationParameters parameters, OperationInvoker invoker); + OperationInvoker apply(EndpointId endpointId, OperationType operationType, OperationParameters parameters, + OperationInvoker invoker); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterMappingException.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterMappingException.java index 6cca7ff0f52..0b3d8d49ea4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterMappingException.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterMappingException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,10 +38,9 @@ public final class ParameterMappingException extends InvalidEndpointRequestExcep * @param value the value being mapped * @param cause the cause of the mapping failure */ - public ParameterMappingException(OperationParameter parameter, Object value, - Throwable cause) { - super("Failed to map " + value + " of type " + value.getClass() + " to " - + parameter, "Parameter mapping failure", cause); + public ParameterMappingException(OperationParameter parameter, Object value, Throwable cause) { + super("Failed to map " + value + " of type " + value.getClass() + " to " + parameter, + "Parameter mapping failure", cause); this.parameter = parameter; this.value = value; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterValueMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterValueMapper.java index 69222218e02..991682f40fe 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterValueMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/ParameterValueMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,6 @@ public interface ParameterValueMapper { * @return a value suitable for that parameter * @throws ParameterMappingException when a mapping failure occurs */ - Object mapParameterValue(OperationParameter parameter, Object value) - throws ParameterMappingException; + Object mapParameterValue(OperationParameter parameter, Object value) throws ParameterMappingException; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapper.java index 24474623ae6..3d185879ed5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ public class ConversionServiceParameterValueMapper implements ParameterValueMapp } @Override - public Object mapParameterValue(OperationParameter parameter, Object value) - throws ParameterMappingException { + public Object mapParameterValue(OperationParameter parameter, Object value) throws ParameterMappingException { try { return this.conversionService.convert(value, parameter.getType()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java index 538f4258742..242de67e743 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ public class OperationMethod { Assert.notNull(operationType, "OperationType must not be null"); this.method = method; this.operationType = operationType; - this.operationParameters = new OperationMethodParameters(method, - DEFAULT_PARAMETER_NAME_DISCOVERER); + this.operationParameters = new OperationMethodParameters(method, DEFAULT_PARAMETER_NAME_DISCOVERER); } /** @@ -82,8 +81,7 @@ public class OperationMethod { @Override public String toString() { - return "Operation " + this.operationType.name().toLowerCase(Locale.ENGLISH) - + " method " + this.method; + return "Operation " + this.operationType.name().toLowerCase(Locale.ENGLISH) + " method " + this.method; } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameters.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameters.java index aeca8ba67df..d81826a8603 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameters.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,24 +43,19 @@ class OperationMethodParameters implements OperationParameters { * @param method the source method * @param parameterNameDiscoverer the parameter name discoverer */ - OperationMethodParameters(Method method, - ParameterNameDiscoverer parameterNameDiscoverer) { + OperationMethodParameters(Method method, ParameterNameDiscoverer parameterNameDiscoverer) { Assert.notNull(method, "Method must not be null"); - Assert.notNull(parameterNameDiscoverer, - "ParameterNameDiscoverer must not be null"); + Assert.notNull(parameterNameDiscoverer, "ParameterNameDiscoverer must not be null"); String[] parameterNames = parameterNameDiscoverer.getParameterNames(method); Parameter[] parameters = method.getParameters(); - Assert.state(parameterNames != null, - () -> "Failed to extract parameter names for " + method); + Assert.state(parameterNames != null, () -> "Failed to extract parameter names for " + method); this.operationParameters = getOperationParameters(parameters, parameterNames); } - private List getOperationParameters(Parameter[] parameters, - String[] names) { + private List getOperationParameters(Parameter[] parameters, String[] names) { List operationParameters = new ArrayList<>(parameters.length); for (int i = 0; i < names.length; i++) { - operationParameters - .add(new OperationMethodParameter(names[i], parameters[i])); + operationParameters.add(new OperationMethodParameter(names[i], parameters[i])); } return Collections.unmodifiableList(operationParameters); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java index 43f7f9f16aa..dbb74b3ce3e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java @@ -78,8 +78,7 @@ public class ReflectiveOperationInvoker implements OperationInvoker { private void validateRequiredParameters(InvocationContext context) { Set missing = this.operationMethod.getParameters().stream() - .filter((parameter) -> isMissing(context, parameter)) - .collect(Collectors.toSet()); + .filter((parameter) -> isMissing(context, parameter)).collect(Collectors.toSet()); if (!missing.isEmpty()) { throw new MissingParametersException(missing); } @@ -99,12 +98,11 @@ public class ReflectiveOperationInvoker implements OperationInvoker { } private Object[] resolveArguments(InvocationContext context) { - return this.operationMethod.getParameters().stream() - .map((parameter) -> resolveArgument(parameter, context)).toArray(); + return this.operationMethod.getParameters().stream().map((parameter) -> resolveArgument(parameter, context)) + .toArray(); } - private Object resolveArgument(OperationParameter parameter, - InvocationContext context) { + private Object resolveArgument(OperationParameter parameter, InvocationContext context) { if (Principal.class.equals(parameter.getType())) { return context.getSecurityContext().getPrincipal(); } @@ -117,8 +115,8 @@ public class ReflectiveOperationInvoker implements OperationInvoker { @Override public String toString() { - return new ToStringCreator(this).append("target", this.target) - .append("method", this.operationMethod).toString(); + return new ToStringCreator(this).append("target", this.target).append("method", this.operationMethod) + .toString(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisor.java index 39be014a011..b62320b8933 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,14 +36,13 @@ public class CachingOperationInvokerAdvisor implements OperationInvokerAdvisor { private final Function endpointIdTimeToLive; - public CachingOperationInvokerAdvisor( - Function endpointIdTimeToLive) { + public CachingOperationInvokerAdvisor(Function endpointIdTimeToLive) { this.endpointIdTimeToLive = endpointIdTimeToLive; } @Override - public OperationInvoker apply(EndpointId endpointId, OperationType operationType, - OperationParameters parameters, OperationInvoker invoker) { + public OperationInvoker apply(EndpointId endpointId, OperationType operationType, OperationParameters parameters, + OperationInvoker invoker) { if (operationType == OperationType.READ && !hasMandatoryParameter(parameters)) { Long timeToLive = this.endpointIdTimeToLive.apply(endpointId); if (timeToLive != null && timeToLive > 0) { @@ -55,8 +54,7 @@ public class CachingOperationInvokerAdvisor implements OperationInvokerAdvisor { private boolean hasMandatoryParameter(OperationParameters parameters) { for (OperationParameter parameter : parameters) { - if (parameter.isMandatory() - && !SecurityContext.class.isAssignableFrom(parameter.getType())) { + if (parameter.isMandatory() && !SecurityContext.class.isAssignableFrom(parameter.getType())) { return true; } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java index da22ee38166..5ac08e150e9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,8 @@ import org.springframework.util.ClassUtils; */ public class EndpointMBean implements DynamicMBean { - private static final boolean REACTOR_PRESENT = ClassUtils.isPresent( - "reactor.core.publisher.Mono", EndpointMBean.class.getClassLoader()); + private static final boolean REACTOR_PRESENT = ClassUtils.isPresent("reactor.core.publisher.Mono", + EndpointMBean.class.getClassLoader()); private final JmxOperationResponseMapper responseMapper; @@ -61,8 +61,7 @@ public class EndpointMBean implements DynamicMBean { private final Map operations; - EndpointMBean(JmxOperationResponseMapper responseMapper, ClassLoader classLoader, - ExposableJmxEndpoint endpoint) { + EndpointMBean(JmxOperationResponseMapper responseMapper, ClassLoader classLoader, ExposableJmxEndpoint endpoint) { Assert.notNull(responseMapper, "ResponseMapper must not be null"); Assert.notNull(endpoint, "Endpoint must not be null"); this.responseMapper = responseMapper; @@ -74,8 +73,7 @@ public class EndpointMBean implements DynamicMBean { private Map getOperations(ExposableJmxEndpoint endpoint) { Map operations = new HashMap<>(); - endpoint.getOperations() - .forEach((operation) -> operations.put(operation.getName(), operation)); + endpoint.getOperations().forEach((operation) -> operations.put(operation.getName(), operation)); return Collections.unmodifiableMap(operations); } @@ -89,12 +87,11 @@ public class EndpointMBean implements DynamicMBean { throws MBeanException, ReflectionException { JmxOperation operation = this.operations.get(actionName); if (operation == null) { - String message = "Endpoint with id '" + this.endpoint.getEndpointId() - + "' has no operation named " + actionName; + String message = "Endpoint with id '" + this.endpoint.getEndpointId() + "' has no operation named " + + actionName; throw new ReflectionException(new IllegalArgumentException(message), message); } - ClassLoader previousClassLoader = overrideThreadContextClassLoader( - this.classLoader); + ClassLoader previousClassLoader = overrideThreadContextClassLoader(this.classLoader); try { return invoke(operation, params); } @@ -115,14 +112,12 @@ public class EndpointMBean implements DynamicMBean { return null; } - private Object invoke(JmxOperation operation, Object[] params) - throws MBeanException, ReflectionException { + private Object invoke(JmxOperation operation, Object[] params) throws MBeanException, ReflectionException { try { - String[] parameterNames = operation.getParameters().stream() - .map(JmxOperationParameter::getName).toArray(String[]::new); + String[] parameterNames = operation.getParameters().stream().map(JmxOperationParameter::getName) + .toArray(String[]::new); Map arguments = getArguments(parameterNames, params); - InvocationContext context = new InvocationContext(SecurityContext.NONE, - arguments); + InvocationContext context = new InvocationContext(SecurityContext.NONE, arguments); Object result = operation.invoke(context); if (REACTOR_PRESENT) { result = ReactiveHandler.handle(result); @@ -130,8 +125,7 @@ public class EndpointMBean implements DynamicMBean { return this.responseMapper.mapResponse(result); } catch (InvalidEndpointRequestException ex) { - throw new ReflectionException(new IllegalArgumentException(ex.getMessage()), - ex.getMessage()); + throw new ReflectionException(new IllegalArgumentException(ex.getMessage()), ex.getMessage()); } catch (Exception ex) { throw new MBeanException(translateIfNecessary(ex), ex.getMessage()); @@ -160,8 +154,8 @@ public class EndpointMBean implements DynamicMBean { } @Override - public void setAttribute(Attribute attribute) throws AttributeNotFoundException, - InvalidAttributeValueException, MBeanException, ReflectionException { + public void setAttribute(Attribute attribute) + throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { throw new AttributeNotFoundException("EndpointMBeans do not support attributes"); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointObjectNameFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointObjectNameFactory.java index 2a7759a80b4..937d1ccc1dc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointObjectNameFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointObjectNameFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,6 @@ public interface EndpointObjectNameFactory { * @return the {@link ObjectName} to use for the endpoint * @throws MalformedObjectNameException if the object name is invalid */ - ObjectName getObjectName(ExposableJmxEndpoint endpoint) - throws MalformedObjectNameException; + ObjectName getObjectName(ExposableJmxEndpoint endpoint) throws MalformedObjectNameException; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java index 3e93a83fc7d..39ff94db1fa 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,9 @@ public class JacksonJmxOperationResponseMapper implements JmxOperationResponseMa public JacksonJmxOperationResponseMapper(ObjectMapper objectMapper) { this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper(); - this.listType = this.objectMapper.getTypeFactory() - .constructParametricType(List.class, Object.class); - this.mapType = this.objectMapper.getTypeFactory() - .constructParametricType(Map.class, String.class, Object.class); + this.listType = this.objectMapper.getTypeFactory().constructParametricType(List.class, Object.class); + this.mapType = this.objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, + Object.class); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporter.java index 8731d8377fe..68598d842a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ import org.springframework.util.Assert; * @author Phillip Webb * @since 2.0.0 */ -public class JmxEndpointExporter - implements InitializingBean, DisposableBean, BeanClassLoaderAware { +public class JmxEndpointExporter implements InitializingBean, DisposableBean, BeanClassLoaderAware { private static final Log logger = LogFactory.getLog(JmxEndpointExporter.class); @@ -60,10 +59,8 @@ public class JmxEndpointExporter private Collection registered; - public JmxEndpointExporter(MBeanServer mBeanServer, - EndpointObjectNameFactory objectNameFactory, - JmxOperationResponseMapper responseMapper, - Collection endpoints) { + public JmxEndpointExporter(MBeanServer mBeanServer, EndpointObjectNameFactory objectNameFactory, + JmxOperationResponseMapper responseMapper, Collection endpoints) { Assert.notNull(mBeanServer, "MBeanServer must not be null"); Assert.notNull(objectNameFactory, "ObjectNameFactory must not be null"); Assert.notNull(responseMapper, "ResponseMapper must not be null"); @@ -97,19 +94,15 @@ public class JmxEndpointExporter Assert.notNull(endpoint, "Endpoint must not be null"); try { ObjectName name = this.objectNameFactory.getObjectName(endpoint); - EndpointMBean mbean = new EndpointMBean(this.responseMapper, this.classLoader, - endpoint); + EndpointMBean mbean = new EndpointMBean(this.responseMapper, this.classLoader, endpoint); this.mBeanServer.registerMBean(mbean, name); return name; } catch (MalformedObjectNameException ex) { - throw new IllegalStateException( - "Invalid ObjectName for " + getEndpointDescription(endpoint), ex); + throw new IllegalStateException("Invalid ObjectName for " + getEndpointDescription(endpoint), ex); } catch (Exception ex) { - throw new MBeanExportException( - "Failed to register MBean for " + getEndpointDescription(endpoint), - ex); + throw new MBeanExportException("Failed to register MBean for " + getEndpointDescription(endpoint), ex); } } @@ -120,8 +113,7 @@ public class JmxEndpointExporter private void unregister(ObjectName objectName) { try { if (logger.isDebugEnabled()) { - logger.debug("Unregister endpoint with ObjectName '" + objectName + "' " - + "from the JMX domain"); + logger.debug("Unregister endpoint with ObjectName '" + objectName + "' " + "from the JMX domain"); } this.mBeanServer.unregisterMBean(objectName); } @@ -129,9 +121,7 @@ public class JmxEndpointExporter // Ignore and continue } catch (MBeanRegistrationException ex) { - throw new JmxException( - "Failed to unregister MBean with ObjectName '" + objectName + "'", - ex); + throw new JmxException("Failed to unregister MBean with ObjectName '" + objectName + "'", ex); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactory.java index c39c8ae6da1..3ad39b1850b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,8 @@ class MBeanInfoFactory { String className = EndpointMBean.class.getName(); String description = getDescription(endpoint); ModelMBeanOperationInfo[] operations = getMBeanOperations(endpoint); - return new ModelMBeanInfoSupport(className, description, NO_ATTRIBUTES, - NO_CONSTRUCTORS, operations, NO_NOTIFICATIONS); + return new ModelMBeanInfoSupport(className, description, NO_ATTRIBUTES, NO_CONSTRUCTORS, operations, + NO_NOTIFICATIONS); } private String getDescription(ExposableJmxEndpoint endpoint) { @@ -62,8 +62,7 @@ class MBeanInfoFactory { } private ModelMBeanOperationInfo[] getMBeanOperations(ExposableJmxEndpoint endpoint) { - return endpoint.getOperations().stream().map(this::getMBeanOperation) - .toArray(ModelMBeanOperationInfo[]::new); + return endpoint.getOperations().stream().map(this::getMBeanOperation).toArray(ModelMBeanOperationInfo[]::new); } private ModelMBeanOperationInfo getMBeanOperation(JmxOperation operation) { @@ -76,21 +75,18 @@ class MBeanInfoFactory { } private MBeanParameterInfo[] getSignature(List parameters) { - return parameters.stream().map(this::getMBeanParameter) - .toArray(MBeanParameterInfo[]::new); + return parameters.stream().map(this::getMBeanParameter).toArray(MBeanParameterInfo[]::new); } private MBeanParameterInfo getMBeanParameter(JmxOperationParameter parameter) { - return new MBeanParameterInfo(parameter.getName(), parameter.getType().getName(), - parameter.getDescription()); + return new MBeanParameterInfo(parameter.getName(), parameter.getType().getName(), parameter.getDescription()); } private int getImpact(OperationType operationType) { if (operationType == OperationType.READ) { return MBeanOperationInfo.INFO; } - if (operationType == OperationType.WRITE - || operationType == OperationType.DELETE) { + if (operationType == OperationType.WRITE || operationType == OperationType.DELETE) { return MBeanOperationInfo.ACTION; } return MBeanOperationInfo.UNKNOWN; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxEndpoint.java index 6b6cfa12569..3cea7f19575 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,12 +29,10 @@ import org.springframework.boot.actuate.endpoint.jmx.JmxOperation; * * @author Phillip Webb */ -class DiscoveredJmxEndpoint extends AbstractDiscoveredEndpoint - implements ExposableJmxEndpoint { +class DiscoveredJmxEndpoint extends AbstractDiscoveredEndpoint implements ExposableJmxEndpoint { - DiscoveredJmxEndpoint(EndpointDiscoverer discoverer, Object endpointBean, - EndpointId id, boolean enabledByDefault, - Collection operations) { + DiscoveredJmxEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, + boolean enabledByDefault, Collection operations) { super(discoverer, endpointBean, id, enabledByDefault, operations); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java index 106f1110f9e..8c6ec7448ac 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java @@ -60,14 +60,12 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO private final List parameters; - DiscoveredJmxOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + DiscoveredJmxOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { super(operationMethod, invoker); Method method = operationMethod.getMethod(); this.name = method.getName(); this.outputType = JmxType.get(method.getReturnType()); - this.description = getDescription(method, - () -> "Invoke " + this.name + " for endpoint " + endpointId); + this.description = getDescription(method, () -> "Invoke " + this.name + " for endpoint " + endpointId); this.parameters = getParameters(operationMethod); } @@ -84,29 +82,24 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO return Collections.emptyList(); } Method method = operationMethod.getMethod(); - ManagedOperationParameter[] managed = jmxAttributeSource - .getManagedOperationParameters(method); + ManagedOperationParameter[] managed = jmxAttributeSource.getManagedOperationParameters(method); if (managed.length == 0) { - return asList(operationMethod.getParameters().stream() - .map(DiscoveredJmxOperationParameter::new)); + return asList(operationMethod.getParameters().stream().map(DiscoveredJmxOperationParameter::new)); } return mergeParameters(operationMethod.getParameters(), managed); } - private List mergeParameters( - OperationParameters operationParameters, + private List mergeParameters(OperationParameters operationParameters, ManagedOperationParameter[] managedParameters) { List merged = new ArrayList<>(managedParameters.length); for (int i = 0; i < managedParameters.length; i++) { - merged.add(new DiscoveredJmxOperationParameter(managedParameters[i], - operationParameters.get(i))); + merged.add(new DiscoveredJmxOperationParameter(managedParameters[i], operationParameters.get(i))); } return Collections.unmodifiableList(merged); } private List asList(Stream stream) { - return stream.collect(Collectors.collectingAndThen(Collectors.toList(), - Collections::unmodifiableList)); + return stream.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override @@ -131,16 +124,14 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO @Override protected void appendFields(ToStringCreator creator) { - creator.append("name", this.name).append("outputType", this.outputType) - .append("description", this.description) + creator.append("name", this.name).append("outputType", this.outputType).append("description", this.description) .append("parameters", this.parameters); } /** * A discovered {@link JmxOperationParameter}. */ - private static class DiscoveredJmxOperationParameter - implements JmxOperationParameter { + private static class DiscoveredJmxOperationParameter implements JmxOperationParameter { private final String name; @@ -197,8 +188,7 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO if (source.isEnum()) { return String.class; } - if (Date.class.isAssignableFrom(source) - || Instant.class.isAssignableFrom(source)) { + if (Date.class.isAssignableFrom(source) || Instant.class.isAssignableFrom(source)) { return String.class; } if (source.getName().startsWith("java.")) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java index e6c98bd6e7c..f9106e3fe1f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.springframework.context.ApplicationContext; * @author Phillip Webb * @since 2.0.0 */ -public class JmxEndpointDiscoverer - extends EndpointDiscoverer +public class JmxEndpointDiscoverer extends EndpointDiscoverer implements JmxEndpointsSupplier { /** @@ -47,30 +46,27 @@ public class JmxEndpointDiscoverer * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ - public JmxEndpointDiscoverer(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, + public JmxEndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { super(applicationContext, parameterValueMapper, invokerAdvisors, filters); } @Override - protected ExposableJmxEndpoint createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - return new DiscoveredJmxEndpoint(this, endpointBean, id, enabledByDefault, - operations); + protected ExposableJmxEndpoint createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, + Collection operations) { + return new DiscoveredJmxEndpoint(this, endpointBean, id, enabledByDefault, operations); } @Override - protected JmxOperation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected JmxOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return new DiscoveredJmxOperation(endpointId, operationMethod, invoker); } @Override protected OperationKey createOperationKey(JmxOperation operation) { - return new OperationKey(operation.getName(), - () -> "MBean call '" + operation.getName() + "'"); + return new OperationKey(operation.getName(), () -> "MBean call '" + operation.getName() + "'"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java index 6c16e5b67bb..b1a1e74a553 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,12 +52,10 @@ public class EndpointLinksResolver { * @param endpoints the endpoints * @param basePath the basePath */ - public EndpointLinksResolver(Collection> endpoints, - String basePath) { + public EndpointLinksResolver(Collection> endpoints, String basePath) { this.endpoints = endpoints; if (logger.isInfoEnabled()) { - logger.info("Exposing " + endpoints.size() - + " endpoint(s) beneath base path '" + basePath + "'"); + logger.info("Exposing " + endpoints.size() + " endpoint(s) beneath base path '" + basePath + "'"); } } @@ -91,8 +89,7 @@ public class EndpointLinksResolver { return requestUrl; } - private void collectLinks(Map links, ExposableWebEndpoint endpoint, - String normalizedUrl) { + private void collectLinks(Map links, ExposableWebEndpoint endpoint, String normalizedUrl) { for (WebOperation operation : endpoint.getOperations()) { links.put(operation.getId(), createLink(normalizedUrl, operation)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointServlet.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointServlet.java index 2b5a4e87bde..417ec9c7e14 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointServlet.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointServlet.java @@ -54,8 +54,7 @@ public final class EndpointServlet { this(servlet, Collections.emptyMap(), -1); } - private EndpointServlet(Servlet servlet, Map initParameters, - int loadOnStartup) { + private EndpointServlet(Servlet servlet, Map initParameters, int loadOnStartup) { Assert.notNull(servlet, "Servlet must not be null"); this.servlet = servlet; this.initParameters = Collections.unmodifiableMap(initParameters); @@ -69,14 +68,11 @@ public final class EndpointServlet { public EndpointServlet withInitParameters(Map initParameters) { Assert.notNull(initParameters, "InitParameters must not be null"); - boolean hasEmptyName = initParameters.keySet().stream() - .anyMatch((name) -> !StringUtils.hasText(name)); + boolean hasEmptyName = initParameters.keySet().stream().anyMatch((name) -> !StringUtils.hasText(name)); Assert.isTrue(!hasEmptyName, "InitParameters must not contain empty names"); - Map mergedInitParameters = new LinkedHashMap<>( - this.initParameters); + Map mergedInitParameters = new LinkedHashMap<>(this.initParameters); mergedInitParameters.putAll(initParameters); - return new EndpointServlet(this.servlet, mergedInitParameters, - this.loadOnStartup); + return new EndpointServlet(this.servlet, mergedInitParameters, this.loadOnStartup); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableServletEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableServletEndpoint.java index 71726cd56de..29bcf6175fe 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableServletEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableServletEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.boot.actuate.endpoint.Operation; * @author Phillip Webb * @since 2.0.0 */ -public interface ExposableServletEndpoint - extends ExposableEndpoint, PathMappedEndpoint { +public interface ExposableServletEndpoint extends ExposableEndpoint, PathMappedEndpoint { /** * Return details of the servlet that should registered. diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableWebEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableWebEndpoint.java index 8d4b509ab4c..7f9833ee9f5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableWebEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ExposableWebEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.springframework.boot.actuate.endpoint.ExposableEndpoint; * @author Phillip Webb * @since 2.0.0 */ -public interface ExposableWebEndpoint - extends ExposableEndpoint, PathMappedEndpoint { +public interface ExposableWebEndpoint extends ExposableEndpoint, PathMappedEndpoint { } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java index 124c7006249..ed00694feff 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,21 +56,18 @@ public class PathMappedEndpoints implements Iterable { * @param basePath the base path of the endpoints * @param suppliers the endpoint suppliers */ - public PathMappedEndpoints(String basePath, - Collection> suppliers) { + public PathMappedEndpoints(String basePath, Collection> suppliers) { Assert.notNull(suppliers, "Suppliers must not be null"); this.basePath = (basePath != null) ? basePath : ""; this.endpoints = getEndpoints(suppliers); } - private Map getEndpoints( - Collection> suppliers) { + private Map getEndpoints(Collection> suppliers) { Map endpoints = new LinkedHashMap<>(); suppliers.forEach((supplier) -> { supplier.getEndpoints().forEach((endpoint) -> { if (endpoint instanceof PathMappedEndpoint) { - endpoints.put(endpoint.getEndpointId(), - (PathMappedEndpoint) endpoint); + endpoints.put(endpoint.getEndpointId(), (PathMappedEndpoint) endpoint); } }); }); @@ -150,8 +147,7 @@ public class PathMappedEndpoints implements Iterable { } private List asList(Stream stream) { - return stream.collect(Collectors.collectingAndThen(Collectors.toList(), - Collections::unmodifiableList)); + return stream.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrar.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrar.java index b2854b1bd30..304cf283727 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrar.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrar.java @@ -45,8 +45,7 @@ public class ServletEndpointRegistrar implements ServletContextInitializer { private final Collection servletEndpoints; - public ServletEndpointRegistrar(String basePath, - Collection servletEndpoints) { + public ServletEndpointRegistrar(String basePath, Collection servletEndpoints) { Assert.notNull(servletEndpoints, "ServletEndpoints must not be null"); this.basePath = cleanBasePath(basePath); this.servletEndpoints = servletEndpoints; @@ -61,18 +60,15 @@ public class ServletEndpointRegistrar implements ServletContextInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { - this.servletEndpoints - .forEach((servletEndpoint) -> register(servletContext, servletEndpoint)); + this.servletEndpoints.forEach((servletEndpoint) -> register(servletContext, servletEndpoint)); } - private void register(ServletContext servletContext, - ExposableServletEndpoint endpoint) { + private void register(ServletContext servletContext, ExposableServletEndpoint endpoint) { String name = endpoint.getEndpointId().toLowerCaseString() + "-actuator-endpoint"; String path = this.basePath + "/" + endpoint.getRootPath(); String urlMapping = path.endsWith("/") ? path + "*" : path + "/*"; EndpointServlet endpointServlet = endpoint.getEndpointServlet(); - Dynamic registration = servletContext.addServlet(name, - endpointServlet.getServlet()); + Dynamic registration = servletContext.addServlet(name, endpointServlet.getServlet()); registration.addMapping(urlMapping); registration.setInitParameters(endpointServlet.getInitParameters()); registration.setLoadOnStartup(endpointServlet.getLoadOnStartup()); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicate.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicate.java index 0e450618707..50cf14dc6b1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicate.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicate.java @@ -50,8 +50,8 @@ public final class WebOperationRequestPredicate { * @param produces the media types that the operation produces * @param consumes the media types that the operation consumes */ - public WebOperationRequestPredicate(String path, WebEndpointHttpMethod httpMethod, - Collection consumes, Collection produces) { + public WebOperationRequestPredicate(String path, WebEndpointHttpMethod httpMethod, Collection consumes, + Collection produces) { this.path = path; this.canonicalPath = PATH_VAR_PATTERN.matcher(path).replaceAll("{*}"); this.httpMethod = httpMethod; @@ -121,15 +121,12 @@ public final class WebOperationRequestPredicate { @Override public String toString() { - StringBuilder result = new StringBuilder( - this.httpMethod + " to path '" + this.path + "'"); + StringBuilder result = new StringBuilder(this.httpMethod + " to path '" + this.path + "'"); if (!CollectionUtils.isEmpty(this.consumes)) { - result.append(" consumes: ") - .append(StringUtils.collectionToCommaDelimitedString(this.consumes)); + result.append(" consumes: ").append(StringUtils.collectionToCommaDelimitedString(this.consumes)); } if (!CollectionUtils.isEmpty(this.produces)) { - result.append(" produces: ") - .append(StringUtils.collectionToCommaDelimitedString(this.produces)); + result.append(" produces: ").append(StringUtils.collectionToCommaDelimitedString(this.produces)); } return result.toString(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java index ec548de1af0..45c672a680b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java @@ -39,8 +39,7 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @since 2.0.0 */ -public class ControllerEndpointDiscoverer - extends EndpointDiscoverer +public class ControllerEndpointDiscoverer extends EndpointDiscoverer implements ControllerEndpointsSupplier { private final List endpointPathMappers; @@ -51,11 +50,9 @@ public class ControllerEndpointDiscoverer * @param endpointPathMappers the endpoint path mappers * @param filters filters to apply */ - public ControllerEndpointDiscoverer(ApplicationContext applicationContext, - List endpointPathMappers, + public ControllerEndpointDiscoverer(ApplicationContext applicationContext, List endpointPathMappers, Collection> filters) { - super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), - filters); + super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), filters); this.endpointPathMappers = endpointPathMappers; } @@ -63,29 +60,25 @@ public class ControllerEndpointDiscoverer protected boolean isEndpointExposed(Object endpointBean) { Class type = ClassUtils.getUserClass(endpointBean.getClass()); MergedAnnotations annotations = MergedAnnotations.from(type); - return annotations.isPresent(ControllerEndpoint.class) - || annotations.isPresent(RestControllerEndpoint.class); + return annotations.isPresent(ControllerEndpoint.class) || annotations.isPresent(RestControllerEndpoint.class); } @Override - protected ExposableControllerEndpoint createEndpoint(Object endpointBean, - EndpointId id, boolean enabledByDefault, Collection operations) { + protected ExposableControllerEndpoint createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, + Collection operations) { String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id); - return new DiscoveredControllerEndpoint(this, endpointBean, id, rootPath, - enabledByDefault); + return new DiscoveredControllerEndpoint(this, endpointBean, id, rootPath, enabledByDefault); } @Override - protected Operation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { - throw new IllegalStateException( - "ControllerEndpoints must not declare operations"); + protected Operation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { + throw new IllegalStateException("ControllerEndpoints must not declare operations"); } @Override protected OperationKey createOperationKey(Operation operation) { - throw new IllegalStateException( - "ControllerEndpoints must not declare operations"); + throw new IllegalStateException("ControllerEndpoints must not declare operations"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointsSupplier.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointsSupplier.java index db20746c964..d33a1234d21 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointsSupplier.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointsSupplier.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import org.springframework.boot.actuate.endpoint.EndpointsSupplier; * @since 2.0.0 */ @FunctionalInterface -public interface ControllerEndpointsSupplier - extends EndpointsSupplier { +public interface ControllerEndpointsSupplier extends EndpointsSupplier { } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredControllerEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredControllerEndpoint.java index a267353e434..be4912db124 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredControllerEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredControllerEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ class DiscoveredControllerEndpoint extends AbstractDiscoveredEndpoint private final String rootPath; - DiscoveredControllerEndpoint(EndpointDiscoverer discoverer, Object endpointBean, - EndpointId id, String rootPath, boolean enabledByDefault) { + DiscoveredControllerEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, + String rootPath, boolean enabledByDefault) { super(discoverer, endpointBean, id, enabledByDefault, Collections.emptyList()); this.rootPath = rootPath; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredServletEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredServletEndpoint.java index 365de6bf512..f8418c08ca3 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredServletEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredServletEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,24 +32,22 @@ import org.springframework.util.Assert; * * @author Phillip Webb */ -class DiscoveredServletEndpoint extends AbstractDiscoveredEndpoint - implements ExposableServletEndpoint { +class DiscoveredServletEndpoint extends AbstractDiscoveredEndpoint implements ExposableServletEndpoint { private final String rootPath; private final EndpointServlet endpointServlet; - DiscoveredServletEndpoint(EndpointDiscoverer discoverer, Object endpointBean, - EndpointId id, String rootPath, boolean enabledByDefault) { + DiscoveredServletEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, String rootPath, + boolean enabledByDefault) { super(discoverer, endpointBean, id, enabledByDefault, Collections.emptyList()); String beanType = endpointBean.getClass().getName(); Assert.state(endpointBean instanceof Supplier, () -> "ServletEndpoint bean " + beanType + " must be a supplier"); Object supplied = ((Supplier) endpointBean).get(); - Assert.state(supplied != null, - () -> "ServletEndpoint bean " + beanType + " must not supply null"); - Assert.state(supplied instanceof EndpointServlet, () -> "ServletEndpoint bean " - + beanType + " must supply an EndpointServlet"); + Assert.state(supplied != null, () -> "ServletEndpoint bean " + beanType + " must not supply null"); + Assert.state(supplied instanceof EndpointServlet, + () -> "ServletEndpoint bean " + beanType + " must supply an EndpointServlet"); this.endpointServlet = (EndpointServlet) supplied; this.rootPath = rootPath; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebEndpoint.java index 6966e7737f3..b62f4f6dda9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,14 +29,12 @@ import org.springframework.boot.actuate.endpoint.web.WebOperation; * * @author Phillip Webb */ -class DiscoveredWebEndpoint extends AbstractDiscoveredEndpoint - implements ExposableWebEndpoint { +class DiscoveredWebEndpoint extends AbstractDiscoveredEndpoint implements ExposableWebEndpoint { private final String rootPath; - DiscoveredWebEndpoint(EndpointDiscoverer discoverer, Object endpointBean, - EndpointId id, String rootPath, boolean enabledByDefault, - Collection operations) { + DiscoveredWebEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, String rootPath, + boolean enabledByDefault, Collection operations) { super(discoverer, endpointBean, id, enabledByDefault, operations); this.rootPath = rootPath; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java index 36c7302de25..63d3af70153 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ import org.springframework.util.ClassUtils; */ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebOperation { - private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent( - "org.reactivestreams.Publisher", + private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent("org.reactivestreams.Publisher", DiscoveredWebOperation.class.getClassLoader()); private final String id; @@ -52,8 +51,7 @@ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebO private final WebOperationRequestPredicate requestPredicate; - DiscoveredWebOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker, + DiscoveredWebOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker, WebOperationRequestPredicate requestPredicate) { super(operationMethod, invoker); Method method = operationMethod.getMethod(); @@ -63,8 +61,8 @@ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebO } private String getId(EndpointId endpointId, Method method) { - return endpointId + Stream.of(method.getParameters()).filter(this::hasSelector) - .map(this::dashName).collect(Collectors.joining()); + return endpointId + Stream.of(method.getParameters()).filter(this::hasSelector).map(this::dashName) + .collect(Collectors.joining()); } private boolean hasSelector(Parameter parameter) { @@ -76,8 +74,7 @@ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebO } private boolean getBlocking(Method method) { - return !REACTIVE_STREAMS_PRESENT - || !Publisher.class.isAssignableFrom(method.getReturnType()); + return !REACTIVE_STREAMS_PRESENT || !Publisher.class.isAssignableFrom(method.getReturnType()); } @Override @@ -97,8 +94,8 @@ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebO @Override protected void appendFields(ToStringCreator creator) { - creator.append("id", this.id).append("blocking", this.blocking) - .append("requestPredicate", this.requestPredicate); + creator.append("id", this.id).append("blocking", this.blocking).append("requestPredicate", + this.requestPredicate); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ExposableControllerEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ExposableControllerEndpoint.java index 1228956bc39..f86c28199e7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ExposableControllerEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ExposableControllerEndpoint.java @@ -29,8 +29,7 @@ import org.springframework.web.bind.annotation.RequestMapping; * @author Phillip Webb * @since 2.0.0 */ -public interface ExposableControllerEndpoint - extends ExposableEndpoint, PathMappedEndpoint { +public interface ExposableControllerEndpoint extends ExposableEndpoint, PathMappedEndpoint { /** * Return the source controller that contains {@link RequestMapping @RequestMapping} diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java index c2fadc72ef1..253551bc8df 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,20 +51,19 @@ class RequestPredicateFactory { this.endpointMediaTypes = endpointMediaTypes; } - public WebOperationRequestPredicate getRequestPredicate(EndpointId endpointId, - String rootPath, DiscoveredOperationMethod operationMethod) { + public WebOperationRequestPredicate getRequestPredicate(EndpointId endpointId, String rootPath, + DiscoveredOperationMethod operationMethod) { Method method = operationMethod.getMethod(); String path = getPath(rootPath, method); - WebEndpointHttpMethod httpMethod = determineHttpMethod( - operationMethod.getOperationType()); + WebEndpointHttpMethod httpMethod = determineHttpMethod(operationMethod.getOperationType()); Collection consumes = getConsumes(httpMethod, method); Collection produces = getProduces(operationMethod, method); return new WebOperationRequestPredicate(path, httpMethod, consumes, produces); } private String getPath(String rootPath, Method method) { - return rootPath + Stream.of(method.getParameters()).filter(this::hasSelector) - .map(this::slashName).collect(Collectors.joining()); + return rootPath + Stream.of(method.getParameters()).filter(this::hasSelector).map(this::slashName) + .collect(Collectors.joining()); } private boolean hasSelector(Parameter parameter) { @@ -75,21 +74,18 @@ class RequestPredicateFactory { return "/{" + parameter.getName() + "}"; } - private Collection getConsumes(WebEndpointHttpMethod httpMethod, - Method method) { + private Collection getConsumes(WebEndpointHttpMethod httpMethod, Method method) { if (WebEndpointHttpMethod.POST == httpMethod && consumesRequestBody(method)) { return this.endpointMediaTypes.getConsumed(); } return Collections.emptyList(); } - private Collection getProduces(DiscoveredOperationMethod operationMethod, - Method method) { + private Collection getProduces(DiscoveredOperationMethod operationMethod, Method method) { if (!operationMethod.getProducesMediaTypes().isEmpty()) { return operationMethod.getProducesMediaTypes(); } - if (Void.class.equals(method.getReturnType()) - || void.class.equals(method.getReturnType())) { + if (Void.class.equals(method.getReturnType()) || void.class.equals(method.getReturnType())) { return Collections.emptyList(); } if (producesResource(method)) { @@ -104,8 +100,7 @@ class RequestPredicateFactory { } if (WebEndpointResponse.class.isAssignableFrom(method.getReturnType())) { ResolvableType returnType = ResolvableType.forMethodReturnType(method); - if (ResolvableType.forClass(Resource.class) - .isAssignableFrom(returnType.getGeneric(0))) { + if (ResolvableType.forClass(Resource.class).isAssignableFrom(returnType.getGeneric(0))) { return true; } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscoverer.java index 90c0209028e..5c7dc7bd67a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscoverer.java @@ -39,8 +39,7 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @since 2.0.0 */ -public class ServletEndpointDiscoverer - extends EndpointDiscoverer +public class ServletEndpointDiscoverer extends EndpointDiscoverer implements ServletEndpointsSupplier { private final List endpointPathMappers; @@ -51,11 +50,9 @@ public class ServletEndpointDiscoverer * @param endpointPathMappers the endpoint path mappers * @param filters filters to apply */ - public ServletEndpointDiscoverer(ApplicationContext applicationContext, - List endpointPathMappers, + public ServletEndpointDiscoverer(ApplicationContext applicationContext, List endpointPathMappers, Collection> filters) { - super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), - filters); + super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), filters); this.endpointPathMappers = endpointPathMappers; } @@ -66,16 +63,15 @@ public class ServletEndpointDiscoverer } @Override - protected ExposableServletEndpoint createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { + protected ExposableServletEndpoint createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, + Collection operations) { String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id); - return new DiscoveredServletEndpoint(this, endpointBean, id, rootPath, - enabledByDefault); + return new DiscoveredServletEndpoint(this, endpointBean, id, rootPath, enabledByDefault); } @Override - protected Operation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected Operation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { throw new IllegalStateException("ServletEndpoints must not declare operations"); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointsSupplier.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointsSupplier.java index 6f7742aeb5d..ee56699e586 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointsSupplier.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointsSupplier.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import org.springframework.boot.actuate.endpoint.web.ExposableServletEndpoint; * @since 2.0.0 */ @FunctionalInterface -public interface ServletEndpointsSupplier - extends EndpointsSupplier { +public interface ServletEndpointsSupplier extends EndpointsSupplier { } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java index 3d4b00d6b27..aff2bcf9e5a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ import org.springframework.context.ApplicationContext; * @author Phillip Webb * @since 2.0.0 */ -public class WebEndpointDiscoverer - extends EndpointDiscoverer +public class WebEndpointDiscoverer extends EndpointDiscoverer implements WebEndpointsSupplier { private final List endpointPathMappers; @@ -57,8 +56,7 @@ public class WebEndpointDiscoverer * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ - public WebEndpointDiscoverer(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, + public WebEndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, EndpointMediaTypes endpointMediaTypes, List endpointPathMappers, Collection invokerAdvisors, Collection> filters) { @@ -68,21 +66,19 @@ public class WebEndpointDiscoverer } @Override - protected ExposableWebEndpoint createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { + protected ExposableWebEndpoint createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, + Collection operations) { String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id); - return new DiscoveredWebEndpoint(this, endpointBean, id, rootPath, - enabledByDefault, operations); + return new DiscoveredWebEndpoint(this, endpointBean, id, rootPath, enabledByDefault, operations); } @Override - protected WebOperation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected WebOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { String rootPath = PathMapper.getRootPath(this.endpointPathMappers, endpointId); - WebOperationRequestPredicate requestPredicate = this.requestPredicateFactory - .getRequestPredicate(endpointId, rootPath, operationMethod); - return new DiscoveredWebOperation(endpointId, operationMethod, invoker, - requestPredicate); + WebOperationRequestPredicate requestPredicate = this.requestPredicateFactory.getRequestPredicate(endpointId, + rootPath, operationMethod); + return new DiscoveredWebOperation(endpointId, operationMethod, invoker, requestPredicate); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java index a306a5bbd51..425f08c983c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,38 +74,33 @@ public class JerseyEndpointResourceFactory { * @return the resources for the operations */ public Collection createEndpointResources(EndpointMapping endpointMapping, - Collection endpoints, - EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver) { + Collection endpoints, EndpointMediaTypes endpointMediaTypes, + EndpointLinksResolver linksResolver) { List resources = new ArrayList<>(); endpoints.stream().flatMap((endpoint) -> endpoint.getOperations().stream()) - .map((operation) -> createResource(endpointMapping, operation)) - .forEach(resources::add); + .map((operation) -> createResource(endpointMapping, operation)).forEach(resources::add); if (StringUtils.hasText(endpointMapping.getPath())) { - Resource resource = createEndpointLinksResource(endpointMapping.getPath(), - endpointMediaTypes, linksResolver); + Resource resource = createEndpointLinksResource(endpointMapping.getPath(), endpointMediaTypes, + linksResolver); resources.add(resource); } return resources; } - private Resource createResource(EndpointMapping endpointMapping, - WebOperation operation) { + private Resource createResource(EndpointMapping endpointMapping, WebOperation operation) { WebOperationRequestPredicate requestPredicate = operation.getRequestPredicate(); - Builder resourceBuilder = Resource.builder() - .path(endpointMapping.createSubPath(requestPredicate.getPath())); + Builder resourceBuilder = Resource.builder().path(endpointMapping.createSubPath(requestPredicate.getPath())); resourceBuilder.addMethod(requestPredicate.getHttpMethod().name()) .consumes(StringUtils.toStringArray(requestPredicate.getConsumes())) .produces(StringUtils.toStringArray(requestPredicate.getProduces())) - .handledBy(new OperationInflector(operation, - !requestPredicate.getConsumes().isEmpty())); + .handledBy(new OperationInflector(operation, !requestPredicate.getConsumes().isEmpty())); return resourceBuilder.build(); } - private Resource createEndpointLinksResource(String endpointPath, - EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver) { + private Resource createEndpointLinksResource(String endpointPath, EndpointMediaTypes endpointMediaTypes, + EndpointLinksResolver linksResolver) { Builder resourceBuilder = Resource.builder().path(endpointPath); - resourceBuilder.addMethod("GET") - .produces(StringUtils.toStringArray(endpointMediaTypes.getProduced())) + resourceBuilder.addMethod("GET").produces(StringUtils.toStringArray(endpointMediaTypes.getProduced())) .handledBy(new EndpointLinksInflector(linksResolver)); return resourceBuilder.build(); } @@ -113,16 +108,14 @@ public class JerseyEndpointResourceFactory { /** * {@link Inflector} to invoke the {@link WebOperation}. */ - private static final class OperationInflector - implements Inflector { + private static final class OperationInflector implements Inflector { private static final List> BODY_CONVERTERS; static { List> converters = new ArrayList<>(); converters.add(new ResourceBodyConverter()); - if (ClassUtils.isPresent("reactor.core.publisher.Mono", - OperationInflector.class.getClassLoader())) { + if (ClassUtils.isPresent("reactor.core.publisher.Mono", OperationInflector.class.getClassLoader())) { converters.add(new MonoBodyConverter()); } BODY_CONVERTERS = Collections.unmodifiableList(converters); @@ -146,8 +139,8 @@ public class JerseyEndpointResourceFactory { arguments.putAll(extractPathParameters(data)); arguments.putAll(extractQueryParameters(data)); try { - Object response = this.operation.invoke(new InvocationContext( - new JerseySecurityContext(data.getSecurityContext()), arguments)); + Object response = this.operation + .invoke(new InvocationContext(new JerseySecurityContext(data.getSecurityContext()), arguments)); return convertToJaxRsResponse(response, data.getRequest().getMethod()); } catch (InvalidEndpointRequestException ex) { @@ -164,18 +157,15 @@ public class JerseyEndpointResourceFactory { return (Map) entity; } - private Map extractPathParameters( - ContainerRequestContext requestContext) { + private Map extractPathParameters(ContainerRequestContext requestContext) { return extract(requestContext.getUriInfo().getPathParameters()); } - private Map extractQueryParameters( - ContainerRequestContext requestContext) { + private Map extractQueryParameters(ContainerRequestContext requestContext) { return extract(requestContext.getUriInfo().getQueryParameters()); } - private Map extract( - MultivaluedMap multivaluedMap) { + private Map extract(MultivaluedMap multivaluedMap) { Map result = new HashMap<>(); multivaluedMap.forEach((name, values) -> { if (!CollectionUtils.isEmpty(values)) { @@ -193,13 +183,11 @@ public class JerseyEndpointResourceFactory { } try { if (!(response instanceof WebEndpointResponse)) { - return Response.status(Status.OK).entity(convertIfNecessary(response)) - .build(); + return Response.status(Status.OK).entity(convertIfNecessary(response)).build(); } WebEndpointResponse webEndpointResponse = (WebEndpointResponse) response; return Response.status(webEndpointResponse.getStatus()) - .entity(convertIfNecessary(webEndpointResponse.getBody())) - .build(); + .entity(convertIfNecessary(webEndpointResponse.getBody())).build(); } catch (IOException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); @@ -254,8 +242,7 @@ public class JerseyEndpointResourceFactory { /** * {@link Inflector} to for endpoint links. */ - private static final class EndpointLinksInflector - implements Inflector { + private static final class EndpointLinksInflector implements Inflector { private final EndpointLinksResolver linksResolver; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java index 85dee9b5d23..9d9cbf4e945 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java @@ -77,8 +77,7 @@ import org.springframework.web.util.pattern.PathPatternParser; * @author Brian Clozel * @since 2.0.0 */ -public abstract class AbstractWebFluxEndpointHandlerMapping - extends RequestMappingInfoHandlerMapping { +public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappingInfoHandlerMapping { private static final PathPatternParser pathPatternParser = new PathPatternParser(); @@ -90,11 +89,11 @@ public abstract class AbstractWebFluxEndpointHandlerMapping private final CorsConfiguration corsConfiguration; - private final Method handleWriteMethod = ReflectionUtils.findMethod( - WriteOperationHandler.class, "handle", ServerWebExchange.class, Map.class); + private final Method handleWriteMethod = ReflectionUtils.findMethod(WriteOperationHandler.class, "handle", + ServerWebExchange.class, Map.class); - private final Method handleReadMethod = ReflectionUtils - .findMethod(ReadOperationHandler.class, "handle", ServerWebExchange.class); + private final Method handleReadMethod = ReflectionUtils.findMethod(ReadOperationHandler.class, "handle", + ServerWebExchange.class); /** * Creates a new {@code AbstractWebFluxEndpointHandlerMapping} that provides mappings @@ -105,8 +104,8 @@ public abstract class AbstractWebFluxEndpointHandlerMapping * @param corsConfiguration the CORS configuration for the endpoints */ public AbstractWebFluxEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration) { + Collection endpoints, EndpointMediaTypes endpointMediaTypes, + CorsConfiguration corsConfiguration) { this.endpointMapping = endpointMapping; this.endpoints = endpoints; this.endpointMediaTypes = endpointMediaTypes; @@ -129,22 +128,18 @@ public abstract class AbstractWebFluxEndpointHandlerMapping @Override protected HandlerMethod createHandlerMethod(Object handler, Method method) { HandlerMethod handlerMethod = super.createHandlerMethod(handler, method); - return new WebFluxEndpointHandlerMethod(handlerMethod.getBean(), - handlerMethod.getMethod()); + return new WebFluxEndpointHandlerMethod(handlerMethod.getBean(), handlerMethod.getMethod()); } - private void registerMappingForOperation(ExposableWebEndpoint endpoint, - WebOperation operation) { - ReactiveWebOperation reactiveWebOperation = wrapReactiveWebOperation(endpoint, - operation, new ReactiveWebOperationAdapter(operation)); + private void registerMappingForOperation(ExposableWebEndpoint endpoint, WebOperation operation) { + ReactiveWebOperation reactiveWebOperation = wrapReactiveWebOperation(endpoint, operation, + new ReactiveWebOperationAdapter(operation)); if (operation.getType() == OperationType.WRITE) { - registerMapping(createRequestMappingInfo(operation), - new WriteOperationHandler((reactiveWebOperation)), + registerMapping(createRequestMappingInfo(operation), new WriteOperationHandler((reactiveWebOperation)), this.handleWriteMethod); } else { - registerMapping(createRequestMappingInfo(operation), - new ReadOperationHandler((reactiveWebOperation)), + registerMapping(createRequestMappingInfo(operation), new ReadOperationHandler((reactiveWebOperation)), this.handleReadMethod); } } @@ -157,37 +152,34 @@ public abstract class AbstractWebFluxEndpointHandlerMapping * @param reactiveWebOperation the reactive web operation to wrap * @return a wrapped reactive web operation */ - protected ReactiveWebOperation wrapReactiveWebOperation(ExposableWebEndpoint endpoint, - WebOperation operation, ReactiveWebOperation reactiveWebOperation) { + protected ReactiveWebOperation wrapReactiveWebOperation(ExposableWebEndpoint endpoint, WebOperation operation, + ReactiveWebOperation reactiveWebOperation) { return reactiveWebOperation; } private RequestMappingInfo createRequestMappingInfo(WebOperation operation) { WebOperationRequestPredicate predicate = operation.getRequestPredicate(); - PatternsRequestCondition patterns = new PatternsRequestCondition(pathPatternParser - .parse(this.endpointMapping.createSubPath(predicate.getPath()))); + PatternsRequestCondition patterns = new PatternsRequestCondition( + pathPatternParser.parse(this.endpointMapping.createSubPath(predicate.getPath()))); RequestMethodsRequestCondition methods = new RequestMethodsRequestCondition( RequestMethod.valueOf(predicate.getHttpMethod().name())); ConsumesRequestCondition consumes = new ConsumesRequestCondition( StringUtils.toStringArray(predicate.getConsumes())); ProducesRequestCondition produces = new ProducesRequestCondition( StringUtils.toStringArray(predicate.getProduces())); - return new RequestMappingInfo(null, patterns, methods, null, null, consumes, - produces, null); + return new RequestMappingInfo(null, patterns, methods, null, null, consumes, produces, null); } private void registerLinksMapping() { PatternsRequestCondition patterns = new PatternsRequestCondition( pathPatternParser.parse(this.endpointMapping.getPath())); - RequestMethodsRequestCondition methods = new RequestMethodsRequestCondition( - RequestMethod.GET); + RequestMethodsRequestCondition methods = new RequestMethodsRequestCondition(RequestMethod.GET); ProducesRequestCondition produces = new ProducesRequestCondition( StringUtils.toStringArray(this.endpointMediaTypes.getProduced())); - RequestMappingInfo mapping = new RequestMappingInfo(patterns, methods, null, null, - null, produces, null); + RequestMappingInfo mapping = new RequestMappingInfo(patterns, methods, null, null, null, produces, null); LinksHandler linksHandler = getLinksHandler(); - registerMapping(mapping, linksHandler, ReflectionUtils - .findMethod(linksHandler.getClass(), "links", ServerWebExchange.class)); + registerMapping(mapping, linksHandler, + ReflectionUtils.findMethod(linksHandler.getClass(), "links", ServerWebExchange.class)); } @Override @@ -196,8 +188,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping } @Override - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mapping) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } @@ -207,8 +198,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping } @Override - protected RequestMappingInfo getMappingForMethod(Method method, - Class handlerType) { + protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { return null; } @@ -240,8 +230,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping @Override public Object invoke(InvocationContext context) { - return Mono.create( - (sink) -> Schedulers.elastic().schedule(() -> invoke(context, sink))); + return Mono.create((sink) -> Schedulers.elastic().schedule(() -> invoke(context, sink))); } private void invoke(InvocationContext context, MonoSink sink) { @@ -272,8 +261,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping @FunctionalInterface protected interface ReactiveWebOperation { - Mono> handle(ServerWebExchange exchange, - Map body); + Mono> handle(ServerWebExchange exchange, Map body); } @@ -281,8 +269,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping * Adapter class to convert an {@link OperationInvoker} into a * {@link ReactiveWebOperation}. */ - private static final class ReactiveWebOperationAdapter - implements ReactiveWebOperation { + private static final class ReactiveWebOperationAdapter implements ReactiveWebOperation { private final OperationInvoker invoker; @@ -305,8 +292,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping } private Supplier> getSecurityContextSupplier() { - if (ClassUtils.isPresent( - "org.springframework.security.core.context.ReactiveSecurityContextHolder", + if (ClassUtils.isPresent("org.springframework.security.core.context.ReactiveSecurityContextHolder", getClass().getClassLoader())) { return this::springSecurityContext; } @@ -315,8 +301,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping public Mono springSecurityContext() { return ReactiveSecurityContextHolder.getContext() - .map((securityContext) -> new ReactiveSecurityContext( - securityContext.getAuthentication())) + .map((securityContext) -> new ReactiveSecurityContext(securityContext.getAuthentication())) .switchIfEmpty(Mono.just(new ReactiveSecurityContext(null))); } @@ -325,26 +310,22 @@ public abstract class AbstractWebFluxEndpointHandlerMapping } @Override - public Mono> handle(ServerWebExchange exchange, - Map body) { + public Mono> handle(ServerWebExchange exchange, Map body) { Map arguments = getArguments(exchange, body); return this.securityContextSupplier.get() - .map((securityContext) -> new InvocationContext(securityContext, - arguments)) - .flatMap((invocationContext) -> handleResult( - (Publisher) this.invoker.invoke(invocationContext), + .map((securityContext) -> new InvocationContext(securityContext, arguments)) + .flatMap((invocationContext) -> handleResult((Publisher) this.invoker.invoke(invocationContext), exchange.getRequest().getMethod())); } - private Map getArguments(ServerWebExchange exchange, - Map body) { + private Map getArguments(ServerWebExchange exchange, Map body) { Map arguments = new LinkedHashMap<>(); arguments.putAll(getTemplateVariables(exchange)); if (body != null) { arguments.putAll(body); } - exchange.getRequest().getQueryParams().forEach((name, values) -> arguments - .put(name, (values.size() != 1) ? values : values.get(0))); + exchange.getRequest().getQueryParams() + .forEach((name, values) -> arguments.put(name, (values.size() != 1) ? values : values.get(0))); return arguments; } @@ -352,14 +333,12 @@ public abstract class AbstractWebFluxEndpointHandlerMapping return exchange.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); } - private Mono> handleResult(Publisher result, - HttpMethod httpMethod) { + private Mono> handleResult(Publisher result, HttpMethod httpMethod) { return Mono.from(result).map(this::toResponseEntity) .onErrorMap(InvalidEndpointRequestException.class, - (ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST, - ex.getReason())) - .defaultIfEmpty(new ResponseEntity<>((httpMethod != HttpMethod.GET) - ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND)); + (ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getReason())) + .defaultIfEmpty(new ResponseEntity<>( + (httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND)); } private ResponseEntity toResponseEntity(Object response) { @@ -429,8 +408,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping @Override public HandlerMethod createWithResolvedBean() { HandlerMethod handlerMethod = super.createWithResolvedBean(); - return new WebFluxEndpointHandlerMethod(handlerMethod.getBean(), - handlerMethod.getMethod()); + return new WebFluxEndpointHandlerMethod(handlerMethod.getBean(), handlerMethod.getMethod()); } } @@ -456,8 +434,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping role = this.roleVoter.getRolePrefix() + role; } return this.roleVoter.vote(this.authentication, null, - Collections.singletonList(new SecurityConfig( - role))) == AccessDecisionVoter.ACCESS_GRANTED; + Collections.singletonList(new SecurityConfig(role))) == AccessDecisionVoter.ACCESS_GRANTED; } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java index 795055c0001..93d84098c6f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java @@ -59,8 +59,7 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi * @param corsConfiguration the CORS configuration for the endpoints or {@code null} */ public ControllerEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - CorsConfiguration corsConfiguration) { + Collection endpoints, CorsConfiguration corsConfiguration) { Assert.notNull(endpointMapping, "EndpointMapping must not be null"); Assert.notNull(endpoints, "Endpoints must not be null"); this.endpointMapping = endpointMapping; @@ -69,8 +68,7 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi setOrder(-100); } - private Map getHandlers( - Collection endpoints) { + private Map getHandlers(Collection endpoints) { Map handlers = new LinkedHashMap<>(); endpoints.forEach((endpoint) -> handlers.put(endpoint.getController(), endpoint)); return Collections.unmodifiableMap(handlers); @@ -82,38 +80,31 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi } @Override - protected void registerHandlerMethod(Object handler, Method method, - RequestMappingInfo mapping) { + protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { ExposableControllerEndpoint endpoint = this.handlers.get(handler); mapping = withEndpointMappedPatterns(endpoint, mapping); super.registerHandlerMethod(handler, method, mapping); } - private RequestMappingInfo withEndpointMappedPatterns( - ExposableControllerEndpoint endpoint, RequestMappingInfo mapping) { + private RequestMappingInfo withEndpointMappedPatterns(ExposableControllerEndpoint endpoint, + RequestMappingInfo mapping) { Set patterns = mapping.getPatternsCondition().getPatterns(); if (patterns.isEmpty()) { patterns = Collections.singleton(getPathPatternParser().parse("")); } PathPattern[] endpointMappedPatterns = patterns.stream() - .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)) - .toArray(PathPattern[]::new); + .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)).toArray(PathPattern[]::new); return withNewPatterns(mapping, endpointMappedPatterns); } - private PathPattern getEndpointMappedPattern(ExposableControllerEndpoint endpoint, - PathPattern pattern) { - return getPathPatternParser().parse( - this.endpointMapping.createSubPath(endpoint.getRootPath() + pattern)); + private PathPattern getEndpointMappedPattern(ExposableControllerEndpoint endpoint, PathPattern pattern) { + return getPathPatternParser().parse(this.endpointMapping.createSubPath(endpoint.getRootPath() + pattern)); } - private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, - PathPattern[] patterns) { - PatternsRequestCondition patternsCondition = new PatternsRequestCondition( - patterns); - return new RequestMappingInfo(patternsCondition, mapping.getMethodsCondition(), - mapping.getParamsCondition(), mapping.getHeadersCondition(), - mapping.getConsumesCondition(), mapping.getProducesCondition(), + private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, PathPattern[] patterns) { + PatternsRequestCondition patternsCondition = new PatternsRequestCondition(patterns); + return new RequestMappingInfo(patternsCondition, mapping.getMethodsCondition(), mapping.getParamsCondition(), + mapping.getHeadersCondition(), mapping.getConsumesCondition(), mapping.getProducesCondition(), mapping.getCustomCondition()); } @@ -123,8 +114,7 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi } @Override - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mapping) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java index 4b223ca2832..4b5e440bd84 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ import org.springframework.web.util.UriComponentsBuilder; * @author Brian Clozel * @since 2.0.0 */ -public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping - implements InitializingBean { +public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping implements InitializingBean { private final EndpointLinksResolver linksResolver; @@ -55,8 +54,7 @@ public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandle * @param corsConfiguration the CORS configuration for the endpoints or {@code null} * @param linksResolver resolver for determining links to available endpoints */ - public WebFluxEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, + public WebFluxEndpointHandlerMapping(EndpointMapping endpointMapping, Collection endpoints, EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration, EndpointLinksResolver linksResolver) { super(endpointMapping, endpoints, endpointMediaTypes, corsConfiguration); @@ -77,12 +75,10 @@ public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandle @Override @ResponseBody public Map> links(ServerWebExchange exchange) { - String requestUri = UriComponentsBuilder - .fromUri(exchange.getRequest().getURI()).replaceQuery(null) + String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).replaceQuery(null) .toUriString(); return Collections.singletonMap("_links", - WebFluxEndpointHandlerMapping.this.linksResolver - .resolveLinks(requestUri)); + WebFluxEndpointHandlerMapping.this.linksResolver.resolveLinks(requestUri)); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java index a91938b0207..0742200cb10 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java @@ -70,8 +70,7 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMappi * @author Brian Clozel * @since 2.0.0 */ -public abstract class AbstractWebMvcEndpointHandlerMapping - extends RequestMappingInfoHandlerMapping +public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappingInfoHandlerMapping implements InitializingBean, MatchableHandlerMapping { private final EndpointMapping endpointMapping; @@ -82,8 +81,8 @@ public abstract class AbstractWebMvcEndpointHandlerMapping private final CorsConfiguration corsConfiguration; - private final Method handleMethod = ReflectionUtils.findMethod(OperationHandler.class, - "handle", HttpServletRequest.class, Map.class); + private final Method handleMethod = ReflectionUtils.findMethod(OperationHandler.class, "handle", + HttpServletRequest.class, Map.class); private static final RequestMappingInfo.BuilderConfiguration builderConfig = getBuilderConfig(); @@ -95,8 +94,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping * @param endpointMediaTypes media types consumed and produced by the endpoints */ public AbstractWebMvcEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - EndpointMediaTypes endpointMediaTypes) { + Collection endpoints, EndpointMediaTypes endpointMediaTypes) { this(endpointMapping, endpoints, endpointMediaTypes, null); } @@ -109,8 +107,8 @@ public abstract class AbstractWebMvcEndpointHandlerMapping * @param corsConfiguration the CORS configuration for the endpoints or {@code null} */ public AbstractWebMvcEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration) { + Collection endpoints, EndpointMediaTypes endpointMediaTypes, + CorsConfiguration corsConfiguration) { this.endpointMapping = endpointMapping; this.endpoints = endpoints; this.endpointMediaTypes = endpointMediaTypes; @@ -133,22 +131,19 @@ public abstract class AbstractWebMvcEndpointHandlerMapping @Override protected HandlerMethod createHandlerMethod(Object handler, Method method) { HandlerMethod handlerMethod = super.createHandlerMethod(handler, method); - return new WebMvcEndpointHandlerMethod(handlerMethod.getBean(), - handlerMethod.getMethod()); + return new WebMvcEndpointHandlerMethod(handlerMethod.getBean(), handlerMethod.getMethod()); } @Override public RequestMatchResult match(HttpServletRequest request, String pattern) { - RequestMappingInfo info = RequestMappingInfo.paths(pattern).options(builderConfig) - .build(); + RequestMappingInfo info = RequestMappingInfo.paths(pattern).options(builderConfig).build(); RequestMappingInfo matchingInfo = info.getMatchingCondition(request); if (matchingInfo == null) { return null; } Set patterns = matchingInfo.getPatternsCondition().getPatterns(); String lookupPath = getUrlPathHelper().getLookupPathForRequest(request); - return new RequestMatchResult(patterns.iterator().next(), lookupPath, - getPathMatcher()); + return new RequestMatchResult(patterns.iterator().next(), lookupPath, getPathMatcher()); } private static RequestMappingInfo.BuilderConfiguration getBuilderConfig() { @@ -160,12 +155,11 @@ public abstract class AbstractWebMvcEndpointHandlerMapping return config; } - private void registerMappingForOperation(ExposableWebEndpoint endpoint, - WebOperation operation) { - ServletWebOperation servletWebOperation = wrapServletWebOperation(endpoint, - operation, new ServletWebOperationAdapter(operation)); - registerMapping(createRequestMappingInfo(operation), - new OperationHandler(servletWebOperation), this.handleMethod); + private void registerMappingForOperation(ExposableWebEndpoint endpoint, WebOperation operation) { + ServletWebOperation servletWebOperation = wrapServletWebOperation(endpoint, operation, + new ServletWebOperationAdapter(operation)); + registerMapping(createRequestMappingInfo(operation), new OperationHandler(servletWebOperation), + this.handleMethod); } /** @@ -176,45 +170,38 @@ public abstract class AbstractWebMvcEndpointHandlerMapping * @param servletWebOperation the servlet web operation to wrap * @return a wrapped servlet web operation */ - protected ServletWebOperation wrapServletWebOperation(ExposableWebEndpoint endpoint, - WebOperation operation, ServletWebOperation servletWebOperation) { + protected ServletWebOperation wrapServletWebOperation(ExposableWebEndpoint endpoint, WebOperation operation, + ServletWebOperation servletWebOperation) { return servletWebOperation; } private RequestMappingInfo createRequestMappingInfo(WebOperation operation) { WebOperationRequestPredicate predicate = operation.getRequestPredicate(); - PatternsRequestCondition patterns = patternsRequestConditionForPattern( - predicate.getPath()); + PatternsRequestCondition patterns = patternsRequestConditionForPattern(predicate.getPath()); RequestMethodsRequestCondition methods = new RequestMethodsRequestCondition( RequestMethod.valueOf(predicate.getHttpMethod().name())); ConsumesRequestCondition consumes = new ConsumesRequestCondition( StringUtils.toStringArray(predicate.getConsumes())); ProducesRequestCondition produces = new ProducesRequestCondition( StringUtils.toStringArray(predicate.getProduces())); - return new RequestMappingInfo(null, patterns, methods, null, null, consumes, - produces, null); + return new RequestMappingInfo(null, patterns, methods, null, null, consumes, produces, null); } private void registerLinksMapping() { PatternsRequestCondition patterns = patternsRequestConditionForPattern(""); - RequestMethodsRequestCondition methods = new RequestMethodsRequestCondition( - RequestMethod.GET); - ProducesRequestCondition produces = new ProducesRequestCondition( - this.endpointMediaTypes.getProduced().toArray(StringUtils - .toStringArray(this.endpointMediaTypes.getProduced()))); - RequestMappingInfo mapping = new RequestMappingInfo(patterns, methods, null, null, - null, produces, null); + RequestMethodsRequestCondition methods = new RequestMethodsRequestCondition(RequestMethod.GET); + ProducesRequestCondition produces = new ProducesRequestCondition(this.endpointMediaTypes.getProduced() + .toArray(StringUtils.toStringArray(this.endpointMediaTypes.getProduced()))); + RequestMappingInfo mapping = new RequestMappingInfo(patterns, methods, null, null, null, produces, null); LinksHandler linksHandler = getLinksHandler(); - registerMapping(mapping, linksHandler, - ReflectionUtils.findMethod(linksHandler.getClass(), "links", - HttpServletRequest.class, HttpServletResponse.class)); + registerMapping(mapping, linksHandler, ReflectionUtils.findMethod(linksHandler.getClass(), "links", + HttpServletRequest.class, HttpServletResponse.class)); } private PatternsRequestCondition patternsRequestConditionForPattern(String path) { String[] patterns = new String[] { this.endpointMapping.createSubPath(path) }; - return new PatternsRequestCondition(patterns, builderConfig.getUrlPathHelper(), - builderConfig.getPathMatcher(), builderConfig.useSuffixPatternMatch(), - builderConfig.useTrailingSlashMatch()); + return new PatternsRequestCondition(patterns, builderConfig.getUrlPathHelper(), builderConfig.getPathMatcher(), + builderConfig.useSuffixPatternMatch(), builderConfig.useTrailingSlashMatch()); } @Override @@ -223,8 +210,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping } @Override - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mapping) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } @@ -234,8 +220,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping } @Override - protected RequestMappingInfo getMappingForMethod(Method method, - Class handlerType) { + protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { return null; } @@ -291,13 +276,11 @@ public abstract class AbstractWebMvcEndpointHandlerMapping } @Override - public Object handle(HttpServletRequest request, - @RequestBody(required = false) Map body) { + public Object handle(HttpServletRequest request, @RequestBody(required = false) Map body) { Map arguments = getArguments(request, body); try { return handleResult( - this.operation.invoke(new InvocationContext( - new ServletSecurityContext(request), arguments)), + this.operation.invoke(new InvocationContext(new ServletSecurityContext(request), arguments)), HttpMethod.valueOf(request.getMethod())); } catch (InvalidEndpointRequestException ex) { @@ -310,35 +293,32 @@ public abstract class AbstractWebMvcEndpointHandlerMapping return "Actuator web endpoint '" + this.operation.getId() + "'"; } - private Map getArguments(HttpServletRequest request, - Map body) { + private Map getArguments(HttpServletRequest request, Map body) { Map arguments = new LinkedHashMap<>(); arguments.putAll(getTemplateVariables(request)); if (body != null && HttpMethod.POST.name().equals(request.getMethod())) { arguments.putAll(body); } - request.getParameterMap().forEach((name, values) -> arguments.put(name, - (values.length != 1) ? Arrays.asList(values) : values[0])); + request.getParameterMap().forEach( + (name, values) -> arguments.put(name, (values.length != 1) ? Arrays.asList(values) : values[0])); return arguments; } @SuppressWarnings("unchecked") private Map getTemplateVariables(HttpServletRequest request) { - return (Map) request - .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); + return (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); } private Object handleResult(Object result, HttpMethod httpMethod) { if (result == null) { - return new ResponseEntity<>((httpMethod != HttpMethod.GET) - ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND); + return new ResponseEntity<>( + (httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND); } if (!(result instanceof WebEndpointResponse)) { return result; } WebEndpointResponse response = (WebEndpointResponse) result; - return new ResponseEntity(response.getBody(), - HttpStatus.valueOf(response.getStatus())); + return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getStatus())); } } @@ -355,8 +335,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping } @ResponseBody - public Object handle(HttpServletRequest request, - @RequestBody(required = false) Map body) { + public Object handle(HttpServletRequest request, @RequestBody(required = false) Map body) { return this.operation.handle(request, body); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java index 2ed23f015f3..f06cf3406b9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java @@ -59,8 +59,7 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi * @param corsConfiguration the CORS configuration for the endpoints or {@code null} */ public ControllerEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, - CorsConfiguration corsConfiguration) { + Collection endpoints, CorsConfiguration corsConfiguration) { Assert.notNull(endpointMapping, "EndpointMapping must not be null"); Assert.notNull(endpoints, "Endpoints must not be null"); this.endpointMapping = endpointMapping; @@ -70,8 +69,7 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi setUseSuffixPatternMatch(false); } - private Map getHandlers( - Collection endpoints) { + private Map getHandlers(Collection endpoints) { Map handlers = new LinkedHashMap<>(); endpoints.forEach((endpoint) -> handlers.put(endpoint.getController(), endpoint)); return Collections.unmodifiableMap(handlers); @@ -83,38 +81,32 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi } @Override - protected void registerHandlerMethod(Object handler, Method method, - RequestMappingInfo mapping) { + protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { ExposableControllerEndpoint endpoint = this.handlers.get(handler); mapping = withEndpointMappedPatterns(endpoint, mapping); super.registerHandlerMethod(handler, method, mapping); } - private RequestMappingInfo withEndpointMappedPatterns( - ExposableControllerEndpoint endpoint, RequestMappingInfo mapping) { + private RequestMappingInfo withEndpointMappedPatterns(ExposableControllerEndpoint endpoint, + RequestMappingInfo mapping) { Set patterns = mapping.getPatternsCondition().getPatterns(); if (patterns.isEmpty()) { patterns = Collections.singleton(""); } String[] endpointMappedPatterns = patterns.stream() - .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)) - .toArray(String[]::new); + .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)).toArray(String[]::new); return withNewPatterns(mapping, endpointMappedPatterns); } - private String getEndpointMappedPattern(ExposableControllerEndpoint endpoint, - String pattern) { + private String getEndpointMappedPattern(ExposableControllerEndpoint endpoint, String pattern) { return this.endpointMapping.createSubPath(endpoint.getRootPath() + pattern); } - private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, - String[] patterns) { - PatternsRequestCondition patternsCondition = new PatternsRequestCondition( - patterns, null, null, useSuffixPatternMatch(), useTrailingSlashMatch(), - null); - return new RequestMappingInfo(patternsCondition, mapping.getMethodsCondition(), - mapping.getParamsCondition(), mapping.getHeadersCondition(), - mapping.getConsumesCondition(), mapping.getProducesCondition(), + private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, String[] patterns) { + PatternsRequestCondition patternsCondition = new PatternsRequestCondition(patterns, null, null, + useSuffixPatternMatch(), useTrailingSlashMatch(), null); + return new RequestMappingInfo(patternsCondition, mapping.getMethodsCondition(), mapping.getParamsCondition(), + mapping.getHeadersCondition(), mapping.getConsumesCondition(), mapping.getProducesCondition(), mapping.getCustomCondition()); } @@ -124,8 +116,7 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi } @Override - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mapping) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java index 5e9e29e9300..43fd5aaafd0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,12 +30,11 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; */ final class SkipPathExtensionContentNegotiation extends HandlerInterceptorAdapter { - private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class.getName() + ".SKIP"; @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, - Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { request.setAttribute(SKIP_ATTRIBUTE, Boolean.TRUE); return true; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java index 7dad6dbdff5..caa86b3cf2d 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ public class WebMvcEndpointHandlerMapping extends AbstractWebMvcEndpointHandlerM * @param corsConfiguration the CORS configuration for the endpoints or {@code null} * @param linksResolver resolver for determining links to available endpoints */ - public WebMvcEndpointHandlerMapping(EndpointMapping endpointMapping, - Collection endpoints, + public WebMvcEndpointHandlerMapping(EndpointMapping endpointMapping, Collection endpoints, EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration, EndpointLinksResolver linksResolver) { super(endpointMapping, endpoints, endpointMediaTypes, corsConfiguration); @@ -74,11 +73,9 @@ public class WebMvcEndpointHandlerMapping extends AbstractWebMvcEndpointHandlerM @Override @ResponseBody - public Map> links(HttpServletRequest request, - HttpServletResponse response) { + public Map> links(HttpServletRequest request, HttpServletResponse response) { return Collections.singletonMap("_links", - WebMvcEndpointHandlerMapping.this.linksResolver - .resolveLinks(request.getRequestURL().toString())); + WebMvcEndpointHandlerMapping.this.linksResolver.resolveLinks(request.getRequestURL().toString())); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java index 28811125207..c652e590ca1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java @@ -87,66 +87,54 @@ public class EnvironmentEndpoint { return getEnvironmentEntryDescriptor(toMatch); } - private EnvironmentDescriptor getEnvironmentDescriptor( - Predicate propertyNamePredicate) { + private EnvironmentDescriptor getEnvironmentDescriptor(Predicate propertyNamePredicate) { PlaceholdersResolver resolver = getResolver(); List propertySources = new ArrayList<>(); getPropertySourcesAsMap().forEach((sourceName, source) -> { if (source instanceof EnumerablePropertySource) { - propertySources.add( - describeSource(sourceName, (EnumerablePropertySource) source, - resolver, propertyNamePredicate)); + propertySources.add(describeSource(sourceName, (EnumerablePropertySource) source, resolver, + propertyNamePredicate)); } }); - return new EnvironmentDescriptor( - Arrays.asList(this.environment.getActiveProfiles()), propertySources); + return new EnvironmentDescriptor(Arrays.asList(this.environment.getActiveProfiles()), propertySources); } - private EnvironmentEntryDescriptor getEnvironmentEntryDescriptor( - String propertyName) { - Map descriptors = getPropertySourceDescriptors( - propertyName); + private EnvironmentEntryDescriptor getEnvironmentEntryDescriptor(String propertyName) { + Map descriptors = getPropertySourceDescriptors(propertyName); PropertySummaryDescriptor summary = getPropertySummaryDescriptor(descriptors); - return new EnvironmentEntryDescriptor(summary, - Arrays.asList(this.environment.getActiveProfiles()), + return new EnvironmentEntryDescriptor(summary, Arrays.asList(this.environment.getActiveProfiles()), toPropertySourceDescriptors(descriptors)); } private List toPropertySourceDescriptors( Map descriptors) { List result = new ArrayList<>(); - descriptors.forEach((name, property) -> result - .add(new PropertySourceEntryDescriptor(name, property))); + descriptors.forEach((name, property) -> result.add(new PropertySourceEntryDescriptor(name, property))); return result; } - private PropertySummaryDescriptor getPropertySummaryDescriptor( - Map descriptors) { + private PropertySummaryDescriptor getPropertySummaryDescriptor(Map descriptors) { for (Map.Entry entry : descriptors.entrySet()) { if (entry.getValue() != null) { - return new PropertySummaryDescriptor(entry.getKey(), - entry.getValue().getValue()); + return new PropertySummaryDescriptor(entry.getKey(), entry.getValue().getValue()); } } return null; } - private Map getPropertySourceDescriptors( - String propertyName) { + private Map getPropertySourceDescriptors(String propertyName) { Map propertySources = new LinkedHashMap<>(); PlaceholdersResolver resolver = getResolver(); - getPropertySourcesAsMap().forEach((sourceName, source) -> propertySources - .put(sourceName, source.containsProperty(propertyName) - ? describeValueOf(propertyName, source, resolver) : null)); + getPropertySourcesAsMap().forEach((sourceName, source) -> propertySources.put(sourceName, + source.containsProperty(propertyName) ? describeValueOf(propertyName, source, resolver) : null)); return propertySources; } - private PropertySourceDescriptor describeSource(String sourceName, - EnumerablePropertySource source, PlaceholdersResolver resolver, - Predicate namePredicate) { + private PropertySourceDescriptor describeSource(String sourceName, EnumerablePropertySource source, + PlaceholdersResolver resolver, Predicate namePredicate) { Map properties = new LinkedHashMap<>(); - Stream.of(source.getPropertyNames()).filter(namePredicate).forEach( - (name) -> properties.put(name, describeValueOf(name, source, resolver))); + Stream.of(source.getPropertyNames()).filter(namePredicate) + .forEach((name) -> properties.put(name, describeValueOf(name, source, resolver))); return new PropertySourceDescriptor(sourceName, properties); } @@ -154,8 +142,7 @@ public class EnvironmentEndpoint { private PropertyValueDescriptor describeValueOf(String name, PropertySource source, PlaceholdersResolver resolver) { Object resolved = resolver.resolvePlaceholders(source.getProperty(name)); - String origin = ((source instanceof OriginLookup) - ? getOrigin((OriginLookup) source, name) : null); + String origin = ((source instanceof OriginLookup) ? getOrigin((OriginLookup) source, name) : null); return new PropertyValueDescriptor(sanitize(name, resolved), origin); } @@ -165,15 +152,13 @@ public class EnvironmentEndpoint { } private PlaceholdersResolver getResolver() { - return new PropertySourcesPlaceholdersSanitizingResolver(getPropertySources(), - this.sanitizer); + return new PropertySourcesPlaceholdersSanitizingResolver(getPropertySources(), this.sanitizer); } private Map> getPropertySourcesAsMap() { Map> map = new LinkedHashMap<>(); for (PropertySource source : getPropertySources()) { - if (!ConfigurationPropertySources - .isAttachedConfigurationPropertySource(source)) { + if (!ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)) { extract("", map, source); } } @@ -187,11 +172,9 @@ public class EnvironmentEndpoint { return new StandardEnvironment().getPropertySources(); } - private void extract(String root, Map> map, - PropertySource source) { + private void extract(String root, Map> map, PropertySource source) { if (source instanceof CompositePropertySource) { - for (PropertySource nest : ((CompositePropertySource) source) - .getPropertySources()) { + for (PropertySource nest : ((CompositePropertySource) source).getPropertySources()) { extract(source.getName() + ":", map, nest); } } @@ -208,17 +191,13 @@ public class EnvironmentEndpoint { * {@link PropertySourcesPlaceholdersResolver} that sanitizes sensitive placeholders * if present. */ - private static class PropertySourcesPlaceholdersSanitizingResolver - extends PropertySourcesPlaceholdersResolver { + private static class PropertySourcesPlaceholdersSanitizingResolver extends PropertySourcesPlaceholdersResolver { private final Sanitizer sanitizer; - PropertySourcesPlaceholdersSanitizingResolver(Iterable> sources, - Sanitizer sanitizer) { - super(sources, - new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX, - SystemPropertyUtils.PLACEHOLDER_SUFFIX, - SystemPropertyUtils.VALUE_SEPARATOR, true)); + PropertySourcesPlaceholdersSanitizingResolver(Iterable> sources, Sanitizer sanitizer) { + super(sources, new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX, + SystemPropertyUtils.PLACEHOLDER_SUFFIX, SystemPropertyUtils.VALUE_SEPARATOR, true)); this.sanitizer = sanitizer; } @@ -242,8 +221,7 @@ public class EnvironmentEndpoint { private final List propertySources; - private EnvironmentDescriptor(List activeProfiles, - List propertySources) { + private EnvironmentDescriptor(List activeProfiles, List propertySources) { this.activeProfiles = activeProfiles; this.propertySources = propertySources; } @@ -270,8 +248,7 @@ public class EnvironmentEndpoint { private final List propertySources; - private EnvironmentEntryDescriptor(PropertySummaryDescriptor property, - List activeProfiles, + private EnvironmentEntryDescriptor(PropertySummaryDescriptor property, List activeProfiles, List propertySources) { this.property = property; this.activeProfiles = activeProfiles; @@ -326,8 +303,7 @@ public class EnvironmentEndpoint { private final Map properties; - private PropertySourceDescriptor(String name, - Map properties) { + private PropertySourceDescriptor(String name, Map properties) { this.name = name; this.properties = properties; } @@ -352,8 +328,7 @@ public class EnvironmentEndpoint { private final PropertyValueDescriptor property; - private PropertySourceEntryDescriptor(String name, - PropertyValueDescriptor property) { + private PropertySourceEntryDescriptor(String name, PropertyValueDescriptor property) { this.name = name; this.property = property; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtension.java index 34427125273..9615fdd4aa1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtension.java @@ -38,8 +38,7 @@ public class EnvironmentEndpointWebExtension { } @ReadOperation - public WebEndpointResponse environmentEntry( - @Selector String toMatch) { + public WebEndpointResponse environmentEntry(@Selector String toMatch) { EnvironmentEntryDescriptor descriptor = this.delegate.environmentEntry(toMatch); return new WebEndpointResponse<>(descriptor, getStatus(descriptor)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java index 0a0070d283f..5e819d75168 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java @@ -57,11 +57,11 @@ public class FlywayEndpoint { Map contextFlywayBeans = new HashMap<>(); while (target != null) { Map flywayBeans = new HashMap<>(); - target.getBeansOfType(Flyway.class).forEach((name, flyway) -> flywayBeans - .put(name, new FlywayDescriptor(flyway.info().all()))); + target.getBeansOfType(Flyway.class) + .forEach((name, flyway) -> flywayBeans.put(name, new FlywayDescriptor(flyway.info().all()))); ApplicationContext parent = target.getParent(); - contextFlywayBeans.put(target.getId(), new ContextFlywayBeans(flywayBeans, - (parent != null) ? parent.getId() : null)); + contextFlywayBeans.put(target.getId(), + new ContextFlywayBeans(flywayBeans, (parent != null) ? parent.getId() : null)); target = parent; } return new ApplicationFlywayBeans(contextFlywayBeans); @@ -95,8 +95,7 @@ public class FlywayEndpoint { private final String parentId; - private ContextFlywayBeans(Map flywayBeans, - String parentId) { + private ContextFlywayBeans(Map flywayBeans, String parentId) { this.flywayBeans = flywayBeans; this.parentId = parentId; } @@ -119,8 +118,7 @@ public class FlywayEndpoint { private final List migrations; private FlywayDescriptor(MigrationInfo[] migrations) { - this.migrations = Stream.of(migrations).map(FlywayMigration::new) - .collect(Collectors.toList()); + this.migrations = Stream.of(migrations).map(FlywayMigration::new).collect(Collectors.toList()); } public FlywayDescriptor(List migrations) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthAggregator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthAggregator.java index f95306e87d7..a39c13efec2 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthAggregator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthAggregator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public abstract class AbstractHealthAggregator implements HealthAggregator { @Override public final Health aggregate(Map healths) { - List statusCandidates = healths.values().stream().map(Health::getStatus) - .collect(Collectors.toList()); + List statusCandidates = healths.values().stream().map(Health::getStatus).collect(Collectors.toList()); Status status = aggregateStatus(statusCandidates); Map details = aggregateDetails(healths); return new Health.Builder(status, details).build(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java index 697eb966ad4..31492ccec55 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,10 +70,8 @@ public abstract class AbstractHealthIndicator implements HealthIndicator { * @param healthCheckFailedMessage the message to log on health check failure * @since 2.0.0 */ - protected AbstractHealthIndicator( - Function healthCheckFailedMessage) { - Assert.notNull(healthCheckFailedMessage, - "HealthCheckFailedMessage must not be null"); + protected AbstractHealthIndicator(Function healthCheckFailedMessage) { + Assert.notNull(healthCheckFailedMessage, "HealthCheckFailedMessage must not be null"); this.healthCheckFailedMessage = healthCheckFailedMessage; } @@ -86,8 +84,7 @@ public abstract class AbstractHealthIndicator implements HealthIndicator { catch (Exception ex) { if (this.logger.isWarnEnabled()) { String message = this.healthCheckFailedMessage.apply(ex); - this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE, - ex); + this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE, ex); } builder.down(ex); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java index 26120756ede..e86b5672581 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java @@ -39,8 +39,7 @@ public class CompositeHealthIndicator implements HealthIndicator { * @param indicators a map of {@link HealthIndicator HealthIndicators} with the key * being used as an indicator name. */ - public CompositeHealthIndicator(HealthAggregator healthAggregator, - Map indicators) { + public CompositeHealthIndicator(HealthAggregator healthAggregator, Map indicators) { this(healthAggregator, new DefaultHealthIndicatorRegistry(indicators)); } @@ -50,8 +49,7 @@ public class CompositeHealthIndicator implements HealthIndicator { * @param healthAggregator the health aggregator * @param registry the registry of {@link HealthIndicator HealthIndicators}. */ - public CompositeHealthIndicator(HealthAggregator healthAggregator, - HealthIndicatorRegistry registry) { + public CompositeHealthIndicator(HealthAggregator healthAggregator, HealthIndicatorRegistry registry) { this.aggregator = healthAggregator; this.registry = registry; } @@ -68,8 +66,7 @@ public class CompositeHealthIndicator implements HealthIndicator { @Override public Health health() { Map healths = new LinkedHashMap<>(); - for (Map.Entry entry : this.registry.getAll() - .entrySet()) { + for (Map.Entry entry : this.registry.getAll().entrySet()) { healths.put(entry.getKey(), entry.getValue().health()); } return this.aggregator.aggregate(healths); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicator.java index e4238904360..5fba0374ee2 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicator.java @@ -53,8 +53,8 @@ public class CompositeReactiveHealthIndicator implements ReactiveHealthIndicator ReactiveHealthIndicatorRegistry registry) { this.registry = registry; this.healthAggregator = healthAggregator; - this.timeoutCompose = (mono) -> (this.timeout != null) ? mono.timeout( - Duration.ofMillis(this.timeout), Mono.just(this.timeoutHealth)) : mono; + this.timeoutCompose = (mono) -> (this.timeout != null) + ? mono.timeout(Duration.ofMillis(this.timeout), Mono.just(this.timeoutHealth)) : mono; } /** @@ -66,11 +66,9 @@ public class CompositeReactiveHealthIndicator implements ReactiveHealthIndicator * {@code timeout} * @return this instance */ - public CompositeReactiveHealthIndicator timeoutStrategy(long timeout, - Health timeoutHealth) { + public CompositeReactiveHealthIndicator timeoutStrategy(long timeout, Health timeoutHealth) { this.timeout = timeout; - this.timeoutHealth = (timeoutHealth != null) ? timeoutHealth - : Health.unknown().build(); + this.timeoutHealth = (timeoutHealth != null) ? timeoutHealth : Health.unknown().build(); return this; } @@ -80,11 +78,9 @@ public class CompositeReactiveHealthIndicator implements ReactiveHealthIndicator @Override public Mono health() { - return Flux.fromIterable(this.registry.getAll().entrySet()) - .flatMap((entry) -> Mono.zip(Mono.just(entry.getKey()), - entry.getValue().health().compose(this.timeoutCompose))) - .collectMap(Tuple2::getT1, Tuple2::getT2) - .map(this.healthAggregator::aggregate); + return Flux.fromIterable(this.registry.getAll().entrySet()).flatMap( + (entry) -> Mono.zip(Mono.just(entry.getKey()), entry.getValue().health().compose(this.timeoutCompose))) + .collectMap(Tuple2::getT1, Tuple2::getT2).map(this.healthAggregator::aggregate); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistry.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistry.java index 0f16f7740b4..eedf3738271 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistry.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,11 +57,9 @@ public class DefaultHealthIndicatorRegistry implements HealthIndicatorRegistry { Assert.notNull(healthIndicator, "HealthIndicator must not be null"); Assert.notNull(name, "Name must not be null"); synchronized (this.monitor) { - HealthIndicator existing = this.healthIndicators.putIfAbsent(name, - healthIndicator); + HealthIndicator existing = this.healthIndicators.putIfAbsent(name, healthIndicator); if (existing != null) { - throw new IllegalStateException( - "HealthIndicator with name '" + name + "' already registered"); + throw new IllegalStateException("HealthIndicator with name '" + name + "' already registered"); } } } @@ -85,8 +83,7 @@ public class DefaultHealthIndicatorRegistry implements HealthIndicatorRegistry { @Override public Map getAll() { synchronized (this.monitor) { - return Collections - .unmodifiableMap(new LinkedHashMap<>(this.healthIndicators)); + return Collections.unmodifiableMap(new LinkedHashMap<>(this.healthIndicators)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistry.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistry.java index b86e41febea..aae88785dc8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistry.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.util.Assert; * @author Stephane Nicoll * @since 2.1.0 */ -public class DefaultReactiveHealthIndicatorRegistry - implements ReactiveHealthIndicatorRegistry { +public class DefaultReactiveHealthIndicatorRegistry implements ReactiveHealthIndicatorRegistry { private final Object monitor = new Object(); @@ -49,8 +48,7 @@ public class DefaultReactiveHealthIndicatorRegistry * @param healthIndicators a map of {@link HealthIndicator}s with the key being used * as an indicator name. */ - public DefaultReactiveHealthIndicatorRegistry( - Map healthIndicators) { + public DefaultReactiveHealthIndicatorRegistry(Map healthIndicators) { Assert.notNull(healthIndicators, "HealthIndicators must not be null"); this.healthIndicators = new LinkedHashMap<>(healthIndicators); } @@ -60,11 +58,9 @@ public class DefaultReactiveHealthIndicatorRegistry Assert.notNull(healthIndicator, "HealthIndicator must not be null"); Assert.notNull(name, "Name must not be null"); synchronized (this.monitor) { - ReactiveHealthIndicator existing = this.healthIndicators.putIfAbsent(name, - healthIndicator); + ReactiveHealthIndicator existing = this.healthIndicators.putIfAbsent(name, healthIndicator); if (existing != null) { - throw new IllegalStateException( - "HealthIndicator with name '" + name + "' already registered"); + throw new IllegalStateException("HealthIndicator with name '" + name + "' already registered"); } } } @@ -88,8 +84,7 @@ public class DefaultReactiveHealthIndicatorRegistry @Override public Map getAll() { synchronized (this.monitor) { - return Collections - .unmodifiableMap(new LinkedHashMap<>(this.healthIndicators)); + return Collections.unmodifiableMap(new LinkedHashMap<>(this.healthIndicators)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpoint.java index 22654cde406..541b52cbc1b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpoint.java @@ -58,8 +58,7 @@ public class HealthEndpoint { */ @ReadOperation public Health healthForComponent(@Selector String component) { - HealthIndicator indicator = getNestedHealthIndicator(this.healthIndicator, - component); + HealthIndicator indicator = getNestedHealthIndicator(this.healthIndicator, component); return (indicator != null) ? indicator.health() : null; } @@ -72,16 +71,13 @@ public class HealthEndpoint { * @return the {@link Health} for the component instance of {@code null} */ @ReadOperation - public Health healthForComponentInstance(@Selector String component, - @Selector String instance) { - HealthIndicator indicator = getNestedHealthIndicator(this.healthIndicator, - component); + public Health healthForComponentInstance(@Selector String component, @Selector String instance) { + HealthIndicator indicator = getNestedHealthIndicator(this.healthIndicator, component); HealthIndicator nestedIndicator = getNestedHealthIndicator(indicator, instance); return (nestedIndicator != null) ? nestedIndicator.health() : null; } - private HealthIndicator getNestedHealthIndicator(HealthIndicator healthIndicator, - String name) { + private HealthIndicator getNestedHealthIndicator(HealthIndicator healthIndicator, String name) { if (healthIndicator instanceof CompositeHealthIndicator) { return ((CompositeHealthIndicator) healthIndicator).getRegistry().get(name); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointWebExtension.java index 90e904b9928..7cdaed53004 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointWebExtension.java @@ -43,8 +43,7 @@ public class HealthEndpointWebExtension { private final HealthWebEndpointResponseMapper responseMapper; - public HealthEndpointWebExtension(HealthEndpoint delegate, - HealthWebEndpointResponseMapper responseMapper) { + public HealthEndpointWebExtension(HealthEndpoint delegate, HealthWebEndpointResponseMapper responseMapper) { this.delegate = delegate; this.responseMapper = responseMapper; } @@ -55,25 +54,20 @@ public class HealthEndpointWebExtension { } @ReadOperation - public WebEndpointResponse healthForComponent(SecurityContext securityContext, - @Selector String component) { + public WebEndpointResponse healthForComponent(SecurityContext securityContext, @Selector String component) { Supplier health = () -> this.delegate.healthForComponent(component); return this.responseMapper.mapDetails(health, securityContext); } @ReadOperation - public WebEndpointResponse healthForComponentInstance( - SecurityContext securityContext, @Selector String component, - @Selector String instance) { - Supplier health = () -> this.delegate - .healthForComponentInstance(component, instance); + public WebEndpointResponse healthForComponentInstance(SecurityContext securityContext, + @Selector String component, @Selector String instance) { + Supplier health = () -> this.delegate.healthForComponentInstance(component, instance); return this.responseMapper.mapDetails(health, securityContext); } - public WebEndpointResponse getHealth(SecurityContext securityContext, - ShowDetails showDetails) { - return this.responseMapper.map(this.delegate.health(), securityContext, - showDetails); + public WebEndpointResponse getHealth(SecurityContext securityContext, ShowDetails showDetails) { + return this.responseMapper.map(this.delegate.health(), securityContext, showDetails); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicatorRegistryFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicatorRegistryFactory.java index c155ca30b8e..465214902d4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicatorRegistryFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicatorRegistryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ public class HealthIndicatorRegistryFactory { private final Function healthIndicatorNameFactory; - public HealthIndicatorRegistryFactory( - Function healthIndicatorNameFactory) { + public HealthIndicatorRegistryFactory(Function healthIndicatorNameFactory) { this.healthIndicatorNameFactory = healthIndicatorNameFactory; } @@ -46,8 +45,7 @@ public class HealthIndicatorRegistryFactory { * @return a {@link HealthIndicator} that delegates to the specified * {@code healthIndicators}. */ - public HealthIndicatorRegistry createHealthIndicatorRegistry( - Map healthIndicators) { + public HealthIndicatorRegistry createHealthIndicatorRegistry(Map healthIndicators) { Assert.notNull(healthIndicators, "HealthIndicators must not be null"); return initialize(new DefaultHealthIndicatorRegistry(), healthIndicators); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthStatusHttpMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthStatusHttpMapper.java index 46af2dbcdd6..15be7841bb4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthStatusHttpMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthStatusHttpMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class HealthStatusHttpMapper { private void setupDefaultStatusMapping() { addStatusMapping(Status.DOWN, WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); - addStatusMapping(Status.OUT_OF_SERVICE, - WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); + addStatusMapping(Status.OUT_OF_SERVICE, WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); } /** @@ -103,9 +102,8 @@ public class HealthStatusHttpMapper { String code = getUniformValue(status.getCode()); if (code != null) { return this.statusMapping.entrySet().stream() - .filter((entry) -> code.equals(getUniformValue(entry.getKey()))) - .map(Map.Entry::getValue).findFirst() - .orElse(WebEndpointResponse.STATUS_OK); + .filter((entry) -> code.equals(getUniformValue(entry.getKey()))).map(Map.Entry::getValue) + .findFirst().orElse(WebEndpointResponse.STATUS_OK); } return WebEndpointResponse.STATUS_OK; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapper.java index e057723f240..868d8280235 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapper.java @@ -37,8 +37,8 @@ public class HealthWebEndpointResponseMapper { private final Set authorizedRoles; - public HealthWebEndpointResponseMapper(HealthStatusHttpMapper statusHttpMapper, - ShowDetails showDetails, Set authorizedRoles) { + public HealthWebEndpointResponseMapper(HealthStatusHttpMapper statusHttpMapper, ShowDetails showDetails, + Set authorizedRoles) { this.statusHttpMapper = statusHttpMapper; this.showDetails = showDetails; this.authorizedRoles = authorizedRoles; @@ -55,8 +55,7 @@ public class HealthWebEndpointResponseMapper { * @param securityContext the security context * @return the mapped response */ - public WebEndpointResponse mapDetails(Supplier health, - SecurityContext securityContext) { + public WebEndpointResponse mapDetails(Supplier health, SecurityContext securityContext) { if (canSeeDetails(securityContext, this.showDetails)) { Health healthDetails = health.get(); if (healthDetails != null) { @@ -73,8 +72,7 @@ public class HealthWebEndpointResponseMapper { * @param securityContext the security context * @return the mapped response */ - public WebEndpointResponse map(Health health, - SecurityContext securityContext) { + public WebEndpointResponse map(Health health, SecurityContext securityContext) { return map(health, securityContext, this.showDetails); } @@ -86,8 +84,7 @@ public class HealthWebEndpointResponseMapper { * @param showDetails when to show details in the response * @return the mapped response */ - public WebEndpointResponse map(Health health, SecurityContext securityContext, - ShowDetails showDetails) { + public WebEndpointResponse map(Health health, SecurityContext securityContext, ShowDetails showDetails) { if (!canSeeDetails(securityContext, showDetails)) { health = Health.status(health.getStatus()).build(); } @@ -99,12 +96,9 @@ public class HealthWebEndpointResponseMapper { return new WebEndpointResponse<>(health, status); } - private boolean canSeeDetails(SecurityContext securityContext, - ShowDetails showDetails) { - if (showDetails == ShowDetails.NEVER - || (showDetails == ShowDetails.WHEN_AUTHORIZED - && (securityContext.getPrincipal() == null - || !isUserInRole(securityContext)))) { + private boolean canSeeDetails(SecurityContext securityContext, ShowDetails showDetails) { + if (showDetails == ShowDetails.NEVER || (showDetails == ShowDetails.WHEN_AUTHORIZED + && (securityContext.getPrincipal() == null || !isUserInRole(securityContext)))) { return false; } return true; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java index 1a5ef2ad607..689ea9d46de 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java @@ -46,48 +46,38 @@ public class ReactiveHealthEndpointWebExtension { @ReadOperation public Mono> health(SecurityContext securityContext) { - return this.delegate.health() - .map((health) -> this.responseMapper.map(health, securityContext)); + return this.delegate.health().map((health) -> this.responseMapper.map(health, securityContext)); } @ReadOperation - public Mono> healthForComponent( - SecurityContext securityContext, @Selector String component) { - return responseFromIndicator(getNestedHealthIndicator(this.delegate, component), - securityContext); + public Mono> healthForComponent(SecurityContext securityContext, + @Selector String component) { + return responseFromIndicator(getNestedHealthIndicator(this.delegate, component), securityContext); } @ReadOperation - public Mono> healthForComponentInstance( - SecurityContext securityContext, @Selector String component, - @Selector String instance) { - ReactiveHealthIndicator indicator = getNestedHealthIndicator(this.delegate, - component); + public Mono> healthForComponentInstance(SecurityContext securityContext, + @Selector String component, @Selector String instance) { + ReactiveHealthIndicator indicator = getNestedHealthIndicator(this.delegate, component); if (indicator != null) { indicator = getNestedHealthIndicator(indicator, instance); } return responseFromIndicator(indicator, securityContext); } - public Mono> health(SecurityContext securityContext, - ShowDetails showDetails) { - return this.delegate.health().map((health) -> this.responseMapper.map(health, - securityContext, showDetails)); + public Mono> health(SecurityContext securityContext, ShowDetails showDetails) { + return this.delegate.health().map((health) -> this.responseMapper.map(health, securityContext, showDetails)); } - private Mono> responseFromIndicator( - ReactiveHealthIndicator indicator, SecurityContext securityContext) { + private Mono> responseFromIndicator(ReactiveHealthIndicator indicator, + SecurityContext securityContext) { return (indicator != null) - ? indicator.health() - .map((health) -> this.responseMapper.map(health, securityContext)) - : Mono.empty(); + ? indicator.health().map((health) -> this.responseMapper.map(health, securityContext)) : Mono.empty(); } - private ReactiveHealthIndicator getNestedHealthIndicator( - ReactiveHealthIndicator healthIndicator, String name) { + private ReactiveHealthIndicator getNestedHealthIndicator(ReactiveHealthIndicator healthIndicator, String name) { if (healthIndicator instanceof CompositeReactiveHealthIndicator) { - return ((CompositeReactiveHealthIndicator) healthIndicator).getRegistry() - .get(name); + return ((CompositeReactiveHealthIndicator) healthIndicator).getRegistry().get(name); } return null; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactory.java index 038a601a77b..b4bcde5745a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class ReactiveHealthIndicatorRegistryFactory { private final Function healthIndicatorNameFactory; - public ReactiveHealthIndicatorRegistryFactory( - Function healthIndicatorNameFactory) { + public ReactiveHealthIndicatorRegistryFactory(Function healthIndicatorNameFactory) { this.healthIndicatorNameFactory = healthIndicatorNameFactory; } @@ -57,35 +56,29 @@ public class ReactiveHealthIndicatorRegistryFactory { public ReactiveHealthIndicatorRegistry createReactiveHealthIndicatorRegistry( Map reactiveHealthIndicators, Map healthIndicators) { - Assert.notNull(reactiveHealthIndicators, - "ReactiveHealthIndicators must not be null"); - return initialize(new DefaultReactiveHealthIndicatorRegistry(), - reactiveHealthIndicators, healthIndicators); + Assert.notNull(reactiveHealthIndicators, "ReactiveHealthIndicators must not be null"); + return initialize(new DefaultReactiveHealthIndicatorRegistry(), reactiveHealthIndicators, healthIndicators); } protected T initialize(T registry, Map reactiveHealthIndicators, Map healthIndicators) { - merge(reactiveHealthIndicators, healthIndicators) - .forEach((beanName, indicator) -> { - String name = this.healthIndicatorNameFactory.apply(beanName); - registry.register(name, indicator); - }); + merge(reactiveHealthIndicators, healthIndicators).forEach((beanName, indicator) -> { + String name = this.healthIndicatorNameFactory.apply(beanName); + registry.register(name, indicator); + }); return registry; } - private Map merge( - Map reactiveHealthIndicators, + private Map merge(Map reactiveHealthIndicators, Map healthIndicators) { if (ObjectUtils.isEmpty(healthIndicators)) { return reactiveHealthIndicators; } - Map allIndicators = new LinkedHashMap<>( - reactiveHealthIndicators); + Map allIndicators = new LinkedHashMap<>(reactiveHealthIndicators); healthIndicators.forEach((beanName, indicator) -> { String name = this.healthIndicatorNameFactory.apply(beanName); - allIndicators.computeIfAbsent(name, - (n) -> new HealthIndicatorReactiveAdapter(indicator)); + allIndicators.computeIfAbsent(name, (n) -> new HealthIndicatorReactiveAdapter(indicator)); }); return allIndicators; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/EnvironmentInfoContributor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/EnvironmentInfoContributor.java index 4d9d33d9ce9..700d522ddde 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/EnvironmentInfoContributor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/EnvironmentInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.core.env.ConfigurableEnvironment; */ public class EnvironmentInfoContributor implements InfoContributor { - private static final Bindable> STRING_OBJECT_MAP = Bindable - .mapOf(String.class, Object.class); + private static final Bindable> STRING_OBJECT_MAP = Bindable.mapOf(String.class, Object.class); private final ConfigurableEnvironment environment; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java index fc52ac8b23f..7c9ba8a0d9f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,10 +64,8 @@ public class GitInfoContributor extends InfoPropertiesInfoContributor content) { - replaceValue(getNestedMap(content, "commit"), "time", - getProperties().getCommitTime()); - replaceValue(getNestedMap(content, "build"), "time", - getProperties().getInstant("build.time")); + replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime()); + replaceValue(getNestedMap(content, "build"), "time", getProperties().getInstant("build.time")); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java index b6266180a59..2227ac96cc4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ public final class Info { public T get(String id, Class type) { Object value = get(id); if (value != null && type != null && !type.isInstance(value)) { - throw new IllegalStateException("Info entry is not of required type [" - + type.getName() + "]: " + value); + throw new IllegalStateException("Info entry is not of required type [" + type.getName() + "]: " + value); } return (T) value; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java index 8289ae39515..4f63d06cabb 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,11 +36,9 @@ import org.springframework.util.StringUtils; * @author Madhura Bhave * @since 1.4.0 */ -public abstract class InfoPropertiesInfoContributor - implements InfoContributor { +public abstract class InfoPropertiesInfoContributor implements InfoContributor { - private static final Bindable> STRING_OBJECT_MAP = Bindable - .mapOf(String.class, Object.class); + private static final Bindable> STRING_OBJECT_MAP = Bindable.mapOf(String.class, Object.class); private final T properties; @@ -92,8 +90,8 @@ public abstract class InfoPropertiesInfoContributor * @return the raw content */ protected Map extractContent(PropertySource propertySource) { - return new Binder(ConfigurationPropertySources.from(propertySource)) - .bind("", STRING_OBJECT_MAP).orElseGet(LinkedHashMap::new); + return new Binder(ConfigurationPropertySources.from(propertySource)).bind("", STRING_OBJECT_MAP) + .orElseGet(LinkedHashMap::new); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicator.java index 6e9f8aaf25f..25cd37e82de 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ import org.springframework.util.StringUtils; * @author Arthur Kalimullin * @since 2.0.0 */ -public class DataSourceHealthIndicator extends AbstractHealthIndicator - implements InitializingBean { +public class DataSourceHealthIndicator extends AbstractHealthIndicator implements InitializingBean { private static final String DEFAULT_QUERY = "SELECT 1"; @@ -91,8 +90,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator @Override public void afterPropertiesSet() throws Exception { - Assert.state(this.dataSource != null, - "DataSource for DataSourceHealthIndicator must be specified"); + Assert.state(this.dataSource != null, "DataSource for DataSourceHealthIndicator must be specified"); } @Override @@ -112,8 +110,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator if (StringUtils.hasText(validationQuery)) { try { // Avoid calling getObject as it breaks MySQL on Java 7 - List results = this.jdbcTemplate.query(validationQuery, - new SingleColumnRowMapper()); + List results = this.jdbcTemplate.query(validationQuery, new SingleColumnRowMapper()); Object result = DataAccessUtils.requiredSingleResult(results); builder.withDetail("result", result); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java index 09767ae35c6..dfbf150b199 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ public class JmsHealthIndicator extends AbstractHealthIndicator { protected void doHealthCheck(Health.Builder builder) throws Exception { try (Connection connection = this.connectionFactory.createConnection()) { new MonitoredConnection(connection).start(); - builder.up().withDetail("provider", - connection.getMetaData().getJMSProviderName()); + builder.up().withDetail("provider", connection.getMetaData().getJMSProviderName()); } } @@ -70,8 +69,8 @@ public class JmsHealthIndicator extends AbstractHealthIndicator { new Thread(() -> { try { if (!this.latch.await(5, TimeUnit.SECONDS)) { - JmsHealthIndicator.this.logger.warn( - "Connection failed to start within 5 seconds and will be closed."); + JmsHealthIndicator.this.logger + .warn("Connection failed to start within 5 seconds and will be closed."); closeConnection(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java index d2029b2ab84..40a5d029aa6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java @@ -65,18 +65,17 @@ public class LiquibaseEndpoint { DatabaseFactory factory = DatabaseFactory.getInstance(); StandardChangeLogHistoryService service = new StandardChangeLogHistoryService(); this.context.getBeansOfType(SpringLiquibase.class) - .forEach((name, liquibase) -> liquibaseBeans.put(name, - createReport(liquibase, service, factory))); + .forEach((name, liquibase) -> liquibaseBeans.put(name, createReport(liquibase, service, factory))); ApplicationContext parent = target.getParent(); - contextBeans.put(target.getId(), new ContextLiquibaseBeans(liquibaseBeans, - (parent != null) ? parent.getId() : null)); + contextBeans.put(target.getId(), + new ContextLiquibaseBeans(liquibaseBeans, (parent != null) ? parent.getId() : null)); target = parent; } return new ApplicationLiquibaseBeans(contextBeans); } - private LiquibaseBean createReport(SpringLiquibase liquibase, - ChangeLogHistoryService service, DatabaseFactory factory) { + private LiquibaseBean createReport(SpringLiquibase liquibase, ChangeLogHistoryService service, + DatabaseFactory factory) { try { DataSource dataSource = liquibase.getDataSource(); JdbcConnection connection = new JdbcConnection(dataSource.getConnection()); @@ -87,13 +86,11 @@ public class LiquibaseEndpoint { if (StringUtils.hasText(defaultSchema)) { database.setDefaultSchemaName(defaultSchema); } - database.setDatabaseChangeLogTableName( - liquibase.getDatabaseChangeLogTable()); - database.setDatabaseChangeLogLockTableName( - liquibase.getDatabaseChangeLogLockTable()); + database.setDatabaseChangeLogTableName(liquibase.getDatabaseChangeLogTable()); + database.setDatabaseChangeLogLockTableName(liquibase.getDatabaseChangeLogLockTable()); service.setDatabase(database); - return new LiquibaseBean(service.getRanChangeSets().stream() - .map(ChangeSet::new).collect(Collectors.toList())); + return new LiquibaseBean( + service.getRanChangeSets().stream().map(ChangeSet::new).collect(Collectors.toList())); } finally { if (database != null) { @@ -137,8 +134,7 @@ public class LiquibaseEndpoint { private final String parentId; - private ContextLiquibaseBeans(Map liquibaseBeans, - String parentId) { + private ContextLiquibaseBeans(Map liquibaseBeans, String parentId) { this.liquibaseBeans = liquibaseBeans; this.parentId = parentId; } @@ -207,15 +203,14 @@ public class LiquibaseEndpoint { this.changeLog = ranChangeSet.getChangeLog(); this.comments = ranChangeSet.getComments(); this.contexts = ranChangeSet.getContextExpression().getContexts(); - this.dateExecuted = Instant - .ofEpochMilli(ranChangeSet.getDateExecuted().getTime()); + this.dateExecuted = Instant.ofEpochMilli(ranChangeSet.getDateExecuted().getTime()); this.deploymentId = ranChangeSet.getDeploymentId(); this.description = ranChangeSet.getDescription(); this.execType = ranChangeSet.getExecType(); this.id = ranChangeSet.getId(); this.labels = ranChangeSet.getLabels().getLabels(); - this.checksum = ((ranChangeSet.getLastCheckSum() != null) - ? ranChangeSet.getLastCheckSum().toString() : null); + this.checksum = ((ranChangeSet.getLastCheckSum() != null) ? ranChangeSet.getLastCheckSum().toString() + : null); this.orderExecuted = ranChangeSet.getOrderExecuted(); this.tag = ranChangeSet.getTag(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/logging/LoggersEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/logging/LoggersEndpoint.java index 5d8d921f712..ac575565768 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/logging/LoggersEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/logging/LoggersEndpoint.java @@ -57,8 +57,7 @@ public class LoggersEndpoint { @ReadOperation public Map loggers() { - Collection configurations = this.loggingSystem - .getLoggerConfigurations(); + Collection configurations = this.loggingSystem.getLoggerConfigurations(); if (configurations == null) { return Collections.emptyMap(); } @@ -71,14 +70,12 @@ public class LoggersEndpoint { @ReadOperation public LoggerLevels loggerLevels(@Selector String name) { Assert.notNull(name, "Name must not be null"); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(name); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(name); return (configuration != null) ? new LoggerLevels(configuration) : null; } @WriteOperation - public void configureLogLevel(@Selector String name, - @Nullable LogLevel configuredLevel) { + public void configureLogLevel(@Selector String name, @Nullable LogLevel configuredLevel) { Assert.notNull(name, "Name must not be empty"); this.loggingSystem.setLogLevel(name, configuredLevel); } @@ -88,8 +85,7 @@ public class LoggersEndpoint { return new TreeSet<>(levels).descendingSet(); } - private Map getLoggers( - Collection configurations) { + private Map getLoggers(Collection configurations) { Map loggers = new LinkedHashMap<>(configurations.size()); for (LoggerConfiguration configuration : configurations) { loggers.put(configuration.getName(), new LoggerLevels(configuration)); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mail/MailHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mail/MailHealthIndicator.java index bdd789e5a53..a7abf862f64 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mail/MailHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mail/MailHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ public class MailHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Builder builder) throws Exception { - builder.withDetail("location", - this.mailSender.getHost() + ":" + this.mailSender.getPort()); + builder.withDetail("location", this.mailSender.getHost() + ":" + this.mailSender.getPort()); this.mailSender.testConnection(); builder.up(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java index 5c64e31470f..c2f9fee1fb1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java @@ -77,8 +77,7 @@ public class HeapDumpWebEndpoint { try { if (this.lock.tryLock(this.timeout, TimeUnit.MILLISECONDS)) { try { - return new WebEndpointResponse<>( - dumpHeap((live != null) ? live : true)); + return new WebEndpointResponse<>(dumpHeap((live != null) ? live : true)); } finally { this.lock.unlock(); @@ -89,12 +88,10 @@ public class HeapDumpWebEndpoint { Thread.currentThread().interrupt(); } catch (IOException ex) { - return new WebEndpointResponse<>( - WebEndpointResponse.STATUS_INTERNAL_SERVER_ERROR); + return new WebEndpointResponse<>(WebEndpointResponse.STATUS_INTERNAL_SERVER_ERROR); } catch (HeapDumperUnavailableException ex) { - return new WebEndpointResponse<>( - WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); + return new WebEndpointResponse<>(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); } return new WebEndpointResponse<>(WebEndpointResponse.STATUS_TOO_MANY_REQUESTS); } @@ -110,8 +107,7 @@ public class HeapDumpWebEndpoint { private File createTempFile(boolean live) throws IOException { String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(new Date()); - File file = File.createTempFile("heapdump" + date + (live ? "-live" : ""), - ".hprof"); + File file = File.createTempFile("heapdump" + date + (live ? "-live" : ""), ".hprof"); file.delete(); return file; } @@ -156,23 +152,21 @@ public class HeapDumpWebEndpoint { @SuppressWarnings("unchecked") protected HotSpotDiagnosticMXBeanHeapDumper() { try { - Class diagnosticMXBeanClass = ClassUtils.resolveClassName( - "com.sun.management.HotSpotDiagnosticMXBean", null); - this.diagnosticMXBean = ManagementFactory.getPlatformMXBean( - (Class) diagnosticMXBeanClass); - this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, - "dumpHeap", String.class, Boolean.TYPE); + Class diagnosticMXBeanClass = ClassUtils + .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); + this.diagnosticMXBean = ManagementFactory + .getPlatformMXBean((Class) diagnosticMXBeanClass); + this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, "dumpHeap", String.class, + Boolean.TYPE); } catch (Throwable ex) { - throw new HeapDumperUnavailableException( - "Unable to locate HotSpotDiagnosticMXBean", ex); + throw new HeapDumperUnavailableException("Unable to locate HotSpotDiagnosticMXBean", ex); } } @Override public void dumpHeap(File file, boolean live) { - ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, - file.getAbsolutePath(), live); + ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, file.getAbsolutePath(), live); } } @@ -245,9 +239,8 @@ public class HeapDumpWebEndpoint { Files.delete(getFile().toPath()); } catch (IOException ex) { - TemporaryFileSystemResource.this.logger.warn( - "Failed to delete temporary heap dump file '" + getFile() + "'", - ex); + TemporaryFileSystemResource.this.logger + .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/ThreadDumpEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/ThreadDumpEndpoint.java index 2f08efe6765..4e65ccd1cf0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/ThreadDumpEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/ThreadDumpEndpoint.java @@ -36,8 +36,7 @@ public class ThreadDumpEndpoint { @ReadOperation public ThreadDumpDescriptor threadDump() { - return new ThreadDumpDescriptor(Arrays - .asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true))); + return new ThreadDumpDescriptor(Arrays.asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true))); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java index 1789f58709d..e43eeb16315 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java @@ -65,8 +65,7 @@ public class MetricsEndpoint { private void collectNames(Set names, MeterRegistry registry) { if (registry instanceof CompositeMeterRegistry) { - ((CompositeMeterRegistry) registry).getRegistries() - .forEach((member) -> collectNames(names, member)); + ((CompositeMeterRegistry) registry).getRegistries().forEach((member) -> collectNames(names, member)); } else { registry.getMeters().stream().map(this::getName).forEach(names::add); @@ -78,11 +77,9 @@ public class MetricsEndpoint { } @ReadOperation - public MetricResponse metric(@Selector String requiredMetricName, - @Nullable List tag) { + public MetricResponse metric(@Selector String requiredMetricName, @Nullable List tag) { List tags = parseTags(tag); - Collection meters = findFirstMatchingMeters(this.registry, - requiredMetricName, tags); + Collection meters = findFirstMatchingMeters(this.registry, requiredMetricName, tags); if (meters.isEmpty()) { return null; } @@ -90,9 +87,8 @@ public class MetricsEndpoint { Map> availableTags = getAvailableTags(meters); tags.forEach((t) -> availableTags.remove(t.getKey())); Meter.Id meterId = meters.iterator().next().getId(); - return new MetricResponse(requiredMetricName, meterId.getDescription(), - meterId.getBaseUnit(), asList(samples, Sample::new), - asList(availableTags, AvailableTag::new)); + return new MetricResponse(requiredMetricName, meterId.getDescription(), meterId.getBaseUnit(), + asList(samples, Sample::new), asList(availableTags, AvailableTag::new)); } private List parseTags(List tags) { @@ -112,20 +108,17 @@ public class MetricsEndpoint { return Tag.of(parts[0], parts[1]); } - private Collection findFirstMatchingMeters(MeterRegistry registry, String name, - Iterable tags) { + private Collection findFirstMatchingMeters(MeterRegistry registry, String name, Iterable tags) { if (registry instanceof CompositeMeterRegistry) { return findFirstMatchingMeters((CompositeMeterRegistry) registry, name, tags); } return registry.find(name).tags(tags).meters(); } - private Collection findFirstMatchingMeters(CompositeMeterRegistry composite, - String name, Iterable tags) { - return composite.getRegistries().stream() - .map((registry) -> findFirstMatchingMeters(registry, name, tags)) - .filter((matching) -> !matching.isEmpty()).findFirst() - .orElse(Collections.emptyList()); + private Collection findFirstMatchingMeters(CompositeMeterRegistry composite, String name, + Iterable tags) { + return composite.getRegistries().stream().map((registry) -> findFirstMatchingMeters(registry, name, tags)) + .filter((matching) -> !matching.isEmpty()).findFirst().orElse(Collections.emptyList()); } private Map getSamples(Collection meters) { @@ -135,8 +128,8 @@ public class MetricsEndpoint { } private void mergeMeasurements(Map samples, Meter meter) { - meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(), - measurement.getValue(), mergeFunction(measurement.getStatistic()))); + meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(), measurement.getValue(), + mergeFunction(measurement.getStatistic()))); } private BiFunction mergeFunction(Statistic statistic) { @@ -164,8 +157,7 @@ public class MetricsEndpoint { } private List asList(Map map, BiFunction mapper) { - return map.entrySet().stream() - .map((entry) -> mapper.apply(entry.getKey(), entry.getValue())) + return map.entrySet().stream().map((entry) -> mapper.apply(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); } @@ -201,8 +193,8 @@ public class MetricsEndpoint { private final List availableTags; - MetricResponse(String name, String description, String baseUnit, - List measurements, List availableTags) { + MetricResponse(String name, String description, String baseUnit, List measurements, + List availableTags) { this.name = name; this.description = description; this.baseUnit = baseUnit; @@ -280,8 +272,7 @@ public class MetricsEndpoint { @Override public String toString() { - return "MeasurementSample{" + "statistic=" + this.statistic + ", value=" - + this.value + '}'; + return "MeasurementSample{" + "statistic=" + this.statistic + ", value=" + this.value + '}'; } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetrics.java index 802d7866541..911f858e57a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ public class RabbitMetrics implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { - this.connectionFactory.setMetricsCollector( - new MicrometerMetricsCollector(registry, "rabbitmq", this.tags)); + this.connectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry, "rabbitmq", this.tags)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java index b6b1c45247c..61cbd08e11d 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ public class CacheMetricsRegistrar { * @param binderProviders the {@link CacheMeterBinderProvider} instances that should * be used to detect compatible caches */ - public CacheMetricsRegistrar(MeterRegistry registry, - Collection> binderProviders) { + public CacheMetricsRegistrar(MeterRegistry registry, Collection> binderProviders) { this.registry = registry; this.binderProviders = binderProviders; } @@ -72,12 +71,10 @@ public class CacheMetricsRegistrar { @SuppressWarnings({ "unchecked" }) private MeterBinder getMeterBinder(Cache cache, Tags tags) { Tags cacheTags = tags.and(getAdditionalTags(cache)); - return LambdaSafe - .callbacks(CacheMeterBinderProvider.class, this.binderProviders, cache) + return LambdaSafe.callbacks(CacheMeterBinderProvider.class, this.binderProviders, cache) .withLogger(CacheMetricsRegistrar.class) - .invokeAnd((binderProvider) -> binderProvider.getMeterBinder(cache, - cacheTags)) - .filter(Objects::nonNull).findFirst().orElse(null); + .invokeAnd((binderProvider) -> binderProvider.getMeterBinder(cache, cacheTags)).filter(Objects::nonNull) + .findFirst().orElse(null); } /** @@ -90,8 +87,7 @@ public class CacheMetricsRegistrar { } private Cache unwrapIfNecessary(Cache cache) { - if (ClassUtils.isPresent( - "org.springframework.cache.transaction.TransactionAwareCacheDecorator", + if (ClassUtils.isPresent("org.springframework.cache.transaction.TransactionAwareCacheDecorator", getClass().getClassLoader())) { return TransactionAwareCacheDecoratorHandler.unwrapIfNecessary(cache); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProvider.java index 77155a42ecd..38d13aa101c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.cache.caffeine.CaffeineCache; * @author Stephane Nicoll * @since 2.0.0 */ -public class CaffeineCacheMeterBinderProvider - implements CacheMeterBinderProvider { +public class CaffeineCacheMeterBinderProvider implements CacheMeterBinderProvider { @Override public MeterBinder getMeterBinder(CaffeineCache cache, Iterable tags) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProvider.java index 32c58d82025..b848b8f50c9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.cache.ehcache.EhCacheCache; * @author Stephane Nicoll * @since 2.0.0 */ -public class EhCache2CacheMeterBinderProvider - implements CacheMeterBinderProvider { +public class EhCache2CacheMeterBinderProvider implements CacheMeterBinderProvider { @Override public MeterBinder getMeterBinder(EhCacheCache cache, Iterable tags) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java index b17c486aecc..8319ecabc5e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import io.micrometer.core.instrument.binder.cache.HazelcastCacheMetrics; * @author Stephane Nicoll * @since 2.0.0 */ -public class HazelcastCacheMeterBinderProvider - implements CacheMeterBinderProvider { +public class HazelcastCacheMeterBinderProvider implements CacheMeterBinderProvider { @Override public MeterBinder getMeterBinder(HazelcastCache cache, Iterable tags) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProvider.java index ada8f92a720..74b7d2255be 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.cache.jcache.JCacheCache; * @author Stephane Nicoll * @since 2.0.0 */ -public class JCacheCacheMeterBinderProvider - implements CacheMeterBinderProvider { +public class JCacheCacheMeterBinderProvider implements CacheMeterBinderProvider { @Override public MeterBinder getMeterBinder(JCacheCache cache, Iterable tags) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java index 8f8d41bf869..1960ed6e075 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ import org.springframework.util.StringUtils; */ public class PrometheusPushGatewayManager { - private static final Log logger = LogFactory - .getLog(PrometheusPushGatewayManager.class); + private static final Log logger = LogFactory.getLog(PrometheusPushGatewayManager.class); private final PushGateway pushGateway; @@ -72,11 +71,9 @@ public class PrometheusPushGatewayManager { * @param shutdownOperation the shutdown operation that should be performed when * context is closed. */ - public PrometheusPushGatewayManager(PushGateway pushGateway, - CollectorRegistry registry, Duration pushRate, String job, - Map groupingKeys, ShutdownOperation shutdownOperation) { - this(pushGateway, registry, new PushGatewayTaskScheduler(), pushRate, job, - groupingKeys, shutdownOperation); + public PrometheusPushGatewayManager(PushGateway pushGateway, CollectorRegistry registry, Duration pushRate, + String job, Map groupingKeys, ShutdownOperation shutdownOperation) { + this(pushGateway, registry, new PushGatewayTaskScheduler(), pushRate, job, groupingKeys, shutdownOperation); } /** @@ -90,10 +87,8 @@ public class PrometheusPushGatewayManager { * @param shutdownOperation the shutdown operation that should be performed when * context is closed. */ - public PrometheusPushGatewayManager(PushGateway pushGateway, - CollectorRegistry registry, TaskScheduler scheduler, Duration pushRate, - String job, Map groupingKey, - ShutdownOperation shutdownOperation) { + public PrometheusPushGatewayManager(PushGateway pushGateway, CollectorRegistry registry, TaskScheduler scheduler, + Duration pushRate, String job, Map groupingKey, ShutdownOperation shutdownOperation) { Assert.notNull(pushGateway, "PushGateway must not be null"); Assert.notNull(registry, "Registry must not be null"); Assert.notNull(scheduler, "Scheduler must not be null"); @@ -103,8 +98,7 @@ public class PrometheusPushGatewayManager { this.registry = registry; this.job = job; this.groupingKey = groupingKey; - this.shutdownOperation = (shutdownOperation != null) ? shutdownOperation - : ShutdownOperation.NONE; + this.shutdownOperation = (shutdownOperation != null) ? shutdownOperation : ShutdownOperation.NONE; this.scheduler = scheduler; this.scheduled = this.scheduler.scheduleAtFixedRate(this::push, pushRate); } @@ -191,8 +185,7 @@ public class PrometheusPushGatewayManager { } @Override - public ScheduledExecutorService getScheduledExecutor() - throws IllegalStateException { + public ScheduledExecutorService getScheduledExecutor() throws IllegalStateException { return Executors.newSingleThreadScheduledExecutor(this::newThread); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java index 07196e887f8..d1387062fbf 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,21 +48,17 @@ public class DataSourcePoolMetrics implements MeterBinder { private final Iterable tags; - public DataSourcePoolMetrics(DataSource dataSource, - Collection metadataProviders, + public DataSourcePoolMetrics(DataSource dataSource, Collection metadataProviders, String dataSourceName, Iterable tags) { - this(dataSource, new CompositeDataSourcePoolMetadataProvider(metadataProviders), - dataSourceName, tags); + this(dataSource, new CompositeDataSourcePoolMetadataProvider(metadataProviders), dataSourceName, tags); } - public DataSourcePoolMetrics(DataSource dataSource, - DataSourcePoolMetadataProvider metadataProvider, String name, + public DataSourcePoolMetrics(DataSource dataSource, DataSourcePoolMetadataProvider metadataProvider, String name, Iterable tags) { Assert.notNull(dataSource, "DataSource must not be null"); Assert.notNull(metadataProvider, "MetadataProvider must not be null"); this.dataSource = dataSource; - this.metadataProvider = new CachingDataSourcePoolMetadataProvider( - metadataProvider); + this.metadataProvider = new CachingDataSourcePoolMetadataProvider(metadataProvider); this.tags = Tags.concat(tags, "name", name); } @@ -75,29 +71,26 @@ public class DataSourcePoolMetrics implements MeterBinder { } } - private void bindPoolMetadata(MeterRegistry registry, - String metricName, Function function) { - bindDataSource(registry, metricName, - this.metadataProvider.getValueFunction(function)); + private void bindPoolMetadata(MeterRegistry registry, String metricName, + Function function) { + bindDataSource(registry, metricName, this.metadataProvider.getValueFunction(function)); } - private void bindDataSource(MeterRegistry registry, - String metricName, Function function) { + private void bindDataSource(MeterRegistry registry, String metricName, + Function function) { if (function.apply(this.dataSource) != null) { registry.gauge("jdbc.connections." + metricName, this.tags, this.dataSource, (m) -> function.apply(m).doubleValue()); } } - private static class CachingDataSourcePoolMetadataProvider - implements DataSourcePoolMetadataProvider { + private static class CachingDataSourcePoolMetadataProvider implements DataSourcePoolMetadataProvider { private static final Map cache = new ConcurrentReferenceHashMap<>(); private final DataSourcePoolMetadataProvider metadataProvider; - CachingDataSourcePoolMetadataProvider( - DataSourcePoolMetadataProvider metadataProvider) { + CachingDataSourcePoolMetadataProvider(DataSourcePoolMetadataProvider metadataProvider) { this.metadataProvider = metadataProvider; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/DefaultRestTemplateExchangeTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/DefaultRestTemplateExchangeTagsProvider.java index 5acd15aa196..63b953d41a5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/DefaultRestTemplateExchangeTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/DefaultRestTemplateExchangeTagsProvider.java @@ -31,18 +31,14 @@ import org.springframework.util.StringUtils; * @author Nishant Raut * @since 2.0.0 */ -public class DefaultRestTemplateExchangeTagsProvider - implements RestTemplateExchangeTagsProvider { +public class DefaultRestTemplateExchangeTagsProvider implements RestTemplateExchangeTagsProvider { @Override - public Iterable getTags(String urlTemplate, HttpRequest request, - ClientHttpResponse response) { - Tag uriTag = (StringUtils.hasText(urlTemplate) - ? RestTemplateExchangeTags.uri(urlTemplate) + public Iterable getTags(String urlTemplate, HttpRequest request, ClientHttpResponse response) { + Tag uriTag = (StringUtils.hasText(urlTemplate) ? RestTemplateExchangeTags.uri(urlTemplate) : RestTemplateExchangeTags.uri(request)); return Arrays.asList(RestTemplateExchangeTags.method(request), uriTag, - RestTemplateExchangeTags.status(response), - RestTemplateExchangeTags.clientName(request), + RestTemplateExchangeTags.status(response), RestTemplateExchangeTags.clientName(request), RestTemplateExchangeTags.outcome(response)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java index 6962e25e8c2..6de494e1622 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java @@ -42,8 +42,7 @@ import org.springframework.web.util.UriTemplateHandler; */ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { - private static final ThreadLocal urlTemplate = new NamedThreadLocal<>( - "Rest Template URL Template"); + private static final ThreadLocal urlTemplate = new NamedThreadLocal<>("Rest Template URL Template"); private final MeterRegistry meterRegistry; @@ -62,8 +61,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto * {@link #MetricsClientHttpRequestInterceptor(MeterRegistry, RestTemplateExchangeTagsProvider, String, AutoTimer)} */ @Deprecated - MetricsClientHttpRequestInterceptor(MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider tagProvider, String metricName) { + MetricsClientHttpRequestInterceptor(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider tagProvider, + String metricName) { this(meterRegistry, tagProvider, metricName, AutoTimer.ENABLED); } @@ -75,9 +74,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto * @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing * @since 2.2.0 */ - MetricsClientHttpRequestInterceptor(MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider tagProvider, String metricName, - AutoTimer autoTimer) { + MetricsClientHttpRequestInterceptor(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider tagProvider, + String metricName, AutoTimer autoTimer) { this.tagProvider = tagProvider; this.meterRegistry = meterRegistry; this.metricName = metricName; @@ -85,8 +83,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto } @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { if (!this.autoTimer.isEnabled()) { return execution.execute(request, body); } @@ -97,8 +95,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto return response; } finally { - getTimeBuilder(request, response).register(this.meterRegistry) - .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); + getTimeBuilder(request, response).register(this.meterRegistry).record(System.nanoTime() - startTime, + TimeUnit.NANOSECONDS); urlTemplate.remove(); } } @@ -121,8 +119,7 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto }; } - private Timer.Builder getTimeBuilder(HttpRequest request, - ClientHttpResponse response) { + private Timer.Builder getTimeBuilder(HttpRequest request, ClientHttpResponse response) { return this.autoTimer.builder(this.metricName) .tags(this.tagProvider.getTags(urlTemplate.get(), request, response)) .description("Timer of RestTemplate operation"); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizer.java index 2688df056e9..889d9b28d0b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizer.java @@ -50,8 +50,8 @@ public class MetricsRestTemplateCustomizer implements RestTemplateCustomizer { * {@link #MetricsRestTemplateCustomizer(MeterRegistry, RestTemplateExchangeTagsProvider, String, AutoTimer)} */ @Deprecated - public MetricsRestTemplateCustomizer(MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider tagProvider, String metricName) { + public MetricsRestTemplateCustomizer(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider tagProvider, + String metricName) { this(meterRegistry, tagProvider, metricName, AutoTimer.ENABLED); } @@ -66,11 +66,9 @@ public class MetricsRestTemplateCustomizer implements RestTemplateCustomizer { * @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing * @since 2.2.0 */ - public MetricsRestTemplateCustomizer(MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider tagProvider, String metricName, - AutoTimer autoTimer) { - this.interceptor = new MetricsClientHttpRequestInterceptor(meterRegistry, - tagProvider, metricName, autoTimer); + public MetricsRestTemplateCustomizer(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider tagProvider, + String metricName, AutoTimer autoTimer) { + this.interceptor = new MetricsClientHttpRequestInterceptor(meterRegistry, tagProvider, metricName, autoTimer); } @Override @@ -78,8 +76,7 @@ public class MetricsRestTemplateCustomizer implements RestTemplateCustomizer { UriTemplateHandler templateHandler = restTemplate.getUriTemplateHandler(); templateHandler = this.interceptor.createUriTemplateHandler(templateHandler); restTemplate.setUriTemplateHandler(templateHandler); - List existingInterceptors = restTemplate - .getInterceptors(); + List existingInterceptors = restTemplate.getInterceptors(); if (!existingInterceptors.contains(this.interceptor)) { List interceptors = new ArrayList<>(); interceptors.add(this.interceptor); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsProvider.java index f512ac46def..4413ba41c3a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,6 @@ public interface RestTemplateExchangeTagsProvider { * @param response the response (may be {@code null} if the exchange failed) * @return the tags */ - Iterable getTags(String urlTemplate, HttpRequest request, - ClientHttpResponse response); + Iterable getTags(String urlTemplate, HttpRequest request, ClientHttpResponse response); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/JettyServerThreadPoolMetricsBinder.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/JettyServerThreadPoolMetricsBinder.java index 6bb590bb786..3703f22b473 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/JettyServerThreadPoolMetricsBinder.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/JettyServerThreadPoolMetricsBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.context.ApplicationListener; * @author Andy Wilkinson * @since 2.1.0 */ -public class JettyServerThreadPoolMetricsBinder - implements ApplicationListener { +public class JettyServerThreadPoolMetricsBinder implements ApplicationListener { private final MeterRegistry meterRegistry; @@ -48,8 +47,7 @@ public class JettyServerThreadPoolMetricsBinder this(meterRegistry, Collections.emptyList()); } - public JettyServerThreadPoolMetricsBinder(MeterRegistry meterRegistry, - Iterable tags) { + public JettyServerThreadPoolMetricsBinder(MeterRegistry meterRegistry, Iterable tags) { this.meterRegistry = meterRegistry; this.tags = tags; } @@ -59,15 +57,13 @@ public class JettyServerThreadPoolMetricsBinder ApplicationContext applicationContext = event.getApplicationContext(); ThreadPool threadPool = findThreadPool(applicationContext); if (threadPool != null) { - new JettyServerThreadPoolMetrics(threadPool, this.tags) - .bindTo(this.meterRegistry); + new JettyServerThreadPoolMetrics(threadPool, this.tags).bindTo(this.meterRegistry); } } private ThreadPool findThreadPool(ApplicationContext applicationContext) { if (applicationContext instanceof WebServerApplicationContext) { - WebServer webServer = ((WebServerApplicationContext) applicationContext) - .getWebServer(); + WebServer webServer = ((WebServerApplicationContext) applicationContext).getWebServer(); if (webServer instanceof JettyWebServer) { return ((JettyWebServer) webServer).getServer().getThreadPool(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProvider.java index 218fa8a6a2f..df3b6861e38 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProvider.java @@ -30,23 +30,19 @@ import org.springframework.web.reactive.function.client.ClientResponse; * @author Nishant Raut * @since 2.1.0 */ -public class DefaultWebClientExchangeTagsProvider - implements WebClientExchangeTagsProvider { +public class DefaultWebClientExchangeTagsProvider implements WebClientExchangeTagsProvider { @Override - public Iterable tags(ClientRequest request, ClientResponse response, - Throwable throwable) { + public Iterable tags(ClientRequest request, ClientResponse response, Throwable throwable) { Tag method = WebClientExchangeTags.method(request); Tag uri = WebClientExchangeTags.uri(request); Tag clientName = WebClientExchangeTags.clientName(request); if (response != null) { - return Arrays.asList(method, uri, clientName, - WebClientExchangeTags.status(response), + return Arrays.asList(method, uri, clientName, WebClientExchangeTags.status(response), WebClientExchangeTags.outcome(response)); } else { - return Arrays.asList(method, uri, clientName, - WebClientExchangeTags.status(throwable)); + return Arrays.asList(method, uri, clientName, WebClientExchangeTags.status(throwable)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizer.java index 4e64f7d8fdc..911c0c71bd1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizer.java @@ -44,8 +44,8 @@ public class MetricsWebClientCustomizer implements WebClientCustomizer { * {@link #MetricsWebClientCustomizer(MeterRegistry, WebClientExchangeTagsProvider, String, AutoTimer)} */ @Deprecated - public MetricsWebClientCustomizer(MeterRegistry meterRegistry, - WebClientExchangeTagsProvider tagProvider, String metricName) { + public MetricsWebClientCustomizer(MeterRegistry meterRegistry, WebClientExchangeTagsProvider tagProvider, + String metricName) { this(meterRegistry, tagProvider, metricName, AutoTimer.ENABLED); } @@ -59,11 +59,9 @@ public class MetricsWebClientCustomizer implements WebClientCustomizer { * @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing * @since 2.2.0 */ - public MetricsWebClientCustomizer(MeterRegistry meterRegistry, - WebClientExchangeTagsProvider tagProvider, String metricName, - AutoTimer autoTimer) { - this.filterFunction = new MetricsWebClientFilterFunction(meterRegistry, - tagProvider, metricName, autoTimer); + public MetricsWebClientCustomizer(MeterRegistry meterRegistry, WebClientExchangeTagsProvider tagProvider, + String metricName, AutoTimer autoTimer) { + this.filterFunction = new MetricsWebClientFilterFunction(meterRegistry, tagProvider, metricName, autoTimer); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java index 3c4692cecc4..8cc9506cf4e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java @@ -39,8 +39,8 @@ import org.springframework.web.reactive.function.client.ExchangeFunction; */ public class MetricsWebClientFilterFunction implements ExchangeFilterFunction { - private static final String METRICS_WEBCLIENT_START_TIME = MetricsWebClientFilterFunction.class - .getName() + ".START_TIME"; + private static final String METRICS_WEBCLIENT_START_TIME = MetricsWebClientFilterFunction.class.getName() + + ".START_TIME"; private final MeterRegistry meterRegistry; @@ -59,8 +59,8 @@ public class MetricsWebClientFilterFunction implements ExchangeFilterFunction { * {@link #MetricsWebClientFilterFunction(MeterRegistry, WebClientExchangeTagsProvider, String, AutoTimer)} */ @Deprecated - public MetricsWebClientFilterFunction(MeterRegistry meterRegistry, - WebClientExchangeTagsProvider tagProvider, String metricName) { + public MetricsWebClientFilterFunction(MeterRegistry meterRegistry, WebClientExchangeTagsProvider tagProvider, + String metricName) { this(meterRegistry, tagProvider, metricName, AutoTimer.ENABLED); } @@ -72,9 +72,8 @@ public class MetricsWebClientFilterFunction implements ExchangeFilterFunction { * @param autoTimer the auto-timer configuration or {@code null} to disable * @since 2.2.0 */ - public MetricsWebClientFilterFunction(MeterRegistry meterRegistry, - WebClientExchangeTagsProvider tagProvider, String metricName, - AutoTimer autoTimer) { + public MetricsWebClientFilterFunction(MeterRegistry meterRegistry, WebClientExchangeTagsProvider tagProvider, + String metricName, AutoTimer autoTimer) { this.meterRegistry = meterRegistry; this.tagProvider = tagProvider; this.metricName = metricName; @@ -92,10 +91,8 @@ public class MetricsWebClientFilterFunction implements ExchangeFilterFunction { ClientResponse response = signal.get(); Throwable throwable = signal.getThrowable(); Iterable tags = this.tagProvider.tags(request, response, throwable); - this.autoTimer.builder(this.metricName).tags(tags) - .description("Timer of WebClient operation") - .register(this.meterRegistry) - .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); + this.autoTimer.builder(this.metricName).tags(tags).description("Timer of WebClient operation") + .register(this.meterRegistry).record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } }).subscriberContext(this::putStartTime); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTags.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTags.java index a65525baef7..329ac637e8f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTags.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTags.java @@ -37,15 +37,13 @@ import org.springframework.web.reactive.function.client.WebClient; */ public final class WebClientExchangeTags { - private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() - + ".uriTemplate"; + private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; private static final Tag IO_ERROR = Tag.of("status", "IO_ERROR"); private static final Tag CLIENT_ERROR = Tag.of("status", "CLIENT_ERROR"); - private static final Pattern PATTERN_BEFORE_PATH = Pattern - .compile("^https?://[^/]+/"); + private static final Pattern PATTERN_BEFORE_PATH = Pattern.compile("^https?://[^/]+/"); private static final Tag CLIENT_NAME_NONE = Tag.of("clientName", "none"); @@ -80,8 +78,7 @@ public final class WebClientExchangeTags { * @return the uri tag */ public static Tag uri(ClientRequest request) { - String uri = (String) request.attribute(URI_TEMPLATE_ATTRIBUTE) - .orElseGet(() -> request.url().getPath()); + String uri = (String) request.attribute(URI_TEMPLATE_ATTRIBUTE).orElseGet(() -> request.url().getPath()); return Tag.of("uri", extractPath(uri)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsProvider.java index d71eba18b8b..6dc127956aa 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,6 @@ public interface WebClientExchangeTagsProvider { * @param throwable the exception (may be {@code null}) * @return tags to associate with metrics for the request and response exchange */ - Iterable tags(ClientRequest request, ClientResponse response, - Throwable throwable); + Iterable tags(ClientRequest request, ClientResponse response, Throwable throwable); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProvider.java index 09266b6baf9..fb54c496b9b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,11 +32,9 @@ import org.springframework.web.server.ServerWebExchange; public class DefaultWebFluxTagsProvider implements WebFluxTagsProvider { @Override - public Iterable httpRequestTags(ServerWebExchange exchange, - Throwable exception) { - return Arrays.asList(WebFluxTags.method(exchange), WebFluxTags.uri(exchange), - WebFluxTags.exception(exception), WebFluxTags.status(exchange), - WebFluxTags.outcome(exchange)); + public Iterable httpRequestTags(ServerWebExchange exchange, Throwable exception) { + return Arrays.asList(WebFluxTags.method(exchange), WebFluxTags.uri(exchange), WebFluxTags.exception(exception), + WebFluxTags.status(exchange), WebFluxTags.outcome(exchange)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java index 5ed64c563f6..b70d337d5cc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java @@ -59,8 +59,8 @@ public class MetricsWebFilter implements WebFilter { * {@link #MetricsWebFilter(MeterRegistry, WebFluxTagsProvider, String, AutoTimer)} */ @Deprecated - public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, - String metricName, boolean autoTimeRequests) { + public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, String metricName, + boolean autoTimeRequests) { this(registry, tagsProvider, metricName, AutoTimer.ENABLED); } @@ -72,8 +72,8 @@ public class MetricsWebFilter implements WebFilter { * @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing * @since 2.2.0 */ - public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, - String metricName, AutoTimer autoTimer) { + public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, String metricName, + AutoTimer autoTimer) { this.registry = registry; this.tagsProvider = tagsProvider; this.metricName = metricName; @@ -113,8 +113,8 @@ public class MetricsWebFilter implements WebFilter { private void record(ServerWebExchange exchange, long start, Throwable cause) { Iterable tags = this.tagsProvider.httpRequestTags(exchange, cause); - this.autoTimer.builder(this.metricName).tags(tags).register(this.registry) - .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); + this.autoTimer.builder(this.metricName).tags(tags).register(this.registry).record(System.nanoTime() - start, + TimeUnit.NANOSECONDS); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTags.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTags.java index 769da6d1030..aafee899515 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTags.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTags.java @@ -96,8 +96,7 @@ public final class WebFluxTags { * @return the uri tag derived from the exchange */ public static Tag uri(ServerWebExchange exchange) { - PathPattern pathPattern = exchange - .getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); + PathPattern pathPattern = exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); if (pathPattern != null) { return Tag.of("uri", pathPattern.getPatternString()); } @@ -132,8 +131,7 @@ public final class WebFluxTags { public static Tag exception(Throwable exception) { if (exception != null) { String simpleName = exception.getClass().getSimpleName(); - return Tag.of("exception", StringUtils.hasText(simpleName) ? simpleName - : exception.getClass().getName()); + return Tag.of("exception", StringUtils.hasText(simpleName) ? simpleName : exception.getClass().getName()); } return EXCEPTION_NONE; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/DefaultWebMvcTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/DefaultWebMvcTagsProvider.java index 1dbb5a95c07..6d7ed11d249 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/DefaultWebMvcTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/DefaultWebMvcTagsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,11 +31,10 @@ import io.micrometer.core.instrument.Tags; public class DefaultWebMvcTagsProvider implements WebMvcTagsProvider { @Override - public Iterable getTags(HttpServletRequest request, HttpServletResponse response, - Object handler, Throwable exception) { - return Tags.of(WebMvcTags.method(request), WebMvcTags.uri(request, response), - WebMvcTags.exception(exception), WebMvcTags.status(response), - WebMvcTags.outcome(response)); + public Iterable getTags(HttpServletRequest request, HttpServletResponse response, Object handler, + Throwable exception) { + return Tags.of(WebMvcTags.method(request), WebMvcTags.uri(request, response), WebMvcTags.exception(exception), + WebMvcTags.status(response), WebMvcTags.outcome(response)); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java index f6f775919eb..524a09b4491 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java @@ -57,15 +57,14 @@ public class LongTaskTimingHandlerInterceptor implements HandlerInterceptor { * @param registry the registry * @param tagsProvider the tags provider */ - public LongTaskTimingHandlerInterceptor(MeterRegistry registry, - WebMvcTagsProvider tagsProvider) { + public LongTaskTimingHandlerInterceptor(MeterRegistry registry, WebMvcTagsProvider tagsProvider) { this.registry = registry; this.tagsProvider = tagsProvider; } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, - Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { LongTaskTimingContext timingContext = LongTaskTimingContext.get(request); if (timingContext == null) { startAndAttachTimingContext(request, handler); @@ -74,8 +73,8 @@ public class LongTaskTimingHandlerInterceptor implements HandlerInterceptor { } @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, - Object handler, Exception ex) throws Exception { + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { if (!request.isAsyncStarted()) { stopLongTaskTimers(LongTaskTimingContext.get(request)); } @@ -83,15 +82,13 @@ public class LongTaskTimingHandlerInterceptor implements HandlerInterceptor { private void startAndAttachTimingContext(HttpServletRequest request, Object handler) { Set annotations = getTimedAnnotations(handler); - Collection longTaskTimerSamples = getLongTaskTimerSamples( - request, handler, annotations); - LongTaskTimingContext timingContext = new LongTaskTimingContext( - longTaskTimerSamples); + Collection longTaskTimerSamples = getLongTaskTimerSamples(request, handler, annotations); + LongTaskTimingContext timingContext = new LongTaskTimingContext(longTaskTimerSamples); timingContext.attachTo(request); } - private Collection getLongTaskTimerSamples( - HttpServletRequest request, Object handler, Set annotations) { + private Collection getLongTaskTimerSamples(HttpServletRequest request, Object handler, + Set annotations) { List samples = new ArrayList<>(); annotations.stream().filter(Timed::longTask).forEach((annotation) -> { Iterable tags = this.tagsProvider.getLongRequestTags(request, handler); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java index 645e95584bc..9bbd94ac9a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java @@ -71,8 +71,8 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { * {@link #WebMvcMetricsFilter(MeterRegistry, WebMvcTagsProvider, String, AutoTimer)} */ @Deprecated - public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider, - String metricName, boolean autoTimeRequests) { + public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider, String metricName, + boolean autoTimeRequests) { this(registry, tagsProvider, metricName, AutoTimer.ENABLED); } @@ -84,8 +84,8 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { * @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing * @since 2.2.0 */ - public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider, - String metricName, AutoTimer autoTimer) { + public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider, String metricName, + AutoTimer autoTimer) { this.registry = registry; this.tagsProvider = tagsProvider; this.metricName = metricName; @@ -98,8 +98,7 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { TimingContext timingContext = TimingContext.get(request); if (timingContext == null) { @@ -112,8 +111,7 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { // If async was started by something further down the chain we wait // until the second filter invocation (but we'll be using the // TimingContext that was attached to the first) - Throwable exception = (Throwable) request - .getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE); + Throwable exception = (Throwable) request.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE); record(timingContext, request, response, exception); } } @@ -135,8 +133,8 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { return timingContext; } - private void record(TimingContext timingContext, HttpServletRequest request, - HttpServletResponse response, Throwable exception) { + private void record(TimingContext timingContext, HttpServletRequest request, HttpServletResponse response, + Throwable exception) { Object handler = getHandler(request); Set annotations = getTimedAnnotations(handler); Timer.Sample timerSample = timingContext.getTimerSample(); @@ -175,15 +173,12 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { if (!annotations.isPresent(Timed.class)) { return Collections.emptySet(); } - return annotations.stream(Timed.class) - .collect(MergedAnnotationCollectors.toAnnotationSet()); + return annotations.stream(Timed.class).collect(MergedAnnotationCollectors.toAnnotationSet()); } - private Timer getTimer(Builder builder, Object handler, HttpServletRequest request, - HttpServletResponse response, Throwable exception) { - return builder - .tags(this.tagsProvider.getTags(request, response, handler, exception)) - .register(this.registry); + private Timer getTimer(Builder builder, Object handler, HttpServletRequest request, HttpServletResponse response, + Throwable exception) { + return builder.tags(this.tagsProvider.getTags(request, response, handler, exception)).register(this.registry); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTags.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTags.java index 13254c08a4a..477d7b42276 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTags.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTags.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,9 +91,7 @@ public final class WebMvcTags { * @return the status tag derived from the status of the response */ public static Tag status(HttpServletResponse response) { - return (response != null) - ? Tag.of("status", Integer.toString(response.getStatus())) - : STATUS_UNKNOWN; + return (response != null) ? Tag.of("status", Integer.toString(response.getStatus())) : STATUS_UNKNOWN; } /** @@ -141,13 +139,11 @@ public final class WebMvcTags { } private static String getMatchingPattern(HttpServletRequest request) { - PathPattern dataRestPathPattern = (PathPattern) request - .getAttribute(DATA_REST_PATH_PATTERN_ATTRIBUTE); + PathPattern dataRestPathPattern = (PathPattern) request.getAttribute(DATA_REST_PATH_PATTERN_ATTRIBUTE); if (dataRestPathPattern != null) { return dataRestPathPattern.getPatternString(); } - return (String) request - .getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); + return (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); } private static String getPathInfo(HttpServletRequest request) { @@ -166,8 +162,7 @@ public final class WebMvcTags { public static Tag exception(Throwable exception) { if (exception != null) { String simpleName = exception.getClass().getSimpleName(); - return Tag.of("exception", StringUtils.hasText(simpleName) ? simpleName - : exception.getClass().getName()); + return Tag.of("exception", StringUtils.hasText(simpleName) ? simpleName : exception.getClass().getName()); } return EXCEPTION_NONE; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTagsProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTagsProvider.java index c8fd567d49f..101ce828ba7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTagsProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTagsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ public interface WebMvcTagsProvider { * @param exception the current exception, if any * @return tags to associate with metrics for the request and response exchange */ - Iterable getTags(HttpServletRequest request, HttpServletResponse response, - Object handler, Throwable exception); + Iterable getTags(HttpServletRequest request, HttpServletResponse response, Object handler, + Throwable exception); /** * Provides tags to be used by {@link LongTaskTimer long task timers}. diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java index c9ec8de5884..689c41cdca4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ public class TomcatMetricsBinder implements ApplicationListener doHealthCheck(Health.Builder builder) { - Mono buildInfo = this.reactiveMongoTemplate - .executeCommand("{ buildInfo: 1 }"); + Mono buildInfo = this.reactiveMongoTemplate.executeCommand("{ buildInfo: 1 }"); return buildInfo.map((document) -> up(builder, document)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java index 39090dd3e40..a2824025a87 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,11 +67,9 @@ public class Neo4jHealthIndicator extends AbstractHealthIndicator { * @param builder the builder to add details to * @throws Exception if getting health details failed */ - protected void extractResult(Session session, Health.Builder builder) - throws Exception { + protected void extractResult(Session session, Health.Builder builder) throws Exception { Result result = session.query(CYPHER, Collections.emptyMap()); - builder.up().withDetail("nodes", - result.queryResults().iterator().next().get("nodes")); + builder.up().withDetail("nodes", result.queryResults().iterator().next().get("nodes")); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisHealthIndicator.java index 9886dc1612f..60a3cb2b21a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,12 +52,10 @@ public class RedisHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - RedisConnection connection = RedisConnectionUtils - .getConnection(this.redisConnectionFactory); + RedisConnection connection = RedisConnectionUtils.getConnection(this.redisConnectionFactory); try { if (connection instanceof RedisClusterConnection) { - ClusterInfo clusterInfo = ((RedisClusterConnection) connection) - .clusterGetClusterInfo(); + ClusterInfo clusterInfo = ((RedisClusterConnection) connection).clusterGetClusterInfo(); builder.up().withDetail("cluster_size", clusterInfo.getClusterSize()) .withDetail("slots_up", clusterInfo.getSlotsOk()) .withDetail("slots_fail", clusterInfo.getSlotsFail()); @@ -68,8 +66,7 @@ public class RedisHealthIndicator extends AbstractHealthIndicator { } } finally { - RedisConnectionUtils.releaseConnection(connection, - this.redisConnectionFactory); + RedisConnectionUtils.releaseConnection(connection, this.redisConnectionFactory); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java index f7b5a93a2e7..b9a735d6c06 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java @@ -39,32 +39,28 @@ public class RedisReactiveHealthIndicator extends AbstractReactiveHealthIndicato private final ReactiveRedisConnectionFactory connectionFactory; - public RedisReactiveHealthIndicator( - ReactiveRedisConnectionFactory connectionFactory) { + public RedisReactiveHealthIndicator(ReactiveRedisConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } @Override protected Mono doHealthCheck(Health.Builder builder) { - return getConnection() - .flatMap((connection) -> doHealthCheck(builder, connection)); + return getConnection().flatMap((connection) -> doHealthCheck(builder, connection)); } - private Mono doHealthCheck(Health.Builder builder, - ReactiveRedisConnection connection) { + private Mono doHealthCheck(Health.Builder builder, ReactiveRedisConnection connection) { return connection.serverCommands().info().map((info) -> up(builder, info)) .onErrorResume((ex) -> Mono.just(down(builder, ex))) .flatMap((health) -> connection.closeLater().thenReturn(health)); } private Mono getConnection() { - return Mono.fromSupplier(this.connectionFactory::getReactiveConnection) - .subscribeOn(Schedulers.parallel()); + return Mono.fromSupplier(this.connectionFactory::getReactiveConnection).subscribeOn(Schedulers.parallel()); } private Health up(Health.Builder builder, Properties info) { - return builder.up().withDetail(RedisHealthIndicator.VERSION, - info.getProperty(RedisHealthIndicator.REDIS_VERSION)).build(); + return builder.up() + .withDetail(RedisHealthIndicator.VERSION, info.getProperty(RedisHealthIndicator.REDIS_VERSION)).build(); } private Health down(Health.Builder builder, Throwable cause) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java index 6b70d89c549..1063877cfb8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java @@ -59,10 +59,9 @@ public class ScheduledTasksEndpoint { @ReadOperation public ScheduledTasksReport scheduledTasks() { - Map> descriptionsByType = this.scheduledTaskHolders - .stream().flatMap((holder) -> holder.getScheduledTasks().stream()) - .map(ScheduledTask::getTask).map(TaskDescription::of) - .filter(Objects::nonNull) + Map> descriptionsByType = this.scheduledTaskHolders.stream() + .flatMap((holder) -> holder.getScheduledTasks().stream()).map(ScheduledTask::getTask) + .map(TaskDescription::of).filter(Objects::nonNull) .collect(Collectors.groupingBy(TaskDescription::getType)); return new ScheduledTasksReport(descriptionsByType); } @@ -81,16 +80,11 @@ public class ScheduledTasksEndpoint { private final List custom; - private ScheduledTasksReport( - Map> descriptionsByType) { - this.cron = descriptionsByType.getOrDefault(TaskType.CRON, - Collections.emptyList()); - this.fixedDelay = descriptionsByType.getOrDefault(TaskType.FIXED_DELAY, - Collections.emptyList()); - this.fixedRate = descriptionsByType.getOrDefault(TaskType.FIXED_RATE, - Collections.emptyList()); - this.custom = descriptionsByType.getOrDefault(TaskType.CUSTOM_TRIGGER, - Collections.emptyList()); + private ScheduledTasksReport(Map> descriptionsByType) { + this.cron = descriptionsByType.getOrDefault(TaskType.CRON, Collections.emptyList()); + this.fixedDelay = descriptionsByType.getOrDefault(TaskType.FIXED_DELAY, Collections.emptyList()); + this.fixedRate = descriptionsByType.getOrDefault(TaskType.FIXED_RATE, Collections.emptyList()); + this.custom = descriptionsByType.getOrDefault(TaskType.CUSTOM_TRIGGER, Collections.emptyList()); } public List getCron() { @@ -119,14 +113,10 @@ public class ScheduledTasksEndpoint { private static final Map, Function> DESCRIBERS = new LinkedHashMap<>(); static { - DESCRIBERS.put(FixedRateTask.class, - (task) -> new FixedRateTaskDescription((FixedRateTask) task)); - DESCRIBERS.put(FixedDelayTask.class, - (task) -> new FixedDelayTaskDescription((FixedDelayTask) task)); - DESCRIBERS.put(CronTask.class, - (task) -> new CronTaskDescription((CronTask) task)); - DESCRIBERS.put(TriggerTask.class, - (task) -> describeTriggerTask((TriggerTask) task)); + DESCRIBERS.put(FixedRateTask.class, (task) -> new FixedRateTaskDescription((FixedRateTask) task)); + DESCRIBERS.put(FixedDelayTask.class, (task) -> new FixedDelayTaskDescription((FixedDelayTask) task)); + DESCRIBERS.put(CronTask.class, (task) -> new CronTaskDescription((CronTask) task)); + DESCRIBERS.put(TriggerTask.class, (task) -> describeTriggerTask((TriggerTask) task)); } private final TaskType type; @@ -134,10 +124,8 @@ public class ScheduledTasksEndpoint { private final RunnableDescription runnable; private static TaskDescription of(Task task) { - return DESCRIBERS.entrySet().stream() - .filter((entry) -> entry.getKey().isInstance(task)) - .map((entry) -> entry.getValue().apply(task)).findFirst() - .orElse(null); + return DESCRIBERS.entrySet().stream().filter((entry) -> entry.getKey().isInstance(task)) + .map((entry) -> entry.getValue().apply(task)).findFirst().orElse(null); } private static TaskDescription describeTriggerTask(TriggerTask triggerTask) { @@ -185,8 +173,7 @@ public class ScheduledTasksEndpoint { this.interval = task.getInterval(); } - protected IntervalTaskDescription(TaskType type, TriggerTask task, - PeriodicTrigger trigger) { + protected IntervalTaskDescription(TaskType type, TriggerTask task, PeriodicTrigger trigger) { super(type, task.getRunnable()); this.initialDelay = trigger.getInitialDelay(); this.interval = trigger.getPeriod(); @@ -290,8 +277,7 @@ public class ScheduledTasksEndpoint { private RunnableDescription(Runnable runnable) { if (runnable instanceof ScheduledMethodRunnable) { Method method = ((ScheduledMethodRunnable) runnable).getMethod(); - this.target = method.getDeclaringClass().getName() + "." - + method.getName(); + this.target = method.getDeclaringClass().getName() + "." + method.getName(); } else { this.target = runnable.getClass().getName(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java index 8e35b98889c..c02ef190474 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.security.authentication.event.AbstractAuthenticationE * @author Vedran Pavic * @since 1.3.0 */ -public abstract class AbstractAuthenticationAuditListener implements - ApplicationListener, ApplicationEventPublisherAware { +public abstract class AbstractAuthenticationAuditListener + implements ApplicationListener, ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java index f97731509cb..5ca0d852d42 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.security.access.event.AbstractAuthorizationEvent; * @author Vedran Pavic * @since 1.3.0 */ -public abstract class AbstractAuthorizationAuditListener implements - ApplicationListener, ApplicationEventPublisherAware { +public abstract class AbstractAuthorizationAuditListener + implements ApplicationListener, ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java index 28f886bd33a..c962548e1ce 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java @@ -80,8 +80,7 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } - publish(new AuditEvent(event.getAuthentication().getName(), - AUTHENTICATION_FAILURE, data)); + publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_FAILURE, data)); } private void onAuthenticationSuccessEvent(AuthenticationSuccessEvent event) { @@ -89,14 +88,12 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } - publish(new AuditEvent(event.getAuthentication().getName(), - AUTHENTICATION_SUCCESS, data)); + publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_SUCCESS, data)); } private static class WebAuditListener { - public void process(AuthenticationAuditListener listener, - AbstractAuthenticationEvent input) { + public void process(AuthenticationAuditListener listener, AbstractAuthenticationEvent input) { if (listener != null) { AuthenticationSwitchUserEvent event = (AuthenticationSwitchUserEvent) input; Map data = new HashMap<>(); @@ -106,8 +103,7 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList if (event.getTargetUser() != null) { data.put("target", event.getTargetUser().getUsername()); } - listener.publish(new AuditEvent(event.getAuthentication().getName(), - AUTHENTICATION_SWITCH, data)); + listener.publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_SWITCH, data)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java index a0a10607832..0120b8c6f19 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,21 +40,18 @@ public class AuthorizationAuditListener extends AbstractAuthorizationAuditListen @Override public void onApplicationEvent(AbstractAuthorizationEvent event) { if (event instanceof AuthenticationCredentialsNotFoundEvent) { - onAuthenticationCredentialsNotFoundEvent( - (AuthenticationCredentialsNotFoundEvent) event); + onAuthenticationCredentialsNotFoundEvent((AuthenticationCredentialsNotFoundEvent) event); } else if (event instanceof AuthorizationFailureEvent) { onAuthorizationFailureEvent((AuthorizationFailureEvent) event); } } - private void onAuthenticationCredentialsNotFoundEvent( - AuthenticationCredentialsNotFoundEvent event) { + private void onAuthenticationCredentialsNotFoundEvent(AuthenticationCredentialsNotFoundEvent event) { Map data = new HashMap<>(); data.put("type", event.getCredentialsNotFoundException().getClass().getName()); data.put("message", event.getCredentialsNotFoundException().getMessage()); - publish(new AuditEvent("", - AuthenticationAuditListener.AUTHENTICATION_FAILURE, data)); + publish(new AuditEvent("", AuthenticationAuditListener.AUTHENTICATION_FAILURE, data)); } private void onAuthorizationFailureEvent(AuthorizationFailureEvent event) { @@ -64,8 +61,7 @@ public class AuthorizationAuditListener extends AbstractAuthorizationAuditListen if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } - publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE, - data)); + publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE, data)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/session/SessionsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/session/SessionsEndpoint.java index 94fb8d7abac..d6ae25cb23a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/session/SessionsEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/session/SessionsEndpoint.java @@ -44,15 +44,13 @@ public class SessionsEndpoint { * Create a new {@link SessionsEndpoint} instance. * @param sessionRepository the session repository */ - public SessionsEndpoint( - FindByIndexNameSessionRepository sessionRepository) { + public SessionsEndpoint(FindByIndexNameSessionRepository sessionRepository) { this.sessionRepository = sessionRepository; } @ReadOperation public SessionsReport sessionsForUsername(String username) { - Map sessions = this.sessionRepository - .findByPrincipalName(username); + Map sessions = this.sessionRepository.findByPrincipalName(username); return new SessionsReport(sessions); } @@ -79,8 +77,7 @@ public class SessionsEndpoint { private final List sessions; public SessionsReport(Map sessions) { - this.sessions = sessions.values().stream().map(SessionDescriptor::new) - .collect(Collectors.toList()); + this.sessions = sessions.values().stream().map(SessionDescriptor::new).collect(Collectors.toList()); } public List getSessions() { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java index ce6058ec76c..a1005d86f13 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java @@ -62,14 +62,11 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator { builder.up(); } else { - logger.warn(String.format( - "Free disk space below threshold. " - + "Available: %d bytes (threshold: %s)", + logger.warn(String.format("Free disk space below threshold. " + "Available: %d bytes (threshold: %s)", diskFreeInBytes, this.threshold)); builder.down(); } - builder.withDetail("total", this.path.getTotalSpace()) - .withDetail("free", diskFreeInBytes) + builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes) .withDetail("threshold", this.threshold.toBytes()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java index 67d93217d02..6929e9535d8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,15 +66,13 @@ public class HttpExchangeTracer { * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ - public final void sendingResponse(HttpTrace trace, TraceableResponse response, - Supplier principal, Supplier sessionId) { - setIfIncluded(Include.TIME_TAKEN, - () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), + public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, + Supplier sessionId) { + setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); - trace.setResponse( - new HttpTrace.Response(new FilteredTraceableResponse(response))); + trace.setResponse(new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** @@ -89,21 +87,18 @@ public class HttpExchangeTracer { return this.includes.contains(include) ? valueSupplier.get() : null; } - private void setIfIncluded(Include include, Supplier supplier, - Consumer consumer) { + private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, - Supplier>> headersSupplier, - Predicate headerPredicate) { + Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } - return headersSupplier.get().entrySet().stream() - .filter((entry) -> headerPredicate.test(entry.getKey())) + return headersSupplier.get().entrySet().stream().filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @@ -127,8 +122,7 @@ public class HttpExchangeTracer { @Override public Map> getHeaders() { - Map> headers = getHeadersIfIncluded( - Include.REQUEST_HEADERS, this.delegate::getHeaders, + Map> headers = getHeadersIfIncluded(Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; @@ -139,8 +133,7 @@ public class HttpExchangeTracer { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { - return HttpExchangeTracer.this.includes - .contains(Include.AUTHORIZATION_HEADER); + return HttpExchangeTracer.this.includes.contains(Include.AUTHORIZATION_HEADER); } return true; } @@ -167,8 +160,7 @@ public class HttpExchangeTracer { @Override public Map> getHeaders() { - return getHeadersIfIncluded(Include.RESPONSE_HEADERS, - this.delegate::getHeaders, this::includedHeader); + return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpTrace.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpTrace.java index 75eacaa92e3..7ef35f5c079 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpTrace.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpTrace.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ public final class HttpTrace { * exchange, if known * @since 2.1.0 */ - public HttpTrace(Request request, Response response, Instant timestamp, - Principal principal, Session session, Long timeTaken) { + public HttpTrace(Request request, Response response, Instant timestamp, Principal principal, Session session, + Long timeTaken) { this.request = request; this.response = response; this.timestamp = timestamp; @@ -132,8 +132,7 @@ public final class HttpTrace { private final String remoteAddress; private Request(TraceableRequest request) { - this(request.getMethod(), request.getUri(), request.getHeaders(), - request.getRemoteAddress()); + this(request.getMethod(), request.getUri(), request.getHeaders(), request.getRemoteAddress()); } /** @@ -146,8 +145,7 @@ public final class HttpTrace { * @param remoteAddress remote address from which the request was sent, if known * @since 2.1.0 */ - public Request(String method, URI uri, Map> headers, - String remoteAddress) { + public Request(String method, URI uri, Map> headers, String remoteAddress) { this.method = method; this.uri = uri; this.headers = new LinkedHashMap<>(headers); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/MappingsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/MappingsEndpoint.java index 8da266c48a2..f5a312ba23b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/MappingsEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/MappingsEndpoint.java @@ -37,8 +37,7 @@ public class MappingsEndpoint { private final ApplicationContext context; - public MappingsEndpoint(Collection descriptionProviders, - ApplicationContext context) { + public MappingsEndpoint(Collection descriptionProviders, ApplicationContext context) { this.descriptionProviders = descriptionProviders; this.context = context; } @@ -56,11 +55,10 @@ public class MappingsEndpoint { private ContextMappings mappingsForContext(ApplicationContext applicationContext) { Map mappings = new HashMap<>(); - this.descriptionProviders - .forEach((provider) -> mappings.put(provider.getMappingName(), - provider.describeMappings(applicationContext))); - return new ContextMappings(mappings, (applicationContext.getParent() != null) - ? applicationContext.getId() : null); + this.descriptionProviders.forEach( + (provider) -> mappings.put(provider.getMappingName(), provider.describeMappings(applicationContext))); + return new ContextMappings(mappings, + (applicationContext.getParent() != null) ? applicationContext.getId() : null); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDescription.java index 9635459bedc..d9f00b40a6c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ public class DispatcherHandlerMappingDescription { private final DispatcherHandlerMappingDetails details; - DispatcherHandlerMappingDescription(String predicate, String handler, - DispatcherHandlerMappingDetails details) { + DispatcherHandlerMappingDescription(String predicate, String handler, DispatcherHandlerMappingDetails details) { this.predicate = predicate; this.handler = handler; this.details = details; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDetails.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDetails.java index f64724d73fd..91a1cff2aed 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDetails.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlerMappingDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ public class DispatcherHandlerMappingDetails { return this.requestMappingConditions; } - void setRequestMappingConditions( - RequestMappingConditionsDescription requestMappingConditions) { + void setRequestMappingConditions(RequestMappingConditionsDescription requestMappingConditions) { this.requestMappingConditions = requestMappingConditions; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java index b5f88e3ef47..31b9d14849a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,13 +53,11 @@ import org.springframework.web.util.pattern.PathPattern; * @author Andy Wilkinson * @since 2.0.0 */ -public class DispatcherHandlersMappingDescriptionProvider - implements MappingDescriptionProvider { +public class DispatcherHandlersMappingDescriptionProvider implements MappingDescriptionProvider { private static final List> descriptionProviders = Arrays .asList(new RequestMappingInfoHandlerMappingDescriptionProvider(), - new UrlHandlerMappingDescriptionProvider(), - new RouterFunctionMappingDescriptionProvider()); + new UrlHandlerMappingDescriptionProvider(), new RouterFunctionMappingDescriptionProvider()); @Override public String getMappingName() { @@ -67,27 +65,22 @@ public class DispatcherHandlersMappingDescriptionProvider } @Override - public Map> describeMappings( - ApplicationContext context) { + public Map> describeMappings(ApplicationContext context) { Map> mappings = new HashMap<>(); - context.getBeansOfType(DispatcherHandler.class).forEach( - (name, handler) -> mappings.put(name, describeMappings(handler))); + context.getBeansOfType(DispatcherHandler.class) + .forEach((name, handler) -> mappings.put(name, describeMappings(handler))); return mappings; } - private List describeMappings( - DispatcherHandler dispatcherHandler) { - return dispatcherHandler.getHandlerMappings().stream().flatMap(this::describe) - .collect(Collectors.toList()); + private List describeMappings(DispatcherHandler dispatcherHandler) { + return dispatcherHandler.getHandlerMappings().stream().flatMap(this::describe).collect(Collectors.toList()); } @SuppressWarnings("unchecked") - private Stream describe( - T handlerMapping) { + private Stream describe(T handlerMapping) { for (HandlerMappingDescriptionProvider descriptionProvider : descriptionProviders) { if (descriptionProvider.getMappingClass().isInstance(handlerMapping)) { - return ((HandlerMappingDescriptionProvider) descriptionProvider) - .describe(handlerMapping).stream(); + return ((HandlerMappingDescriptionProvider) descriptionProvider).describe(handlerMapping).stream(); } } @@ -103,8 +96,7 @@ public class DispatcherHandlersMappingDescriptionProvider } private static final class RequestMappingInfoHandlerMappingDescriptionProvider - implements - HandlerMappingDescriptionProvider { + implements HandlerMappingDescriptionProvider { @Override public Class getMappingClass() { @@ -112,23 +104,17 @@ public class DispatcherHandlersMappingDescriptionProvider } @Override - public List describe( - RequestMappingInfoHandlerMapping handlerMapping) { - Map handlerMethods = handlerMapping - .getHandlerMethods(); - return handlerMethods.entrySet().stream().map(this::describe) - .collect(Collectors.toList()); + public List describe(RequestMappingInfoHandlerMapping handlerMapping) { + Map handlerMethods = handlerMapping.getHandlerMethods(); + return handlerMethods.entrySet().stream().map(this::describe).collect(Collectors.toList()); } - private DispatcherHandlerMappingDescription describe( - Entry mapping) { + private DispatcherHandlerMappingDescription describe(Entry mapping) { DispatcherHandlerMappingDetails handlerMapping = new DispatcherHandlerMappingDetails(); - handlerMapping - .setHandlerMethod(new HandlerMethodDescription(mapping.getValue())); - handlerMapping.setRequestMappingConditions( - new RequestMappingConditionsDescription(mapping.getKey())); - return new DispatcherHandlerMappingDescription(mapping.getKey().toString(), - mapping.getValue().toString(), handlerMapping); + handlerMapping.setHandlerMethod(new HandlerMethodDescription(mapping.getValue())); + handlerMapping.setRequestMappingConditions(new RequestMappingConditionsDescription(mapping.getKey())); + return new DispatcherHandlerMappingDescription(mapping.getKey().toString(), mapping.getValue().toString(), + handlerMapping); } } @@ -142,17 +128,13 @@ public class DispatcherHandlersMappingDescriptionProvider } @Override - public List describe( - AbstractUrlHandlerMapping handlerMapping) { - return handlerMapping.getHandlerMap().entrySet().stream().map(this::describe) - .collect(Collectors.toList()); + public List describe(AbstractUrlHandlerMapping handlerMapping) { + return handlerMapping.getHandlerMap().entrySet().stream().map(this::describe).collect(Collectors.toList()); } - private DispatcherHandlerMappingDescription describe( - Entry mapping) { - return new DispatcherHandlerMappingDescription( - mapping.getKey().getPatternString(), mapping.getValue().toString(), - null); + private DispatcherHandlerMappingDescription describe(Entry mapping) { + return new DispatcherHandlerMappingDescription(mapping.getKey().getPatternString(), + mapping.getValue().toString(), null); } } @@ -166,8 +148,7 @@ public class DispatcherHandlersMappingDescriptionProvider } @Override - public List describe( - RouterFunctionMapping handlerMapping) { + public List describe(RouterFunctionMapping handlerMapping) { MappingDescriptionVisitor visitor = new MappingDescriptionVisitor(); RouterFunction routerFunction = handlerMapping.getRouterFunction(); if (routerFunction != null) { @@ -191,12 +172,11 @@ public class DispatcherHandlersMappingDescriptionProvider } @Override - public void route(RequestPredicate predicate, - HandlerFunction handlerFunction) { + public void route(RequestPredicate predicate, HandlerFunction handlerFunction) { DispatcherHandlerMappingDetails details = new DispatcherHandlerMappingDetails(); details.setHandlerFunction(new HandlerFunctionDescription(handlerFunction)); - this.descriptions.add(new DispatcherHandlerMappingDescription( - predicate.toString(), handlerFunction.toString(), details)); + this.descriptions.add( + new DispatcherHandlerMappingDescription(predicate.toString(), handlerFunction.toString(), details)); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java index b5eb17da7de..a133bb53108 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ public class RequestMappingConditionsDescription { this.methods = requestMapping.getMethodsCondition().getMethods(); this.params = requestMapping.getParamsCondition().getExpressions().stream() .map(NameValueExpressionDescription::new).collect(Collectors.toList()); - this.patterns = requestMapping.getPatternsCondition().getPatterns().stream() - .map(PathPattern::getPatternString).collect(Collectors.toSet()); + this.patterns = requestMapping.getPatternsCondition().getPatterns().stream().map(PathPattern::getPatternString) + .collect(Collectors.toSet()); this.produces = requestMapping.getProducesCondition().getExpressions().stream() .map(MediaTypeExpressionDescription::new).collect(Collectors.toList()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java index 0c3cfed1122..46184afbd3d 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,7 @@ final class DispatcherServletHandlerMappings { } public List getHandlerMappings() { - List handlerMappings = this.dispatcherServlet - .getHandlerMappings(); + List handlerMappings = this.dispatcherServlet.getHandlerMappings(); if (handlerMappings == null) { initializeDispatcherServletIfPossible(); handlerMappings = this.dispatcherServlet.getHandlerMappings(); @@ -71,15 +70,12 @@ final class DispatcherServletHandlerMappings { if (!(this.applicationContext instanceof ServletWebServerApplicationContext)) { return; } - WebServer webServer = ((ServletWebServerApplicationContext) this.applicationContext) - .getWebServer(); + WebServer webServer = ((ServletWebServerApplicationContext) this.applicationContext).getWebServer(); if (webServer instanceof UndertowServletWebServer) { - new UndertowServletInitializer((UndertowServletWebServer) webServer) - .initializeServlet(this.name); + new UndertowServletInitializer((UndertowServletWebServer) webServer).initializeServlet(this.name); } else if (webServer instanceof TomcatWebServer) { - new TomcatServletInitializer((TomcatWebServer) webServer) - .initializeServlet(this.name); + new TomcatServletInitializer((TomcatWebServer) webServer).initializeServlet(this.name); } } @@ -100,9 +96,8 @@ final class DispatcherServletHandlerMappings { } private Optional findContext() { - return Stream.of(this.webServer.getTomcat().getHost().findChildren()) - .filter(Context.class::isInstance).map(Context.class::cast) - .findFirst(); + return Stream.of(this.webServer.getTomcat().getHost().findChildren()).filter(Context.class::isInstance) + .map(Context.class::cast).findFirst(); } private void initializeServlet(Context context, String name) { @@ -130,8 +125,7 @@ final class DispatcherServletHandlerMappings { void initializeServlet(String name) { try { - this.webServer.getDeploymentManager().getDeployment().getServlets() - .getManagedServlet(name).forceInit(); + this.webServer.getDeploymentManager().getDeployment().getServlets().getManagedServlet(name).forceInit(); } catch (ServletException ex) { // Continue diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDescription.java index c5d32f9ce19..0f45ed48d59 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ public class DispatcherServletMappingDescription { private final DispatcherServletMappingDetails details; - DispatcherServletMappingDescription(String predicate, String handler, - DispatcherServletMappingDetails details) { + DispatcherServletMappingDescription(String predicate, String handler, DispatcherServletMappingDetails details) { this.handler = handler; this.predicate = predicate; this.details = details; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDetails.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDetails.java index aeab6d2ddf3..699ff05b460 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDetails.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletMappingDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class DispatcherServletMappingDetails { return this.requestMappingConditions; } - void setRequestMappingConditions( - RequestMappingConditionsDescription requestMappingConditions) { + void setRequestMappingConditions(RequestMappingConditionsDescription requestMappingConditions) { this.requestMappingConditions = requestMappingConditions; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java index 05963a50b99..0d40fa52016 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMappi * @author Stephane Nicoll * @since 2.0.0 */ -public class DispatcherServletsMappingDescriptionProvider - implements MappingDescriptionProvider { +public class DispatcherServletsMappingDescriptionProvider implements MappingDescriptionProvider { private static final List> descriptionProviders; @@ -60,11 +59,8 @@ public class DispatcherServletsMappingDescriptionProvider List> providers = new ArrayList<>(); providers.add(new RequestMappingInfoHandlerMappingDescriptionProvider()); providers.add(new UrlHandlerMappingDescriptionProvider()); - if (ClassUtils.isPresent( - "org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping", - null)) { - providers.add(new DelegatingHandlerMappingDescriptionProvider( - new ArrayList<>(providers))); + if (ClassUtils.isPresent("org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping", null)) { + providers.add(new DelegatingHandlerMappingDescriptionProvider(new ArrayList<>(providers))); } descriptionProviders = Collections.unmodifiableList(providers); } @@ -75,63 +71,50 @@ public class DispatcherServletsMappingDescriptionProvider } @Override - public Map> describeMappings( - ApplicationContext context) { + public Map> describeMappings(ApplicationContext context) { if (context instanceof WebApplicationContext) { return describeMappings((WebApplicationContext) context); } return Collections.emptyMap(); } - private Map> describeMappings( - WebApplicationContext context) { + private Map> describeMappings(WebApplicationContext context) { Map> mappings = new HashMap<>(); - determineDispatcherServlets(context).forEach((name, dispatcherServlet) -> mappings - .put(name, describeMappings(new DispatcherServletHandlerMappings(name, - dispatcherServlet, context)))); + determineDispatcherServlets(context).forEach((name, dispatcherServlet) -> mappings.put(name, + describeMappings(new DispatcherServletHandlerMappings(name, dispatcherServlet, context)))); return mappings; } - private Map determineDispatcherServlets( - WebApplicationContext context) { + private Map determineDispatcherServlets(WebApplicationContext context) { Map dispatcherServlets = new LinkedHashMap<>(); - context.getBeansOfType(ServletRegistrationBean.class).values() - .forEach((registration) -> { - Servlet servlet = registration.getServlet(); - if (servlet instanceof DispatcherServlet - && !dispatcherServlets.containsValue(servlet)) { - dispatcherServlets.put(registration.getServletName(), - (DispatcherServlet) servlet); - } - }); - context.getBeansOfType(DispatcherServlet.class) - .forEach((name, dispatcherServlet) -> { - if (!dispatcherServlets.containsValue(dispatcherServlet)) { - dispatcherServlets.put(name, dispatcherServlet); - } - }); + context.getBeansOfType(ServletRegistrationBean.class).values().forEach((registration) -> { + Servlet servlet = registration.getServlet(); + if (servlet instanceof DispatcherServlet && !dispatcherServlets.containsValue(servlet)) { + dispatcherServlets.put(registration.getServletName(), (DispatcherServlet) servlet); + } + }); + context.getBeansOfType(DispatcherServlet.class).forEach((name, dispatcherServlet) -> { + if (!dispatcherServlets.containsValue(dispatcherServlet)) { + dispatcherServlets.put(name, dispatcherServlet); + } + }); return dispatcherServlets; } - private List describeMappings( - DispatcherServletHandlerMappings mappings) { - return mappings.getHandlerMappings().stream().flatMap(this::describe) - .collect(Collectors.toList()); + private List describeMappings(DispatcherServletHandlerMappings mappings) { + return mappings.getHandlerMappings().stream().flatMap(this::describe).collect(Collectors.toList()); } - private Stream describe( - T handlerMapping) { + private Stream describe(T handlerMapping) { return describe(handlerMapping, descriptionProviders).stream(); } @SuppressWarnings("unchecked") - private static List describe( - T handlerMapping, + private static List describe(T handlerMapping, List> descriptionProviders) { for (HandlerMappingDescriptionProvider descriptionProvider : descriptionProviders) { if (descriptionProvider.getMappingClass().isInstance(handlerMapping)) { - return ((HandlerMappingDescriptionProvider) descriptionProvider) - .describe(handlerMapping); + return ((HandlerMappingDescriptionProvider) descriptionProvider).describe(handlerMapping); } } return Collections.emptyList(); @@ -146,8 +129,7 @@ public class DispatcherServletsMappingDescriptionProvider } private static final class RequestMappingInfoHandlerMappingDescriptionProvider - implements - HandlerMappingDescriptionProvider { + implements HandlerMappingDescriptionProvider { @Override public Class getMappingClass() { @@ -155,23 +137,17 @@ public class DispatcherServletsMappingDescriptionProvider } @Override - public List describe( - RequestMappingInfoHandlerMapping handlerMapping) { - Map handlerMethods = handlerMapping - .getHandlerMethods(); - return handlerMethods.entrySet().stream().map(this::describe) - .collect(Collectors.toList()); + public List describe(RequestMappingInfoHandlerMapping handlerMapping) { + Map handlerMethods = handlerMapping.getHandlerMethods(); + return handlerMethods.entrySet().stream().map(this::describe).collect(Collectors.toList()); } - private DispatcherServletMappingDescription describe( - Entry mapping) { + private DispatcherServletMappingDescription describe(Entry mapping) { DispatcherServletMappingDetails mappingDetails = new DispatcherServletMappingDetails(); - mappingDetails - .setHandlerMethod(new HandlerMethodDescription(mapping.getValue())); - mappingDetails.setRequestMappingConditions( - new RequestMappingConditionsDescription(mapping.getKey())); - return new DispatcherServletMappingDescription(mapping.getKey().toString(), - mapping.getValue().toString(), mappingDetails); + mappingDetails.setHandlerMethod(new HandlerMethodDescription(mapping.getValue())); + mappingDetails.setRequestMappingConditions(new RequestMappingConditionsDescription(mapping.getKey())); + return new DispatcherServletMappingDescription(mapping.getKey().toString(), mapping.getValue().toString(), + mappingDetails); } } @@ -185,16 +161,12 @@ public class DispatcherServletsMappingDescriptionProvider } @Override - public List describe( - AbstractUrlHandlerMapping handlerMapping) { - return handlerMapping.getHandlerMap().entrySet().stream().map(this::describe) - .collect(Collectors.toList()); + public List describe(AbstractUrlHandlerMapping handlerMapping) { + return handlerMapping.getHandlerMap().entrySet().stream().map(this::describe).collect(Collectors.toList()); } - private DispatcherServletMappingDescription describe( - Entry mapping) { - return new DispatcherServletMappingDescription(mapping.getKey(), - mapping.getValue().toString(), null); + private DispatcherServletMappingDescription describe(Entry mapping) { + return new DispatcherServletMappingDescription(mapping.getKey(), mapping.getValue().toString(), null); } } @@ -215,12 +187,11 @@ public class DispatcherServletsMappingDescriptionProvider } @Override - public List describe( - DelegatingHandlerMapping handlerMapping) { + public List describe(DelegatingHandlerMapping handlerMapping) { List descriptions = new ArrayList<>(); for (HandlerMapping delegate : handlerMapping.getDelegates()) { - descriptions.addAll(DispatcherServletsMappingDescriptionProvider - .describe(delegate, this.descriptionProviders)); + descriptions.addAll( + DispatcherServletsMappingDescriptionProvider.describe(delegate, this.descriptionProviders)); } return descriptions; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FilterRegistrationMappingDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FilterRegistrationMappingDescription.java index b0cc39f15bb..8943b3d1bf5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FilterRegistrationMappingDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FilterRegistrationMappingDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import javax.servlet.FilterRegistration; * @author Andy Wilkinson * @since 2.0.0 */ -public class FilterRegistrationMappingDescription - extends RegistrationMappingDescription { +public class FilterRegistrationMappingDescription extends RegistrationMappingDescription { /** * Creates a new {@code FilterRegistrationMappingDescription} derived from the given diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java index 74bde4f2ab6..677558448a7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,15 +37,12 @@ import org.springframework.web.context.WebApplicationContext; public class FiltersMappingDescriptionProvider implements MappingDescriptionProvider { @Override - public List describeMappings( - ApplicationContext context) { + public List describeMappings(ApplicationContext context) { if (!(context instanceof WebApplicationContext)) { return Collections.emptyList(); } - return ((WebApplicationContext) context).getServletContext() - .getFilterRegistrations().values().stream() - .map(FilterRegistrationMappingDescription::new) - .collect(Collectors.toList()); + return ((WebApplicationContext) context).getServletContext().getFilterRegistrations().values().stream() + .map(FilterRegistrationMappingDescription::new).collect(Collectors.toList()); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletRegistrationMappingDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletRegistrationMappingDescription.java index 8cc20c04f82..80858da64d3 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletRegistrationMappingDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletRegistrationMappingDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,16 +26,14 @@ import javax.servlet.ServletRegistration; * @author Andy Wilkinson * @since 2.0.0 */ -public class ServletRegistrationMappingDescription - extends RegistrationMappingDescription { +public class ServletRegistrationMappingDescription extends RegistrationMappingDescription { /** * Creates a new {@code ServletRegistrationMappingDescription} derived from the given * {@code servletRegistration}. * @param servletRegistration the servlet registration */ - public ServletRegistrationMappingDescription( - ServletRegistration servletRegistration) { + public ServletRegistrationMappingDescription(ServletRegistration servletRegistration) { super(servletRegistration); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java index fc9ab2b4f42..b2d7d96975c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,15 +37,12 @@ import org.springframework.web.context.WebApplicationContext; public class ServletsMappingDescriptionProvider implements MappingDescriptionProvider { @Override - public List describeMappings( - ApplicationContext context) { + public List describeMappings(ApplicationContext context) { if (!(context instanceof WebApplicationContext)) { return Collections.emptyList(); } - return ((WebApplicationContext) context).getServletContext() - .getServletRegistrations().values().stream() - .map(ServletRegistrationMappingDescription::new) - .collect(Collectors.toList()); + return ((WebApplicationContext) context).getServletContext().getServletRegistrations().values().stream() + .map(ServletRegistrationMappingDescription::new).collect(Collectors.toList()); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java index 811c2506d4c..224724f8d7f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java @@ -51,8 +51,7 @@ public class HttpTraceWebFilter implements WebFilter, Ordered { private final Set includes; - public HttpTraceWebFilter(HttpTraceRepository repository, HttpExchangeTracer tracer, - Set includes) { + public HttpTraceWebFilter(HttpTraceRepository repository, HttpExchangeTracer tracer, Set includes) { this.repository = repository; this.tracer = tracer; this.includes = includes; @@ -70,14 +69,10 @@ public class HttpTraceWebFilter implements WebFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { Mono principal = (this.includes.contains(Include.PRINCIPAL) - ? exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE) - : Mono.just(NONE)); - Mono session = (this.includes.contains(Include.SESSION_ID) - ? exchange.getSession() : Mono.just(NONE)); - return Mono.zip(principal, session) - .flatMap((tuple) -> filter(exchange, chain, - asType(tuple.getT1(), Principal.class), - asType(tuple.getT2(), WebSession.class))); + ? exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE) : Mono.just(NONE)); + Mono session = (this.includes.contains(Include.SESSION_ID) ? exchange.getSession() : Mono.just(NONE)); + return Mono.zip(principal, session).flatMap((tuple) -> filter(exchange, chain, + asType(tuple.getT1(), Principal.class), asType(tuple.getT2(), WebSession.class))); } private T asType(Object object, Class type) { @@ -87,16 +82,13 @@ public class HttpTraceWebFilter implements WebFilter, Ordered { return null; } - private Mono filter(ServerWebExchange exchange, WebFilterChain chain, - Principal principal, WebSession session) { - ServerWebExchangeTraceableRequest request = new ServerWebExchangeTraceableRequest( - exchange); + private Mono filter(ServerWebExchange exchange, WebFilterChain chain, Principal principal, + WebSession session) { + ServerWebExchangeTraceableRequest request = new ServerWebExchangeTraceableRequest(exchange); HttpTrace trace = this.tracer.receivedRequest(request); exchange.getResponse().beforeCommit(() -> { - TraceableServerHttpResponse response = new TraceableServerHttpResponse( - exchange.getResponse()); - this.tracer.sendingResponse(trace, response, () -> principal, - () -> getStartedSessionId(session)); + TraceableServerHttpResponse response = new TraceableServerHttpResponse(exchange.getResponse()); + this.tracer.sendingResponse(trace, response, () -> principal, () -> getStartedSessionId(session)); this.repository.add(trace); return Mono.empty(); }); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/TraceableServerHttpResponse.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/TraceableServerHttpResponse.java index 5c3e95ce959..8a3b2c81b0a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/TraceableServerHttpResponse.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/TraceableServerHttpResponse.java @@ -36,8 +36,7 @@ class TraceableServerHttpResponse implements TraceableResponse { private final Map> headers; TraceableServerHttpResponse(ServerHttpResponse response) { - this.status = (response.getStatusCode() != null) - ? response.getStatusCode().value() : HttpStatus.OK.value(); + this.status = (response.getStatusCode() != null) ? response.getStatusCode().value() : HttpStatus.OK.value(); this.headers = new LinkedHashMap<>(response.getHeaders()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/HttpTraceFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/HttpTraceFilter.java index 838b5790c3e..7d85cc03990 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/HttpTraceFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/HttpTraceFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,15 +75,13 @@ public class HttpTraceFilter extends OncePerRequestFilter implements Ordered { } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!isRequestValid(request)) { filterChain.doFilter(request, response); return; } - TraceableHttpServletRequest traceableRequest = new TraceableHttpServletRequest( - request); + TraceableHttpServletRequest traceableRequest = new TraceableHttpServletRequest(request); HttpTrace trace = this.tracer.receivedRequest(traceableRequest); int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); try { @@ -92,11 +90,9 @@ public class HttpTraceFilter extends OncePerRequestFilter implements Ordered { } finally { TraceableHttpServletResponse traceableResponse = new TraceableHttpServletResponse( - (status != response.getStatus()) - ? new CustomStatusResponseWrapper(response, status) - : response); - this.tracer.sendingResponse(trace, traceableResponse, - request::getUserPrincipal, () -> getSessionId(request)); + (status != response.getStatus()) ? new CustomStatusResponseWrapper(response, status) : response); + this.tracer.sendingResponse(trace, traceableResponse, request::getUserPrincipal, + () -> getSessionId(request)); this.repository.add(trace); } } @@ -116,8 +112,7 @@ public class HttpTraceFilter extends OncePerRequestFilter implements Ordered { return (session != null) ? session.getId() : null; } - private static final class CustomStatusResponseWrapper - extends HttpServletResponseWrapper { + private static final class CustomStatusResponseWrapper extends HttpServletResponseWrapper { private final int status; diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java index 49959d74be3..eaaee0441ab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java @@ -60,8 +60,7 @@ public class RabbitHealthIndicatorTests { @Test public void createWhenRabbitTemplateIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RabbitHealthIndicator(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RabbitHealthIndicator(null)) .withMessageContaining("RabbitTemplate must not be null"); } @@ -69,8 +68,7 @@ public class RabbitHealthIndicatorTests { public void healthWhenConnectionSucceedsShouldReturnUpWithVersion() { Connection connection = mock(Connection.class); given(this.channel.getConnection()).willReturn(connection); - given(connection.getServerProperties()) - .willReturn(Collections.singletonMap("version", "123")); + given(connection.getServerProperties()).willReturn(Collections.singletonMap("version", "123")); Health health = new RabbitHealthIndicator(this.rabbitTemplate).health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("version", "123"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index 772807e68d6..c906e78bcc7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -36,8 +36,7 @@ public class AuditEventTests { @Test public void nowEvent() { - AuditEvent event = new AuditEvent("phil", "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + AuditEvent event = new AuditEvent("phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b")); assertThat(event.getData().get("a")).isEqualTo("b"); assertThat(event.getType()).isEqualTo("UNKNOWN"); assertThat(event.getPrincipal()).isEqualTo("phil"); @@ -53,24 +52,21 @@ public class AuditEventTests { @Test public void nullPrincipalIsMappedToEmptyString() { - AuditEvent auditEvent = new AuditEvent(null, "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + AuditEvent auditEvent = new AuditEvent(null, "UNKNOWN", Collections.singletonMap("a", (Object) "b")); assertThat(auditEvent.getPrincipal()).isEmpty(); } @Test public void nullTimestamp() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", - Collections.singletonMap("a", (Object) "b"))) + .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b"))) .withMessageContaining("Timestamp must not be null"); } @Test public void nullType() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AuditEvent("phil", null, - Collections.singletonMap("a", (Object) "b"))) + .isThrownBy(() -> new AuditEvent("phil", null, Collections.singletonMap("a", (Object) "b"))) .withMessageContaining("Type must not be null"); } @@ -78,12 +74,10 @@ public class AuditEventTests { public void jsonFormat() throws Exception { AuditEvent event = new AuditEvent("johannes", "UNKNOWN", Collections.singletonMap("type", (Object) "BadCredentials")); - String json = Jackson2ObjectMapperBuilder.json().build() - .writeValueAsString(event); + String json = Jackson2ObjectMapperBuilder.json().build().writeValueAsString(event); JSONObject jsonObject = new JSONObject(json); assertThat(jsonObject.getString("type")).isEqualTo("UNKNOWN"); - assertThat(jsonObject.getJSONObject("data").getString("type")) - .isEqualTo("BadCredentials"); + assertThat(jsonObject.getJSONObject("data").getString("type")).isEqualTo("BadCredentials"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java index af37e13077d..742398aeb8c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java @@ -37,13 +37,11 @@ public class AuditEventsEndpointTests { private final AuditEventsEndpoint endpoint = new AuditEventsEndpoint(this.repository); - private final AuditEvent event = new AuditEvent("principal", "type", - Collections.singletonMap("a", "alpha")); + private final AuditEvent event = new AuditEvent("principal", "type", Collections.singletonMap("a", "alpha")); @Test public void eventsWithType() { - given(this.repository.find(null, null, "type")) - .willReturn(Collections.singletonList(this.event)); + given(this.repository.find(null, null, "type")).willReturn(Collections.singletonList(this.event)); List result = this.endpoint.events(null, null, "type").getEvents(); assertThat(result).isEqualTo(Collections.singletonList(this.event)); } @@ -51,16 +49,14 @@ public class AuditEventsEndpointTests { @Test public void eventsCreatedAfter() { OffsetDateTime now = OffsetDateTime.now(); - given(this.repository.find(null, now.toInstant(), null)) - .willReturn(Collections.singletonList(this.event)); + given(this.repository.find(null, now.toInstant(), null)).willReturn(Collections.singletonList(this.event)); List result = this.endpoint.events(null, now, null).getEvents(); assertThat(result).isEqualTo(Collections.singletonList(this.event)); } @Test public void eventsWithPrincipal() { - given(this.repository.find("Joan", null, null)) - .willReturn(Collections.singletonList(this.event)); + given(this.repository.find("Joan", null, null)).willReturn(Collections.singletonList(this.event)); List result = this.endpoint.events("Joan", null, null).getEvents(); assertThat(result).isEqualTo(Collections.singletonList(this.event)); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java index 8c6be74fe37..845d9a35238 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java @@ -42,11 +42,9 @@ public class AuditEventsEndpointWebIntegrationTests { @Test public void allEvents() { - client.get().uri((builder) -> builder.path("/actuator/auditevents").build()) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin") - .appendElement("user")); + client.get().uri((builder) -> builder.path("/actuator/auditevents").build()).exchange().expectStatus().isOk() + .expectBody().jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin").appendElement("user")); } @Test @@ -54,29 +52,21 @@ public class AuditEventsEndpointWebIntegrationTests { client.get() .uri((builder) -> builder.path("/actuator/auditevents") .queryParam("after", "2016-11-01T13:00:00%2B00:00").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events") - .isEmpty(); + .exchange().expectStatus().isOk().expectBody().jsonPath("events").isEmpty(); } @Test public void eventsWithPrincipal() { - client.get() - .uri((builder) -> builder.path("/actuator/auditevents") - .queryParam("principal", "user").build()) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("events.[*].principal") + client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("principal", "user").build()) + .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") .isEqualTo(new JSONArray().appendElement("user")); } @Test public void eventsWithType() { - client.get() - .uri((builder) -> builder.path("/actuator/auditevents") - .queryParam("type", "logout").build()) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("admin")) - .jsonPath("events.[*].type") + client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("type", "logout").build()) + .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("admin")).jsonPath("events.[*].type") .isEqualTo(new JSONArray().appendElement("logout")); } @@ -93,14 +83,12 @@ public class AuditEventsEndpointWebIntegrationTests { } @Bean - public AuditEventsEndpoint auditEventsEndpoint( - AuditEventRepository auditEventRepository) { + public AuditEventsEndpoint auditEventsEndpoint(AuditEventRepository auditEventRepository) { return new AuditEventsEndpoint(auditEventRepository); } private AuditEvent createEvent(String instant, String principal, String type) { - return new AuditEvent(Instant.parse(instant), principal, type, - Collections.emptyMap()); + return new AuditEvent(Instant.parse(instant), principal, type, Collections.emptyMap()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java index adab01c3c03..8632b8faa1d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java @@ -98,12 +98,9 @@ public class InMemoryAuditEventRepositoryTests { Map data = new HashMap<>(); InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); repository.add(new AuditEvent(instant, "dave", "a", data)); - repository - .add(new AuditEvent(instant.plus(1, ChronoUnit.DAYS), "phil", "b", data)); - repository - .add(new AuditEvent(instant.plus(2, ChronoUnit.DAYS), "dave", "c", data)); - repository - .add(new AuditEvent(instant.plus(3, ChronoUnit.DAYS), "phil", "d", data)); + repository.add(new AuditEvent(instant.plus(1, ChronoUnit.DAYS), "phil", "b", data)); + repository.add(new AuditEvent(instant.plus(2, ChronoUnit.DAYS), "dave", "c", data)); + repository.add(new AuditEvent(instant.plus(3, ChronoUnit.DAYS), "phil", "d", data)); Instant after = instant.plus(1, ChronoUnit.DAYS); List events = repository.find(null, after, null); assertThat(events.size()).isEqualTo(2); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java index c976bddeae2..e58706b0ff2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java @@ -53,8 +53,7 @@ public class BeansEndpointTests { ContextBeans descriptor = result.getContexts().get(context.getId()); assertThat(descriptor.getParentId()).isNull(); Map beans = descriptor.getBeans(); - assertThat(beans.size()) - .isLessThanOrEqualTo(context.getBeanDefinitionCount()); + assertThat(beans.size()).isLessThanOrEqualTo(context.getBeanDefinitionCount()); assertThat(beans).containsKey("endpoint"); }); } @@ -67,8 +66,7 @@ public class BeansEndpointTests { ConfigurableListableBeanFactory factory = (ConfigurableListableBeanFactory) context .getAutowireCapableBeanFactory(); List infrastructureBeans = Stream.of(context.getBeanDefinitionNames()) - .filter((name) -> BeanDefinition.ROLE_INFRASTRUCTURE == factory - .getBeanDefinition(name).getRole()) + .filter((name) -> BeanDefinition.ROLE_INFRASTRUCTURE == factory.getBeanDefinition(name).getRole()) .collect(Collectors.toList()); ApplicationBeans result = context.getBean(BeansEndpoint.class).beans(); ContextBeans contextDescriptor = result.getContexts().get(context.getId()); @@ -82,8 +80,7 @@ public class BeansEndpointTests { @Test public void lazyBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class, - LazyBeanConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class, LazyBeanConfiguration.class); contextRunner.run((context) -> { ApplicationBeans result = context.getBean(BeansEndpoint.class).beans(); ContextBeans contextDescriptor = result.getContexts().get(context.getId()); @@ -97,15 +94,11 @@ public class BeansEndpointTests { ApplicationContextRunner parentRunner = new ApplicationContextRunner() .withUserConfiguration(BeanConfiguration.class); parentRunner.run((parent) -> { - new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class).withParent(parent) + new ApplicationContextRunner().withUserConfiguration(EndpointConfiguration.class).withParent(parent) .run((child) -> { - ApplicationBeans result = child.getBean(BeansEndpoint.class) - .beans(); - assertThat(result.getContexts().get(parent.getId()).getBeans()) - .containsKey("bean"); - assertThat(result.getContexts().get(child.getId()).getBeans()) - .containsKey("endpoint"); + ApplicationBeans result = child.getBean(BeansEndpoint.class).beans(); + assertThat(result.getContexts().get(parent.getId()).getBeans()).containsKey("bean"); + assertThat(result.getContexts().get(child.getId()).getBeans()).containsKey("endpoint"); }); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java index 3af1c03f0f6..beda28b7e4a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java @@ -47,17 +47,14 @@ public class CachesEndpointTests { @Test public void allCachesWithSingleCacheManager() { - CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", - new ConcurrentMapCacheManager("a", "b"))); - Map allDescriptors = endpoint.caches() - .getCacheManagers(); + CachesEndpoint endpoint = new CachesEndpoint( + Collections.singletonMap("test", new ConcurrentMapCacheManager("a", "b"))); + Map allDescriptors = endpoint.caches().getCacheManagers(); assertThat(allDescriptors).containsOnlyKeys("test"); CacheManagerDescriptor descriptors = allDescriptors.get("test"); assertThat(descriptors.getCaches()).containsOnlyKeys("a", "b"); - assertThat(descriptors.getCaches().get("a").getTarget()) - .isEqualTo(ConcurrentHashMap.class.getName()); - assertThat(descriptors.getCaches().get("b").getTarget()) - .isEqualTo(ConcurrentHashMap.class.getName()); + assertThat(descriptors.getCaches().get("a").getTarget()).isEqualTo(ConcurrentHashMap.class.getName()); + assertThat(descriptors.getCaches().get("b").getTarget()).isEqualTo(ConcurrentHashMap.class.getName()); } @Test @@ -66,8 +63,7 @@ public class CachesEndpointTests { cacheManagers.put("test", new ConcurrentMapCacheManager("a", "b")); cacheManagers.put("another", new ConcurrentMapCacheManager("a", "c")); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); - Map allDescriptors = endpoint.caches() - .getCacheManagers(); + Map allDescriptors = endpoint.caches().getCacheManagers(); assertThat(allDescriptors).containsOnlyKeys("test", "another"); assertThat(allDescriptors.get("test").getCaches()).containsOnlyKeys("a", "b"); assertThat(allDescriptors.get("another").getCaches()).containsOnlyKeys("a", "c"); @@ -75,8 +71,8 @@ public class CachesEndpointTests { @Test public void namedCacheWithSingleCacheManager() { - CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", - new ConcurrentMapCacheManager("b", "a"))); + CachesEndpoint endpoint = new CachesEndpoint( + Collections.singletonMap("test", new ConcurrentMapCacheManager("b", "a"))); CacheEntry entry = endpoint.cache("a", null); assertThat(entry).isNotNull(); assertThat(entry.getCacheManager()).isEqualTo("test"); @@ -90,16 +86,14 @@ public class CachesEndpointTests { cacheManagers.put("test", new ConcurrentMapCacheManager("b", "dupe-cache")); cacheManagers.put("another", new ConcurrentMapCacheManager("c", "dupe-cache")); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); - assertThatExceptionOfType(NonUniqueCacheException.class) - .isThrownBy(() -> endpoint.cache("dupe-cache", null)) - .withMessageContaining("dupe-cache").withMessageContaining("test") - .withMessageContaining("another"); + assertThatExceptionOfType(NonUniqueCacheException.class).isThrownBy(() -> endpoint.cache("dupe-cache", null)) + .withMessageContaining("dupe-cache").withMessageContaining("test").withMessageContaining("another"); } @Test public void namedCacheWithUnknownCache() { - CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", - new ConcurrentMapCacheManager("b", "a"))); + CachesEndpoint endpoint = new CachesEndpoint( + Collections.singletonMap("test", new ConcurrentMapCacheManager("b", "a"))); CacheEntry entry = endpoint.cache("unknown", null); assertThat(entry).isNull(); } @@ -130,8 +124,7 @@ public class CachesEndpointTests { public void clearAllCaches() { Cache a = mockCache("a"); Cache b = mockCache("b"); - CachesEndpoint endpoint = new CachesEndpoint( - Collections.singletonMap("test", cacheManager(a, b))); + CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b))); endpoint.clearCaches(); verify(a).clear(); verify(b).clear(); @@ -141,8 +134,7 @@ public class CachesEndpointTests { public void clearCache() { Cache a = mockCache("a"); Cache b = mockCache("b"); - CachesEndpoint endpoint = new CachesEndpoint( - Collections.singletonMap("test", cacheManager(a, b))); + CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b))); assertThat(endpoint.clearCache("a", null)).isTrue(); verify(a).clear(); verify(b, never()).clear(); @@ -155,9 +147,8 @@ public class CachesEndpointTests { cacheManagers.put("another", cacheManager(mockCache("dupe-cache"))); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); assertThatExceptionOfType(NonUniqueCacheException.class) - .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)) - .withMessageContaining("dupe-cache").withMessageContaining("test") - .withMessageContaining("another"); + .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)).withMessageContaining("dupe-cache") + .withMessageContaining("test").withMessageContaining("another"); } @Test @@ -178,8 +169,7 @@ public class CachesEndpointTests { @Test public void clearCacheWithUnknownCache() { Cache a = mockCache("a"); - CachesEndpoint endpoint = new CachesEndpoint( - Collections.singletonMap("test", cacheManager(a))); + CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a))); assertThat(endpoint.clearCache("unknown", null)).isFalse(); verify(a, never()).clear(); } @@ -187,8 +177,7 @@ public class CachesEndpointTests { @Test public void clearCacheWithUnknownCacheManager() { Cache a = mockCache("a"); - CachesEndpoint endpoint = new CachesEndpoint( - Collections.singletonMap("test", cacheManager(a))); + CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a))); assertThat(endpoint.clearCache("a", "unknown")).isFalse(); verify(a, never()).clear(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java index 42596626cb8..c3671ed8fa7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java @@ -49,28 +49,22 @@ public class CachesEndpointWebIntegrationTests { @Test public void allCaches() { client.get().uri("/actuator/caches").exchange().expectStatus().isOk().expectBody() - .jsonPath("cacheManagers.one.caches.a.target") - .isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.one.caches.b.target") - .isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.two.caches.a.target") - .isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.two.caches.c.target") - .isEqualTo(ConcurrentHashMap.class.getName()); + .jsonPath("cacheManagers.one.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.one.caches.b.target").isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.two.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.two.caches.c.target").isEqualTo(ConcurrentHashMap.class.getName()); } @Test public void namedCache() { - client.get().uri("/actuator/caches/b").exchange().expectStatus().isOk() - .expectBody().jsonPath("name").isEqualTo("b").jsonPath("cacheManager") - .isEqualTo("one").jsonPath("target") + client.get().uri("/actuator/caches/b").exchange().expectStatus().isOk().expectBody().jsonPath("name") + .isEqualTo("b").jsonPath("cacheManager").isEqualTo("one").jsonPath("target") .isEqualTo(ConcurrentHashMap.class.getName()); } @Test public void namedCacheWithUnknownName() { - client.get().uri("/actuator/caches/does-not-exist").exchange().expectStatus() - .isNotFound(); + client.get().uri("/actuator/caches/does-not-exist").exchange().expectStatus().isNotFound(); } @Test @@ -88,8 +82,7 @@ public class CachesEndpointWebIntegrationTests { @Test public void cleanNamedCacheWithUnknownName() { - client.delete().uri("/actuator/caches/does-not-exist").exchange().expectStatus() - .isNotFound(); + client.delete().uri("/actuator/caches/does-not-exist").exchange().expectStatus().isNotFound(); } @Test @@ -116,8 +109,7 @@ public class CachesEndpointWebIntegrationTests { } @Bean - public CachesEndpointWebExtension cachesEndpointWebExtension( - CachesEndpoint endpoint) { + public CachesEndpointWebExtension cachesEndpointWebExtension(CachesEndpoint endpoint) { return new CachesEndpointWebExtension(endpoint); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java index ea6fd1e5a01..f3077a52932 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class CassandraHealthIndicatorTests { @Test public void createWhenCassandraOperationsIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new CassandraHealthIndicator(null)); + assertThatIllegalArgumentException().isThrownBy(() -> new CassandraHealthIndicator(null)); } @Test @@ -50,8 +49,7 @@ public class CassandraHealthIndicatorTests { CassandraOperations cassandraOperations = mock(CassandraOperations.class); CqlOperations cqlOperations = mock(CqlOperations.class); ResultSet resultSet = mock(ResultSet.class); - CassandraHealthIndicator healthIndicator = new CassandraHealthIndicator( - cassandraOperations); + CassandraHealthIndicator healthIndicator = new CassandraHealthIndicator(cassandraOperations); given(cassandraOperations.getCqlOperations()).willReturn(cqlOperations); given(cqlOperations.queryForResultSet(any(Select.class))).willReturn(resultSet); given(resultSet.isExhausted()).willReturn(true); @@ -65,8 +63,7 @@ public class CassandraHealthIndicatorTests { CqlOperations cqlOperations = mock(CqlOperations.class); ResultSet resultSet = mock(ResultSet.class); Row row = mock(Row.class); - CassandraHealthIndicator healthIndicator = new CassandraHealthIndicator( - cassandraOperations); + CassandraHealthIndicator healthIndicator = new CassandraHealthIndicator(cassandraOperations); given(cassandraOperations.getCqlOperations()).willReturn(cqlOperations); given(cqlOperations.queryForResultSet(any(Select.class))).willReturn(resultSet); given(resultSet.isExhausted()).willReturn(false); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java index 943a2435c78..7daba57d9ba 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java @@ -42,12 +42,9 @@ public class CassandraReactiveHealthIndicatorTests { @Test public void testCassandraIsUp() { ReactiveCqlOperations reactiveCqlOperations = mock(ReactiveCqlOperations.class); - given(reactiveCqlOperations.queryForObject(any(Select.class), eq(String.class))) - .willReturn(Mono.just("6.0.0")); - ReactiveCassandraOperations reactiveCassandraOperations = mock( - ReactiveCassandraOperations.class); - given(reactiveCassandraOperations.getReactiveCqlOperations()) - .willReturn(reactiveCqlOperations); + given(reactiveCqlOperations.queryForObject(any(Select.class), eq(String.class))).willReturn(Mono.just("6.0.0")); + ReactiveCassandraOperations reactiveCassandraOperations = mock(ReactiveCassandraOperations.class); + given(reactiveCassandraOperations.getReactiveCqlOperations()).willReturn(reactiveCqlOperations); CassandraReactiveHealthIndicator cassandraReactiveHealthIndicator = new CassandraReactiveHealthIndicator( reactiveCassandraOperations); @@ -61,8 +58,7 @@ public class CassandraReactiveHealthIndicatorTests { @Test public void testCassandraIsDown() { - ReactiveCassandraOperations reactiveCassandraOperations = mock( - ReactiveCassandraOperations.class); + ReactiveCassandraOperations reactiveCassandraOperations = mock(ReactiveCassandraOperations.class); given(reactiveCassandraOperations.getReactiveCqlOperations()) .willThrow(new CassandraInternalException("Connection failed")); @@ -72,8 +68,8 @@ public class CassandraReactiveHealthIndicatorTests { StepVerifier.create(health).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.DOWN); assertThat(h.getDetails()).containsOnlyKeys("error"); - assertThat(h.getDetails().get("error")).isEqualTo( - CassandraInternalException.class.getName() + ": Connection failed"); + assertThat(h.getDetails().get("error")) + .isEqualTo(CassandraInternalException.class.getName() + ": Connection failed"); }).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java index 12b554f9694..5c216d04305 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java @@ -52,8 +52,7 @@ public class ShutdownEndpointTests { EndpointConfig config = context.getBean(EndpointConfig.class); ClassLoader previousTccl = Thread.currentThread().getContextClassLoader(); Map result; - Thread.currentThread().setContextClassLoader( - new URLClassLoader(new URL[0], getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[0], getClass().getClassLoader())); try { result = context.getBean(ShutdownEndpoint.class).shutdown(); } @@ -63,32 +62,27 @@ public class ShutdownEndpointTests { assertThat(result.get("message")).startsWith("Shutting down"); assertThat(((ConfigurableApplicationContext) context).isActive()).isTrue(); assertThat(config.latch.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(config.threadContextClassLoader) - .isEqualTo(getClass().getClassLoader()); + assertThat(config.threadContextClassLoader).isEqualTo(getClass().getClassLoader()); }); } @Test public void shutdownChild() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - EmptyConfig.class).child(EndpointConfig.class) - .web(WebApplicationType.NONE).run(); + ConfigurableApplicationContext context = new SpringApplicationBuilder(EmptyConfig.class) + .child(EndpointConfig.class).web(WebApplicationType.NONE).run(); CountDownLatch latch = context.getBean(EndpointConfig.class).latch; - assertThat(context.getBean(ShutdownEndpoint.class).shutdown().get("message")) - .startsWith("Shutting down"); + assertThat(context.getBean(ShutdownEndpoint.class).shutdown().get("message")).startsWith("Shutting down"); assertThat(context.isActive()).isTrue(); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test public void shutdownParent() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - EndpointConfig.class).child(EmptyConfig.class) - .web(WebApplicationType.NONE).run(); + ConfigurableApplicationContext context = new SpringApplicationBuilder(EndpointConfig.class) + .child(EmptyConfig.class).web(WebApplicationType.NONE).run(); CountDownLatch parentLatch = context.getBean(EndpointConfig.class).latch; CountDownLatch childLatch = context.getBean(EmptyConfig.class).latch; - assertThat(context.getBean(ShutdownEndpoint.class).shutdown().get("message")) - .startsWith("Shutting down"); + assertThat(context.getBean(ShutdownEndpoint.class).shutdown().get("message")).startsWith("Shutting down"); assertThat(context.isActive()).isTrue(); assertThat(parentLatch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(childLatch.await(10, TimeUnit.SECONDS)).isTrue(); @@ -110,8 +104,7 @@ public class ShutdownEndpointTests { @Bean public ApplicationListener listener() { return (event) -> { - EndpointConfig.this.threadContextClassLoader = Thread.currentThread() - .getContextClassLoader(); + EndpointConfig.this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); EndpointConfig.this.latch.countDown(); }; } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java index 0e3fc957c74..c9582013999 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java @@ -39,20 +39,15 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test public void testNaming() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class) + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) .withPropertyValues("other.name:foo", "first.name:bar"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - assertThat(applicationProperties.getContexts()) - .containsOnlyKeys(context.getId()); - ContextConfigurationProperties contextProperties = applicationProperties - .getContexts().get(context.getId()); - ConfigurationPropertiesBeanDescriptor other = contextProperties.getBeans() - .get("other"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); + ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); + ConfigurationPropertiesBeanDescriptor other = contextProperties.getBeans().get("other"); assertThat(other).isNotNull(); assertThat(other.getPrefix()).isEqualTo("other"); assertThat(other.getProperties()).isNotNull(); @@ -63,19 +58,14 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test public void prefixFromBeanMethodConfigurationPropertiesCanOverridePrefixOnClass() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(OverriddenPrefix.class) - .withPropertyValues("other.name:foo"); + .withUserConfiguration(OverriddenPrefix.class).withPropertyValues("other.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - assertThat(applicationProperties.getContexts()) - .containsOnlyKeys(context.getId()); - ContextConfigurationProperties contextProperties = applicationProperties - .getContexts().get(context.getId()); - ConfigurationPropertiesBeanDescriptor bar = contextProperties.getBeans() - .get("bar"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); + ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); + ConfigurationPropertiesBeanDescriptor bar = contextProperties.getBeans().get("bar"); assertThat(bar).isNotNull(); assertThat(bar.getPrefix()).isEqualTo("other"); assertThat(bar.getProperties()).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java index d5e324c3660..7ac7eb75604 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java @@ -38,50 +38,35 @@ public class ConfigurationPropertiesReportEndpointParentTests { @Test public void configurationPropertiesClass() { - new ApplicationContextRunner().withUserConfiguration(Parent.class) - .run((parent) -> { - new ApplicationContextRunner() - .withUserConfiguration(ClassConfigurationProperties.class) - .withParent(parent).run((child) -> { - ConfigurationPropertiesReportEndpoint endpoint = child - .getBean( - ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - assertThat(applicationProperties.getContexts()) - .containsOnlyKeys(child.getId(), parent.getId()); - assertThat(applicationProperties.getContexts() - .get(child.getId()).getBeans().keySet()) - .containsExactly("someProperties"); - assertThat((applicationProperties.getContexts() - .get(parent.getId()).getBeans().keySet())) - .containsExactly("testProperties"); - }); - }); + new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { + new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class).withParent(parent) + .run((child) -> { + ConfigurationPropertiesReportEndpoint endpoint = child + .getBean(ConfigurationPropertiesReportEndpoint.class); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts()).containsOnlyKeys(child.getId(), parent.getId()); + assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) + .containsExactly("someProperties"); + assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) + .containsExactly("testProperties"); + }); + }); } @Test public void configurationPropertiesBeanMethod() { - new ApplicationContextRunner().withUserConfiguration(Parent.class) - .run((parent) -> { - new ApplicationContextRunner() - .withUserConfiguration( - BeanMethodConfigurationProperties.class) - .withParent(parent).run((child) -> { - ConfigurationPropertiesReportEndpoint endpoint = child - .getBean( - ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - assertThat(applicationProperties.getContexts() - .get(child.getId()).getBeans().keySet()) - .containsExactlyInAnyOrder( - "otherProperties"); - assertThat((applicationProperties.getContexts() - .get(parent.getId()).getBeans().keySet())) - .containsExactly("testProperties"); - }); - }); + new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { + new ApplicationContextRunner().withUserConfiguration(BeanMethodConfigurationProperties.class) + .withParent(parent).run((child) -> { + ConfigurationPropertiesReportEndpoint endpoint = child + .getBean(ConfigurationPropertiesReportEndpoint.class); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) + .containsExactlyInAnyOrder("otherProperties"); + assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) + .containsExactly("testProperties"); + }); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java index 14b55c741d6..23ce16b938e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java @@ -49,16 +49,14 @@ public class ConfigurationPropertiesReportEndpointProxyTests { @Test public void testWithProxyClass() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class, SqlExecutor.class); + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class, + SqlExecutor.class); contextRunner.run((context) -> { ApplicationConfigurationProperties applicationProperties = context - .getBean(ConfigurationPropertiesReportEndpoint.class) - .configurationProperties(); - assertThat(applicationProperties.getContexts().get(context.getId()).getBeans() - .values().stream() - .map(ConfigurationPropertiesBeanDescriptor::getPrefix) - .filter("executor.sql"::equals).findFirst()).isNotEmpty(); + .getBean(ConfigurationPropertiesReportEndpoint.class).configurationProperties(); + assertThat(applicationProperties.getContexts().get(context.getId()).getBeans().values().stream() + .map(ConfigurationPropertiesBeanDescriptor::getPrefix).filter("executor.sql"::equals).findFirst()) + .isNotEmpty(); }); } @@ -79,8 +77,7 @@ public class ConfigurationPropertiesReportEndpointProxyTests { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java index 5c5eeb32f23..1ede7313982 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -48,16 +48,14 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test public void testNaming() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(FooConfig.class) + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) .withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -70,22 +68,19 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") public void testNestedNaming() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(FooConfig.class) + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) .withPropertyValues("foo.bar.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo).isNotNull(); Map map = foo.getProperties(); assertThat(map).isNotNull(); assertThat(map).hasSize(2); - assertThat(((Map) map.get("bar")).get("name")) - .isEqualTo("foo"); + assertThat(((Map) map.get("bar")).get("name")).isEqualTo("foo"); }); } @@ -93,15 +88,13 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") public void testSelfReferentialProperty() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(SelfReferentialConfig.class) - .withPropertyValues("foo.name:foo"); + .withUserConfiguration(SelfReferentialConfig.class).withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); assertThat(map).isNotNull(); @@ -120,10 +113,9 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor cycle = applicationProperties - .getContexts().get(context.getId()).getBeans().get("cycle"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor cycle = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("cycle"); assertThat(cycle.getPrefix()).isEqualTo("cycle"); Map map = cycle.getProperties(); assertThat(map).isNotNull(); @@ -135,37 +127,32 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") public void testMap() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MapConfig.class) + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class) .withPropertyValues("foo.map.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor fooProperties = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor fooProperties = applicationProperties.getContexts() + .get(context.getId()).getBeans().get("foo"); assertThat(fooProperties).isNotNull(); assertThat(fooProperties.getPrefix()).isEqualTo("foo"); Map map = fooProperties.getProperties(); assertThat(map).isNotNull(); assertThat(map).hasSize(3); - assertThat(((Map) map.get("map")).get("name")) - .isEqualTo("foo"); + assertThat(((Map) map.get("map")).get("name")).isEqualTo("foo"); }); } @Test public void testEmptyMapIsNotAdded() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MapConfig.class); + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -178,16 +165,14 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") public void testList() { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ListConfig.class) + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(ListConfig.class) .withPropertyValues("foo.list[0]:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -200,15 +185,13 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test public void testInetAddress() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(AddressedConfig.class) - .withPropertyValues("foo.address:192.168.1.10"); + .withUserConfiguration(AddressedConfig.class).withPropertyValues("foo.address:192.168.1.10"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -227,10 +210,9 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties - .getContexts().get(context.getId()).getBeans().get("foo"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) + .getBeans().get("foo"); assertThat(foo.getPrefix()).isEqualTo("foo"); Map propertiesMap = foo.getProperties(); assertThat(propertiesMap).containsOnlyKeys("bar", "name", "map", "list"); @@ -248,11 +230,9 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint - .configurationProperties(); - ConfigurationPropertiesBeanDescriptor hikariDataSource = applicationProperties - .getContexts().get(context.getId()).getBeans() - .get("hikariDataSource"); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + ConfigurationPropertiesBeanDescriptor hikariDataSource = applicationProperties.getContexts() + .get(context.getId()).getBeans().get("hikariDataSource"); Map nestedProperties = hikariDataSource.getProperties(); assertThat(nestedProperties).doesNotContainKey("error"); }); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java index 12f5feec1f2..509e619c23c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java @@ -53,8 +53,7 @@ public class ConfigurationPropertiesReportEndpointTests { public void configurationPropertiesAreReturned() { load((context, properties) -> { assertThat(properties.getBeans().size()).isGreaterThan(0); - ConfigurationPropertiesBeanDescriptor nestedProperties = properties.getBeans() - .get("testProperties"); + ConfigurationPropertiesBeanDescriptor nestedProperties = properties.getBeans().get("testProperties"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.getPrefix()).isEqualTo("test"); assertThat(nestedProperties.getProperties()).isNotEmpty(); @@ -64,8 +63,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void entriesWithNullValuesAreNotIncluded() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).doesNotContainKey("nullValue"); }); } @@ -73,8 +71,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void defaultKeySanitization() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("dbPassword")).isEqualTo("******"); assertThat(nestedProperties.get("myTestProperty")).isEqualTo("654321"); @@ -84,8 +81,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void customKeySanitization() { load("property", (context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("dbPassword")).isEqualTo("123456"); assertThat(nestedProperties.get("myTestProperty")).isEqualTo("******"); @@ -95,8 +91,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void customPatternKeySanitization() { load(".*pass.*", (context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("dbPassword")).isEqualTo("******"); assertThat(nestedProperties.get("myTestProperty")).isEqualTo("654321"); @@ -107,26 +102,21 @@ public class ConfigurationPropertiesReportEndpointTests { @SuppressWarnings("unchecked") public void keySanitizationWithCustomPatternUsingCompositeKeys() { // gh-4415 - load(Arrays.asList(".*\\.secrets\\..*", ".*\\.hidden\\..*"), - (context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); - assertThat(nestedProperties).isNotNull(); - Map secrets = (Map) nestedProperties - .get("secrets"); - Map hidden = (Map) nestedProperties - .get("hidden"); - assertThat(secrets.get("mine")).isEqualTo("******"); - assertThat(secrets.get("yours")).isEqualTo("******"); - assertThat(hidden.get("mine")).isEqualTo("******"); - }); + load(Arrays.asList(".*\\.secrets\\..*", ".*\\.hidden\\..*"), (context, properties) -> { + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); + assertThat(nestedProperties).isNotNull(); + Map secrets = (Map) nestedProperties.get("secrets"); + Map hidden = (Map) nestedProperties.get("hidden"); + assertThat(secrets.get("mine")).isEqualTo("******"); + assertThat(secrets.get("yours")).isEqualTo("******"); + assertThat(hidden.get("mine")).isEqualTo("******"); + }); } @Test public void nonCamelCaseProperty() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("myURL")).isEqualTo("https://example.com"); }); } @@ -134,8 +124,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void simpleBoolean() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("simpleBoolean")).isEqualTo(true); }); } @@ -143,8 +132,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void mixedBoolean() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("mixedBoolean")).isEqualTo(true); }); } @@ -152,8 +140,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void mixedCase() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("mIxedCase")).isEqualTo("mixed"); }); } @@ -161,18 +148,15 @@ public class ConfigurationPropertiesReportEndpointTests { @Test public void duration() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); - assertThat(nestedProperties.get("duration")) - .isEqualTo(Duration.ofSeconds(10).toString()); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); + assertThat(nestedProperties.get("duration")).isEqualTo(Duration.ofSeconds(10).toString()); }); } @Test public void singleLetterProperty() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("z")).isEqualTo("zzz"); }); } @@ -181,8 +165,7 @@ public class ConfigurationPropertiesReportEndpointTests { @SuppressWarnings("unchecked") public void listsAreSanitized() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("listItems")).isInstanceOf(List.class); List list = (List) nestedProperties.get("listItems"); assertThat(list).hasSize(1); @@ -195,11 +178,9 @@ public class ConfigurationPropertiesReportEndpointTests { @SuppressWarnings("unchecked") public void listsOfListsAreSanitized() { load((context, properties) -> { - Map nestedProperties = properties.getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("listOfListItems")).isInstanceOf(List.class); - List> listOfLists = (List>) nestedProperties - .get("listOfListItems"); + List> listOfLists = (List>) nestedProperties.get("listOfListItems"); assertThat(listOfLists).hasSize(1); List list = listOfLists.get(0); assertThat(list).hasSize(1); @@ -208,28 +189,24 @@ public class ConfigurationPropertiesReportEndpointTests { }); } - private void load( - BiConsumer properties) { + private void load(BiConsumer properties) { load(Collections.emptyList(), properties); } - private void load(String keyToSanitize, - BiConsumer properties) { + private void load(String keyToSanitize, BiConsumer properties) { load(Collections.singletonList(keyToSanitize), properties); } private void load(List keysToSanitize, BiConsumer properties) { - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class); + ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context .getBean(ConfigurationPropertiesReportEndpoint.class); if (!CollectionUtils.isEmpty(keysToSanitize)) { endpoint.setKeysToSanitize(StringUtils.toStringArray(keysToSanitize)); } - properties.accept(context, endpoint.configurationProperties().getContexts() - .get(context.getId())); + properties.accept(context, endpoint.configurationProperties().getContexts().get(context.getId())); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java index 21011c335c0..3e415686b07 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java @@ -49,18 +49,15 @@ public class CouchbaseHealthIndicatorTests { public void couchbaseClusterIsUp() { Cluster cluster = mock(Cluster.class); CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(cluster); - List endpoints = Arrays.asList(new EndpointHealth( - ServiceType.BINARY, LifecycleState.CONNECTED, new InetSocketAddress(0), - new InetSocketAddress(0), 1234, "endpoint-1")); - DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", - "test-id", null); + List endpoints = Arrays.asList(new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, + new InetSocketAddress(0), new InetSocketAddress(0), 1234, "endpoint-1")); + DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", "test-id", null); given(cluster.diagnostics()).willReturn(diagnostics); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsKey("endpoints"); - assertThat((List>) health.getDetails().get("endpoints")) - .hasSize(1); + assertThat((List>) health.getDetails().get("endpoints")).hasSize(1); verify(cluster).diagnostics(); } @@ -70,21 +67,17 @@ public class CouchbaseHealthIndicatorTests { Cluster cluster = mock(Cluster.class); CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(cluster); List endpoints = Arrays.asList( - new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, - new InetSocketAddress(0), new InetSocketAddress(0), 1234, - "endpoint-1"), - new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTING, - new InetSocketAddress(0), new InetSocketAddress(0), 1234, - "endpoint-2")); - DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", - "test-id", null); + new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, new InetSocketAddress(0), + new InetSocketAddress(0), 1234, "endpoint-1"), + new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTING, new InetSocketAddress(0), + new InetSocketAddress(0), 1234, "endpoint-2")); + DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", "test-id", null); given(cluster.diagnostics()).willReturn(diagnostics); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsKey("endpoints"); - assertThat((List>) health.getDetails().get("endpoints")) - .hasSize(2); + assertThat((List>) health.getDetails().get("endpoints")).hasSize(2); verify(cluster).diagnostics(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java index e60263553a0..a9240f131c3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java @@ -45,20 +45,16 @@ public class CouchbaseReactiveHealthIndicatorTests { @SuppressWarnings("unchecked") public void couchbaseClusterIsUp() { Cluster cluster = mock(Cluster.class); - CouchbaseReactiveHealthIndicator healthIndicator = new CouchbaseReactiveHealthIndicator( - cluster); - List endpoints = Arrays.asList(new EndpointHealth( - ServiceType.BINARY, LifecycleState.CONNECTED, new InetSocketAddress(0), - new InetSocketAddress(0), 1234, "endpoint-1")); - DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", - "test-id", null); + CouchbaseReactiveHealthIndicator healthIndicator = new CouchbaseReactiveHealthIndicator(cluster); + List endpoints = Arrays.asList(new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, + new InetSocketAddress(0), new InetSocketAddress(0), 1234, "endpoint-1")); + DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", "test-id", null); given(cluster.diagnostics()).willReturn(diagnostics); Health health = healthIndicator.health().block(Duration.ofSeconds(30)); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsKey("endpoints"); - assertThat((List>) health.getDetails().get("endpoints")) - .hasSize(1); + assertThat((List>) health.getDetails().get("endpoints")).hasSize(1); verify(cluster).diagnostics(); } @@ -66,24 +62,19 @@ public class CouchbaseReactiveHealthIndicatorTests { @SuppressWarnings("unchecked") public void couchbaseClusterIsDown() { Cluster cluster = mock(Cluster.class); - CouchbaseReactiveHealthIndicator healthIndicator = new CouchbaseReactiveHealthIndicator( - cluster); + CouchbaseReactiveHealthIndicator healthIndicator = new CouchbaseReactiveHealthIndicator(cluster); List endpoints = Arrays.asList( - new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, - new InetSocketAddress(0), new InetSocketAddress(0), 1234, - "endpoint-1"), - new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTING, - new InetSocketAddress(0), new InetSocketAddress(0), 1234, - "endpoint-2")); - DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", - "test-id", null); + new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, new InetSocketAddress(0), + new InetSocketAddress(0), 1234, "endpoint-1"), + new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTING, new InetSocketAddress(0), + new InetSocketAddress(0), 1234, "endpoint-2")); + DiagnosticsReport diagnostics = new DiagnosticsReport(endpoints, "test-sdk", "test-id", null); given(cluster.diagnostics()).willReturn(diagnostics); Health health = healthIndicator.health().block(Duration.ofSeconds(30)); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsKey("endpoints"); - assertThat((List>) health.getDetails().get("endpoints")) - .hasSize(2); + assertThat((List>) health.getDetails().get("endpoints")).hasSize(2); verify(cluster).diagnostics(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java index 59b6b51a226..cf2bec594cf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java @@ -75,8 +75,7 @@ public class ElasticsearchHealthIndicatorTests { public void defaultConfigurationQueriesAllIndicesWith100msTimeout() { TestActionFuture responseFuture = new TestActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); - ArgumentCaptor requestCaptor = ArgumentCaptor - .forClass(ClusterHealthRequest.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); Health health = this.indicator.health(); assertThat(responseFuture.getTimeout).isEqualTo(100L); @@ -86,16 +85,13 @@ public class ElasticsearchHealthIndicatorTests { @Test public void certainIndices() { - this.indicator = new ElasticsearchHealthIndicator(this.client, 100L, - "test-index-1", "test-index-2"); + this.indicator = new ElasticsearchHealthIndicator(this.client, 100L, "test-index-1", "test-index-2"); PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse()); - ArgumentCaptor requestCaptor = ArgumentCaptor - .forClass(ClusterHealthRequest.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); Health health = this.indicator.health(); - assertThat(requestCaptor.getValue().indices()).contains("test-index-1", - "test-index-2"); + assertThat(requestCaptor.getValue().indices()).contains("test-index-1", "test-index-2"); assertThat(health.getStatus()).isEqualTo(Status.UP); } @@ -104,8 +100,7 @@ public class ElasticsearchHealthIndicatorTests { this.indicator = new ElasticsearchHealthIndicator(this.client, 1000L); TestActionFuture responseFuture = new TestActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); - ArgumentCaptor requestCaptor = ArgumentCaptor - .forClass(ClusterHealthRequest.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); this.indicator.health(); assertThat(responseFuture.getTimeout).isEqualTo(1000L); @@ -115,8 +110,7 @@ public class ElasticsearchHealthIndicatorTests { public void healthDetails() { PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse()); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); Map details = health.getDetails(); @@ -134,30 +128,25 @@ public class ElasticsearchHealthIndicatorTests { public void redResponseMapsToDown() { PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.RED)); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); assertThat(this.indicator.health().getStatus()).isEqualTo(Status.DOWN); } @Test public void yellowResponseMapsToUp() { PlainActionFuture responseFuture = new PlainActionFuture<>(); - responseFuture - .onResponse(new StubClusterHealthResponse(ClusterHealthStatus.YELLOW)); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.YELLOW)); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP); } @Test public void responseTimeout() { PlainActionFuture responseFuture = new PlainActionFuture<>(); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains(ElasticsearchTimeoutException.class.getName()); + assertThat((String) health.getDetails().get("error")).contains(ElasticsearchTimeoutException.class.getName()); } @SuppressWarnings("unchecked") @@ -174,10 +163,8 @@ public class ElasticsearchHealthIndicatorTests { } private StubClusterHealthResponse(ClusterHealthStatus status) { - super("test-cluster", new String[0], - new ClusterState(null, 0, null, null, RoutingTable.builder().build(), - DiscoveryNodes.builder().build(), - ClusterBlocks.builder().build(), null, 1, false)); + super("test-cluster", new String[0], new ClusterState(null, 0, null, null, RoutingTable.builder().build(), + DiscoveryNodes.builder().build(), ClusterBlocks.builder().build(), null, 1, false)); this.status = status; } @@ -223,14 +210,12 @@ public class ElasticsearchHealthIndicatorTests { } - private static class TestActionFuture - extends PlainActionFuture { + private static class TestActionFuture extends PlainActionFuture { private long getTimeout = -1L; @Override - public ClusterHealthResponse actionGet(long timeoutMillis) - throws ElasticsearchException { + public ClusterHealthResponse actionGet(long timeoutMillis) throws ElasticsearchException { this.getTimeout = timeoutMillis; return super.actionGet(timeoutMillis); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java index 3d33c98dcc1..93109d1bdcf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java @@ -54,8 +54,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsUp() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(200, true, "green")); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, true, "green")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertHealthDetailsWithStatus(health.getDetails(), "green"); @@ -64,8 +63,7 @@ public class ElasticsearchJestHealthIndicatorTests { @Test @SuppressWarnings("unchecked") public void elasticsearchWithYellowStatusIsUp() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(200, true, "yellow")); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, true, "yellow")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertHealthDetailsWithStatus(health.getDetails(), "yellow"); @@ -74,8 +72,8 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsDown() throws IOException { - given(this.jestClient.execute(any(Action.class))).willThrow( - new CouldNotConnectException("http://localhost:9200", new IOException())); + given(this.jestClient.execute(any(Action.class))) + .willThrow(new CouldNotConnectException("http://localhost:9200", new IOException())); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); } @@ -83,8 +81,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsDownWhenQueryDidNotSucceed() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(200, false, "")); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, false, "")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); } @@ -92,8 +89,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsDownByResponseCode() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(500, false, "")); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(500, false, "")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails()).contains(entry("statusCode", 500)); @@ -102,45 +98,38 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsOutOfServiceByStatus() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(200, true, "red")); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, true, "red")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE); assertHealthDetailsWithStatus(health.getDetails(), "red"); } - private void assertHealthDetailsWithStatus(Map details, - String status) { - assertThat(details).contains(entry("cluster_name", "elasticsearch"), - entry("status", status), entry("timed_out", false), - entry("number_of_nodes", 1), entry("number_of_data_nodes", 1), - entry("active_primary_shards", 0), entry("active_shards", 0), - entry("relocating_shards", 0), entry("initializing_shards", 0), - entry("unassigned_shards", 0), entry("delayed_unassigned_shards", 0), - entry("number_of_pending_tasks", 0), - entry("number_of_in_flight_fetch", 0), - entry("task_max_waiting_in_queue_millis", 0), - entry("active_shards_percent_as_number", 100.0)); + private void assertHealthDetailsWithStatus(Map details, String status) { + assertThat(details).contains(entry("cluster_name", "elasticsearch"), entry("status", status), + entry("timed_out", false), entry("number_of_nodes", 1), entry("number_of_data_nodes", 1), + entry("active_primary_shards", 0), entry("active_shards", 0), entry("relocating_shards", 0), + entry("initializing_shards", 0), entry("unassigned_shards", 0), entry("delayed_unassigned_shards", 0), + entry("number_of_pending_tasks", 0), entry("number_of_in_flight_fetch", 0), + entry("task_max_waiting_in_queue_millis", 0), entry("active_shards_percent_as_number", 100.0)); } - private static JestResult createJestResult(int responseCode, boolean succeeded, - String status) { + private static JestResult createJestResult(int responseCode, boolean succeeded, String status) { SearchResult searchResult = new SearchResult(new Gson()); String json; if (responseCode == 200) { - json = String.format("{\"cluster_name\":\"elasticsearch\"," - + "\"status\":\"%s\",\"timed_out\":false,\"number_of_nodes\":1," - + "\"number_of_data_nodes\":1,\"active_primary_shards\":0," - + "\"active_shards\":0,\"relocating_shards\":0,\"initializing_shards\":0," - + "\"unassigned_shards\":0,\"delayed_unassigned_shards\":0," - + "\"number_of_pending_tasks\":0,\"number_of_in_flight_fetch\":0," - + "\"task_max_waiting_in_queue_millis\":0,\"active_shards_percent_as_number\":100.0}", + json = String.format( + "{\"cluster_name\":\"elasticsearch\"," + + "\"status\":\"%s\",\"timed_out\":false,\"number_of_nodes\":1," + + "\"number_of_data_nodes\":1,\"active_primary_shards\":0," + + "\"active_shards\":0,\"relocating_shards\":0,\"initializing_shards\":0," + + "\"unassigned_shards\":0,\"delayed_unassigned_shards\":0," + + "\"number_of_pending_tasks\":0,\"number_of_in_flight_fetch\":0," + + "\"task_max_waiting_in_queue_millis\":0,\"active_shards_percent_as_number\":100.0}", status); } else { - json = "{\n" + " \"error\": \"Server Error\",\n" + " \"status\": \"" - + status + "\"\n" + "}"; + json = "{\n" + " \"error\": \"Server Error\",\n" + " \"status\": \"" + status + "\"\n" + "}"; } searchResult.setJsonString(json); searchResult.setJsonObject(new JsonParser().parse(json).getAsJsonObject()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java index c9fe1e20261..a4a3b6bac93 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java @@ -52,8 +52,7 @@ public class ElasticsearchRestHealthIndicatorTest { @Test public void elasticsearchIsUp() throws IOException { BasicHttpEntity httpEntity = new BasicHttpEntity(); - httpEntity.setContent( - new ByteArrayInputStream(createJsonResult(200, "green").getBytes())); + httpEntity.setContent(new ByteArrayInputStream(createJsonResult(200, "green").getBytes())); Response response = mock(Response.class); StatusLine statusLine = mock(StatusLine.class); given(statusLine.getStatusCode()).willReturn(200); @@ -68,8 +67,7 @@ public class ElasticsearchRestHealthIndicatorTest { @Test public void elasticsearchWithYellowStatusIsUp() throws IOException { BasicHttpEntity httpEntity = new BasicHttpEntity(); - httpEntity.setContent( - new ByteArrayInputStream(createJsonResult(200, "yellow").getBytes())); + httpEntity.setContent(new ByteArrayInputStream(createJsonResult(200, "yellow").getBytes())); Response response = mock(Response.class); StatusLine statusLine = mock(StatusLine.class); given(statusLine.getStatusCode()).willReturn(200); @@ -83,12 +81,10 @@ public class ElasticsearchRestHealthIndicatorTest { @Test public void elasticsearchIsDown() throws IOException { - given(this.restClient.performRequest(any(Request.class))) - .willThrow(new IOException("Couldn't connect")); + given(this.restClient.performRequest(any(Request.class))).willThrow(new IOException("Couldn't connect")); Health health = this.elasticsearchRestHealthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat(health.getDetails()) - .contains(entry("error", "java.io.IOException: Couldn't connect")); + assertThat(health.getDetails()).contains(entry("error", "java.io.IOException: Couldn't connect")); } @Test @@ -108,8 +104,7 @@ public class ElasticsearchRestHealthIndicatorTest { @Test public void elasticsearchIsOutOfServiceByStatus() throws IOException { BasicHttpEntity httpEntity = new BasicHttpEntity(); - httpEntity.setContent( - new ByteArrayInputStream(createJsonResult(200, "red").getBytes())); + httpEntity.setContent(new ByteArrayInputStream(createJsonResult(200, "red").getBytes())); Response response = mock(Response.class); StatusLine statusLine = mock(StatusLine.class); given(statusLine.getStatusCode()).willReturn(200); @@ -121,33 +116,28 @@ public class ElasticsearchRestHealthIndicatorTest { assertHealthDetailsWithStatus(health.getDetails(), "red"); } - private void assertHealthDetailsWithStatus(Map details, - String status) { - assertThat(details).contains(entry("cluster_name", "elasticsearch"), - entry("status", status), entry("timed_out", false), - entry("number_of_nodes", 1), entry("number_of_data_nodes", 1), - entry("active_primary_shards", 0), entry("active_shards", 0), - entry("relocating_shards", 0), entry("initializing_shards", 0), - entry("unassigned_shards", 0), entry("delayed_unassigned_shards", 0), - entry("number_of_pending_tasks", 0), - entry("number_of_in_flight_fetch", 0), - entry("task_max_waiting_in_queue_millis", 0), - entry("active_shards_percent_as_number", 100.0)); + private void assertHealthDetailsWithStatus(Map details, String status) { + assertThat(details).contains(entry("cluster_name", "elasticsearch"), entry("status", status), + entry("timed_out", false), entry("number_of_nodes", 1), entry("number_of_data_nodes", 1), + entry("active_primary_shards", 0), entry("active_shards", 0), entry("relocating_shards", 0), + entry("initializing_shards", 0), entry("unassigned_shards", 0), entry("delayed_unassigned_shards", 0), + entry("number_of_pending_tasks", 0), entry("number_of_in_flight_fetch", 0), + entry("task_max_waiting_in_queue_millis", 0), entry("active_shards_percent_as_number", 100.0)); } private String createJsonResult(int responseCode, String status) { if (responseCode == 200) { - return String.format("{\"cluster_name\":\"elasticsearch\"," - + "\"status\":\"%s\",\"timed_out\":false,\"number_of_nodes\":1," - + "\"number_of_data_nodes\":1,\"active_primary_shards\":0," - + "\"active_shards\":0,\"relocating_shards\":0,\"initializing_shards\":0," - + "\"unassigned_shards\":0,\"delayed_unassigned_shards\":0," - + "\"number_of_pending_tasks\":0,\"number_of_in_flight_fetch\":0," - + "\"task_max_waiting_in_queue_millis\":0,\"active_shards_percent_as_number\":100.0}", + return String.format( + "{\"cluster_name\":\"elasticsearch\"," + + "\"status\":\"%s\",\"timed_out\":false,\"number_of_nodes\":1," + + "\"number_of_data_nodes\":1,\"active_primary_shards\":0," + + "\"active_shards\":0,\"relocating_shards\":0,\"initializing_shards\":0," + + "\"unassigned_shards\":0,\"delayed_unassigned_shards\":0," + + "\"number_of_pending_tasks\":0,\"number_of_in_flight_fetch\":0," + + "\"task_max_waiting_in_queue_millis\":0,\"active_shards_percent_as_number\":100.0}", status); } - return "{\n" + " \"error\": \"Server Error\",\n" + " \"status\": " - + responseCode + "\n" + "}"; + return "{\n" + " \"error\": \"Server Error\",\n" + " \"status\": " + responseCode + "\n" + "}"; } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java index 427ea75c74b..3ce7a43af3e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java @@ -41,8 +41,7 @@ public class EndpointIdTests { @Test public void ofWhenEmptyThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("")) - .withMessage("Value must not be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("")).withMessage("Value must not be empty"); } @Test @@ -89,8 +88,8 @@ public class EndpointIdTests { public void ofWhenContainsDeprecatedCharsLogsWarning(CapturedOutput capturedOutput) { EndpointId.resetLoggedWarnings(); EndpointId.of("foo-bar"); - assertThat(capturedOutput.toString()).contains( - "Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); + assertThat(capturedOutput.toString()) + .contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); } @Test @@ -102,8 +101,8 @@ public class EndpointIdTests { EndpointId five = EndpointId.of("barfoo1"); EndpointId six = EndpointId.of("foobar2"); assertThat(one.hashCode()).isEqualTo(two.hashCode()); - assertThat(one).isEqualTo(one).isEqualTo(two).isEqualTo(three).isEqualTo(four) - .isNotEqualTo(five).isNotEqualTo(six); + assertThat(one).isEqualTo(one).isEqualTo(two).isEqualTo(three).isEqualTo(four).isNotEqualTo(five) + .isNotEqualTo(six); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java index 5e6a3325228..bd297eee287 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java @@ -39,8 +39,7 @@ public class SanitizerTests { assertThat(sanitizer.sanitize("token", "secret")).isEqualTo("******"); assertThat(sanitizer.sanitize("sometoken", "secret")).isEqualTo("******"); assertThat(sanitizer.sanitize("find", "secret")).isEqualTo("secret"); - assertThat(sanitizer.sanitize("sun.java.command", - "--spring.redis.password=pa55w0rd")).isEqualTo("******"); + assertThat(sanitizer.sanitize("sun.java.command", "--spring.redis.password=pa55w0rd")).isEqualTo("******"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java index 841417655a5..43b8be1932b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java @@ -37,8 +37,8 @@ public class DiscoveredOperationMethodTests { @Test public void createWhenAnnotationAttributesIsNullShouldThrowException() { Method method = ReflectionUtils.findMethod(getClass(), "example"); - assertThatIllegalArgumentException().isThrownBy( - () -> new DiscoveredOperationMethod(method, OperationType.READ, null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new DiscoveredOperationMethod(method, OperationType.READ, null)) .withMessageContaining("AnnotationAttributes must not be null"); } @@ -48,10 +48,9 @@ public class DiscoveredOperationMethodTests { AnnotationAttributes annotationAttributes = new AnnotationAttributes(); String[] produces = new String[] { "application/json" }; annotationAttributes.put("produces", produces); - DiscoveredOperationMethod discovered = new DiscoveredOperationMethod(method, - OperationType.READ, annotationAttributes); - assertThat(discovered.getProducesMediaTypes()) - .containsExactly("application/json"); + DiscoveredOperationMethod discovered = new DiscoveredOperationMethod(method, OperationType.READ, + annotationAttributes); + assertThat(discovered.getProducesMediaTypes()).containsExactly("application/json"); } public void example() { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java index 8b412b17bc3..bc7d7b21e38 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java @@ -55,14 +55,12 @@ public class DiscoveredOperationsFactoryTests { public void setup() { this.parameterValueMapper = (parameter, value) -> value.toString(); this.invokerAdvisors = new ArrayList<>(); - this.factory = new TestDiscoveredOperationsFactory(this.parameterValueMapper, - this.invokerAdvisors); + this.factory = new TestDiscoveredOperationsFactory(this.parameterValueMapper, this.invokerAdvisors); } @Test public void createOperationsWhenHasReadMethodShouldCreateOperation() { - Collection operations = this.factory - .createOperations(EndpointId.of("test"), new ExampleRead()); + Collection operations = this.factory.createOperations(EndpointId.of("test"), new ExampleRead()); assertThat(operations).hasSize(1); TestOperation operation = getFirst(operations); assertThat(operation.getType()).isEqualTo(OperationType.READ); @@ -70,8 +68,7 @@ public class DiscoveredOperationsFactoryTests { @Test public void createOperationsWhenHasWriteMethodShouldCreateOperation() { - Collection operations = this.factory - .createOperations(EndpointId.of("test"), new ExampleWrite()); + Collection operations = this.factory.createOperations(EndpointId.of("test"), new ExampleWrite()); assertThat(operations).hasSize(1); TestOperation operation = getFirst(operations); assertThat(operation.getType()).isEqualTo(OperationType.WRITE); @@ -79,8 +76,8 @@ public class DiscoveredOperationsFactoryTests { @Test public void createOperationsWhenHasDeleteMethodShouldCreateOperation() { - Collection operations = this.factory - .createOperations(EndpointId.of("test"), new ExampleDelete()); + Collection operations = this.factory.createOperations(EndpointId.of("test"), + new ExampleDelete()); assertThat(operations).hasSize(1); TestOperation operation = getFirst(operations); assertThat(operation.getType()).isEqualTo(OperationType.DELETE); @@ -88,17 +85,17 @@ public class DiscoveredOperationsFactoryTests { @Test public void createOperationsWhenMultipleShouldReturnMultiple() { - Collection operations = this.factory - .createOperations(EndpointId.of("test"), new ExampleMultiple()); + Collection operations = this.factory.createOperations(EndpointId.of("test"), + new ExampleMultiple()); assertThat(operations).hasSize(2); - assertThat(operations.stream().map(TestOperation::getType)) - .containsOnly(OperationType.READ, OperationType.WRITE); + assertThat(operations.stream().map(TestOperation::getType)).containsOnly(OperationType.READ, + OperationType.WRITE); } @Test public void createOperationsShouldProvideOperationMethod() { - TestOperation operation = getFirst(this.factory - .createOperations(EndpointId.of("test"), new ExampleWithParams())); + TestOperation operation = getFirst( + this.factory.createOperations(EndpointId.of("test"), new ExampleWithParams())); OperationMethod operationMethod = operation.getOperationMethod(); assertThat(operationMethod.getMethod().getName()).isEqualTo("read"); assertThat(operationMethod.getParameters().hasParameters()).isTrue(); @@ -106,11 +103,10 @@ public class DiscoveredOperationsFactoryTests { @Test public void createOperationsShouldProviderInvoker() { - TestOperation operation = getFirst(this.factory - .createOperations(EndpointId.of("test"), new ExampleWithParams())); + TestOperation operation = getFirst( + this.factory.createOperations(EndpointId.of("test"), new ExampleWithParams())); Map params = Collections.singletonMap("name", 123); - Object result = operation - .invoke(new InvocationContext(mock(SecurityContext.class), params)); + Object result = operation.invoke(new InvocationContext(mock(SecurityContext.class), params)); assertThat(result).isEqualTo("123"); } @@ -118,10 +114,8 @@ public class DiscoveredOperationsFactoryTests { public void createOperationShouldApplyAdvisors() { TestOperationInvokerAdvisor advisor = new TestOperationInvokerAdvisor(); this.invokerAdvisors.add(advisor); - TestOperation operation = getFirst( - this.factory.createOperations(EndpointId.of("test"), new ExampleRead())); - operation.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.emptyMap())); + TestOperation operation = getFirst(this.factory.createOperations(EndpointId.of("test"), new ExampleRead())); + operation.invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap())); assertThat(advisor.getEndpointId()).isEqualTo(EndpointId.of("test")); assertThat(advisor.getOperationType()).isEqualTo(OperationType.READ); assertThat(advisor.getParameters()).isEmpty(); @@ -181,8 +175,7 @@ public class DiscoveredOperationsFactoryTests { } - static class TestDiscoveredOperationsFactory - extends DiscoveredOperationsFactory { + static class TestDiscoveredOperationsFactory extends DiscoveredOperationsFactory { TestDiscoveredOperationsFactory(ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { @@ -190,8 +183,8 @@ public class DiscoveredOperationsFactoryTests { } @Override - protected TestOperation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected TestOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return new TestOperation(endpointId, operationMethod, invoker); } @@ -199,8 +192,7 @@ public class DiscoveredOperationsFactoryTests { static class TestOperation extends AbstractDiscoveredOperation { - TestOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, - OperationInvoker invoker) { + TestOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { super(operationMethod, invoker); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java index 4c5825f4874..5f28eca0e1f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java @@ -41,23 +41,20 @@ public class DiscovererEndpointFilterTests { @Test public void createWhenDiscovererIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new TestDiscovererEndpointFilter(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new TestDiscovererEndpointFilter(null)) .withMessageContaining("Discoverer must not be null"); } @Test public void matchWhenDiscoveredByDiscovererShouldReturnTrue() { - DiscovererEndpointFilter filter = new TestDiscovererEndpointFilter( - TestDiscovererA.class); + DiscovererEndpointFilter filter = new TestDiscovererEndpointFilter(TestDiscovererA.class); DiscoveredEndpoint endpoint = mockDiscoveredEndpoint(TestDiscovererA.class); assertThat(filter.match(endpoint)).isTrue(); } @Test public void matchWhenNotDiscoveredByDiscovererShouldReturnFalse() { - DiscovererEndpointFilter filter = new TestDiscovererEndpointFilter( - TestDiscovererA.class); + DiscovererEndpointFilter filter = new TestDiscovererEndpointFilter(TestDiscovererA.class); DiscoveredEndpoint endpoint = mockDiscoveredEndpoint(TestDiscovererB.class); assertThat(filter.match(endpoint)).isFalse(); } @@ -71,18 +68,15 @@ public class DiscovererEndpointFilterTests { static class TestDiscovererEndpointFilter extends DiscovererEndpointFilter { - TestDiscovererEndpointFilter( - Class> discoverer) { + TestDiscovererEndpointFilter(Class> discoverer) { super(discoverer); } } - abstract static class TestDiscovererA - extends EndpointDiscoverer, Operation> { + abstract static class TestDiscovererA extends EndpointDiscoverer, Operation> { - TestDiscovererA(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, + TestDiscovererA(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection>> filters) { super(applicationContext, parameterValueMapper, invokerAdvisors, filters); @@ -90,11 +84,9 @@ public class DiscovererEndpointFilterTests { } - abstract static class TestDiscovererB - extends EndpointDiscoverer, Operation> { + abstract static class TestDiscovererB extends EndpointDiscoverer, Operation> { - TestDiscovererB(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, + TestDiscovererB(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection>> filters) { super(applicationContext, parameterValueMapper, invokerAdvisors, filters); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java index d800bf1a1a4..7d84686e5f5 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java @@ -69,34 +69,31 @@ public class EndpointDiscovererTests { @Test public void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(null, - mock(ParameterValueMapper.class), Collections.emptyList(), - Collections.emptyList())) + .isThrownBy(() -> new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), + Collections.emptyList(), Collections.emptyList())) .withMessageContaining("ApplicationContext must not be null"); } @Test public void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new TestEndpointDiscoverer(mock(ApplicationContext.class), - null, Collections.emptyList(), Collections.emptyList())) + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), null, + Collections.emptyList(), Collections.emptyList())) .withMessageContaining("ParameterValueMapper must not be null"); } @Test public void createWhenInvokerAdvisorsIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer( - mock(ApplicationContext.class), mock(ParameterValueMapper.class), - null, Collections.emptyList())) + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + mock(ParameterValueMapper.class), null, Collections.emptyList())) .withMessageContaining("InvokerAdvisors must not be null"); } @Test public void createWhenFiltersIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + assertThatIllegalArgumentException() + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), mock(ParameterValueMapper.class), Collections.emptyList(), null)) .withMessageContaining("Filters must not be null"); } @@ -126,16 +123,13 @@ public class EndpointDiscovererTests { public void getEndpointsWhenHasSubclassedEndpointShouldReturnEndpoint() { load(TestEndpointSubclassConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - Map operations = mapOperations( - endpoints.get(EndpointId.of("test"))); + Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); assertThat(operations).hasSize(5); assertThat(operations).containsKeys(testEndpointMethods()); - assertThat(operations).containsKeys(ReflectionUtils.findMethod( - TestEndpointSubclass.class, "updateWithMoreArguments", String.class, - String.class, String.class)); + assertThat(operations).containsKeys(ReflectionUtils.findMethod(TestEndpointSubclass.class, + "updateWithMoreArguments", String.class, String.class, String.class)); }); } @@ -144,34 +138,27 @@ public class EndpointDiscovererTests { load(ClashingEndpointConfiguration.class, (context) -> assertThatIllegalStateException() .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) - .withMessageContaining( - "Found two endpoints with the id 'test': ")); + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test public void getEndpointsWhenEndpointsArePrefixedWithScopedTargetShouldRegisterOnlyOneEndpoint() { load(ScopedTargetEndpointConfiguration.class, (context) -> { - TestEndpoint expectedEndpoint = context.getBean("testEndpoint", - TestEndpoint.class); - Collection endpoints = new TestEndpointDiscoverer( - context).getEndpoints(); - assertThat(endpoints).flatExtracting(TestExposableEndpoint::getEndpointBean) - .containsOnly(expectedEndpoint); + TestEndpoint expectedEndpoint = context.getBean("testEndpoint", TestEndpoint.class); + Collection endpoints = new TestEndpointDiscoverer(context).getEndpoints(); + assertThat(endpoints).flatExtracting(TestExposableEndpoint::getEndpointBean).containsOnly(expectedEndpoint); }); } @Test public void getEndpointsWhenTtlSetToZeroShouldNotCacheInvokeCalls() { load(TestEndpointConfiguration.class, (context) -> { - TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, - (endpointId) -> 0L); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, (endpointId) -> 0L); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - Map operations = mapOperations( - endpoints.get(EndpointId.of("test"))); - operations.values().forEach((operation) -> assertThat(operation.getInvoker()) - .isNotInstanceOf(CachingOperationInvoker.class)); + Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); + operations.values().forEach( + (operation) -> assertThat(operation.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class)); }); } @@ -180,13 +167,11 @@ public class EndpointDiscovererTests { load(TestEndpointConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, (endpointId) -> (endpointId.equals("foo") ? 500L : 0L)); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - Map operations = mapOperations( - endpoints.get(EndpointId.of("test"))); - operations.values().forEach((operation) -> assertThat(operation.getInvoker()) - .isNotInstanceOf(CachingOperationInvoker.class)); + Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); + operations.values().forEach( + (operation) -> assertThat(operation.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class)); }); } @@ -194,24 +179,17 @@ public class EndpointDiscovererTests { public void getEndpointsWhenTtlSetByIdAndIdMatchesShouldCacheInvokeCalls() { load(TestEndpointConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, - (endpointId) -> (endpointId.equals(EndpointId.of("test")) ? 500L - : 0L)); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + (endpointId) -> (endpointId.equals(EndpointId.of("test")) ? 500L : 0L)); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - Map operations = mapOperations( - endpoints.get(EndpointId.of("test"))); + Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); TestOperation getAll = operations.get(findTestEndpointMethod("getAll")); - TestOperation getOne = operations - .get(findTestEndpointMethod("getOne", String.class)); - TestOperation update = operations.get(ReflectionUtils.findMethod( - TestEndpoint.class, "update", String.class, String.class)); - assertThat(((CachingOperationInvoker) getAll.getInvoker()).getTimeToLive()) - .isEqualTo(500); - assertThat(getOne.getInvoker()) - .isNotInstanceOf(CachingOperationInvoker.class); - assertThat(update.getInvoker()) - .isNotInstanceOf(CachingOperationInvoker.class); + TestOperation getOne = operations.get(findTestEndpointMethod("getOne", String.class)); + TestOperation update = operations + .get(ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class, String.class)); + assertThat(((CachingOperationInvoker) getAll.getInvoker()).getTimeToLive()).isEqualTo(500); + assertThat(getOne.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class); + assertThat(update.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class); }); } @@ -219,8 +197,7 @@ public class EndpointDiscovererTests { public void getEndpointsWhenHasSpecializedFiltersInNonSpecializedDiscovererShouldFilterEndpoints() { load(SpecializedEndpointsConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); }); } @@ -228,26 +205,19 @@ public class EndpointDiscovererTests { @Test public void getEndpointsWhenHasSpecializedFiltersInSpecializedDiscovererShouldNotFilterEndpoints() { load(SpecializedEndpointsConfiguration.class, (context) -> { - SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer( - context); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); - assertThat(endpoints).containsOnlyKeys(EndpointId.of("test"), - EndpointId.of("specialized")); + SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); + assertThat(endpoints).containsOnlyKeys(EndpointId.of("test"), EndpointId.of("specialized")); }); } @Test public void getEndpointsShouldApplyExtensions() { load(SpecializedEndpointsConfiguration.class, (context) -> { - SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer( - context); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); - Map operations = mapOperations( - endpoints.get(EndpointId.of("specialized"))); - assertThat(operations).containsKeys( - ReflectionUtils.findMethod(SpecializedExtension.class, "getSpecial")); + SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); + Map operations = mapOperations(endpoints.get(EndpointId.of("specialized"))); + assertThat(operations).containsKeys(ReflectionUtils.findMethod(SpecializedExtension.class, "getSpecial")); }); } @@ -255,18 +225,13 @@ public class EndpointDiscovererTests { @Test public void getEndpointShouldFindParentExtension() { load(SubSpecializedEndpointsConfiguration.class, (context) -> { - SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer( - context); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); - Map operations = mapOperations( - endpoints.get(EndpointId.of("specialized"))); + SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); + Map operations = mapOperations(endpoints.get(EndpointId.of("specialized"))); + assertThat(operations).containsKeys(ReflectionUtils.findMethod(SpecializedTestEndpoint.class, "getAll")); assertThat(operations).containsKeys( - ReflectionUtils.findMethod(SpecializedTestEndpoint.class, "getAll")); - assertThat(operations).containsKeys(ReflectionUtils.findMethod( - SubSpecializedTestEndpoint.class, "getSpecialOne", String.class)); - assertThat(operations).containsKeys( - ReflectionUtils.findMethod(SpecializedExtension.class, "getSpecial")); + ReflectionUtils.findMethod(SubSpecializedTestEndpoint.class, "getSpecialOne", String.class)); + assertThat(operations).containsKeys(ReflectionUtils.findMethod(SpecializedExtension.class, "getSpecial")); assertThat(operations).hasSize(3); }); } @@ -278,21 +243,18 @@ public class EndpointDiscovererTests { EndpointId id = endpoint.getEndpointId(); return !id.equals(EndpointId.of("specialized")); }; - SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer( - context, Collections.singleton(filter)); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context, + Collections.singleton(filter)); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); }); } private void hasTestEndpoint(AnnotationConfigApplicationContext context) { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context); - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - Map operations = mapOperations( - endpoints.get(EndpointId.of("test"))); + Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); assertThat(operations).hasSize(4); assertThat(operations).containsKeys(); } @@ -310,37 +272,32 @@ public class EndpointDiscovererTests { return ReflectionUtils.findMethod(TestEndpoint.class, name, paramTypes); } - private > Map mapEndpoints( - Collection endpoints) { + private > Map mapEndpoints(Collection endpoints) { Map byId = new LinkedHashMap<>(); endpoints.forEach((endpoint) -> { E existing = byId.put(endpoint.getEndpointId(), endpoint); if (existing != null) { throw new AssertionError( - String.format("Found endpoints with duplicate id '%s'", - endpoint.getEndpointId())); + String.format("Found endpoints with duplicate id '%s'", endpoint.getEndpointId())); } }); return byId; } - private Map mapOperations( - ExposableEndpoint endpoint) { + private Map mapOperations(ExposableEndpoint endpoint) { Map byMethod = new HashMap<>(); endpoint.getOperations().forEach((operation) -> { AbstractDiscoveredOperation discoveredOperation = (AbstractDiscoveredOperation) operation; Method method = discoveredOperation.getOperationMethod().getMethod(); O existing = byMethod.put(method, operation); if (existing != null) { - throw new AssertionError(String.format( - "Found endpoint with duplicate operation method '%s'", method)); + throw new AssertionError(String.format("Found endpoint with duplicate operation method '%s'", method)); } }); return byMethod; } - private void load(Class configuration, - Consumer consumer) { + private void load(Class configuration, Consumer consumer) { load(null, configuration, consumer); } @@ -420,14 +377,12 @@ public class EndpointDiscovererTests { } - @Import({ TestEndpoint.class, SpecializedTestEndpoint.class, - SpecializedExtension.class }) + @Import({ TestEndpoint.class, SpecializedTestEndpoint.class, SpecializedExtension.class }) static class SpecializedEndpointsConfiguration { } - @Import({ TestEndpoint.class, SubSpecializedTestEndpoint.class, - SpecializedExtension.class }) + @Import({ TestEndpoint.class, SubSpecializedTestEndpoint.class, SpecializedExtension.class }) static class SubSpecializedEndpointsConfiguration { } @@ -482,8 +437,7 @@ public class EndpointDiscovererTests { } - @EndpointExtension(endpoint = SpecializedTestEndpoint.class, - filter = SpecializedEndpointFilter.class) + @EndpointExtension(endpoint = SpecializedTestEndpoint.class, filter = SpecializedEndpointFilter.class) public static class SpecializedExtension { @ReadOperation @@ -520,43 +474,37 @@ public class EndpointDiscovererTests { } - static class TestEndpointDiscoverer - extends EndpointDiscoverer { + static class TestEndpointDiscoverer extends EndpointDiscoverer { TestEndpointDiscoverer(ApplicationContext applicationContext) { this(applicationContext, (id) -> null); } - TestEndpointDiscoverer(ApplicationContext applicationContext, - Function timeToLive) { + TestEndpointDiscoverer(ApplicationContext applicationContext, Function timeToLive) { this(applicationContext, timeToLive, Collections.emptyList()); } - TestEndpointDiscoverer(ApplicationContext applicationContext, - Function timeToLive, + TestEndpointDiscoverer(ApplicationContext applicationContext, Function timeToLive, Collection> filters) { this(applicationContext, new ConversionServiceParameterValueMapper(), - Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), - filters); + Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), filters); } - TestEndpointDiscoverer(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, + TestEndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { super(applicationContext, parameterValueMapper, invokerAdvisors, filters); } @Override - protected TestExposableEndpoint createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - return new TestExposableEndpoint(this, endpointBean, id, enabledByDefault, - operations); + protected TestExposableEndpoint createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, + Collection operations) { + return new TestExposableEndpoint(this, endpointBean, id, enabledByDefault, operations); } @Override - protected TestOperation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected TestOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return new TestOperation(operationMethod, invoker); } @@ -568,8 +516,8 @@ public class EndpointDiscovererTests { } - static class SpecializedEndpointDiscoverer extends - EndpointDiscoverer { + static class SpecializedEndpointDiscoverer + extends EndpointDiscoverer { SpecializedEndpointDiscoverer(ApplicationContext applicationContext) { this(applicationContext, Collections.emptyList()); @@ -577,21 +525,18 @@ public class EndpointDiscovererTests { SpecializedEndpointDiscoverer(ApplicationContext applicationContext, Collection> filters) { - super(applicationContext, new ConversionServiceParameterValueMapper(), - Collections.emptyList(), filters); + super(applicationContext, new ConversionServiceParameterValueMapper(), Collections.emptyList(), filters); } @Override - protected SpecializedExposableEndpoint createEndpoint(Object endpointBean, - EndpointId id, boolean enabledByDefault, - Collection operations) { - return new SpecializedExposableEndpoint(this, endpointBean, id, - enabledByDefault, operations); + protected SpecializedExposableEndpoint createEndpoint(Object endpointBean, EndpointId id, + boolean enabledByDefault, Collection operations) { + return new SpecializedExposableEndpoint(this, endpointBean, id, enabledByDefault, operations); } @Override - protected SpecializedOperation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected SpecializedOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return new SpecializedOperation(operationMethod, invoker); } @@ -605,20 +550,17 @@ public class EndpointDiscovererTests { static class TestExposableEndpoint extends AbstractDiscoveredEndpoint { - TestExposableEndpoint(EndpointDiscoverer discoverer, Object endpointBean, - EndpointId id, boolean enabledByDefault, - Collection operations) { + TestExposableEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, + boolean enabledByDefault, Collection operations) { super(discoverer, endpointBean, id, enabledByDefault, operations); } } - static class SpecializedExposableEndpoint - extends AbstractDiscoveredEndpoint { + static class SpecializedExposableEndpoint extends AbstractDiscoveredEndpoint { - SpecializedExposableEndpoint(EndpointDiscoverer discoverer, - Object endpointBean, EndpointId id, boolean enabledByDefault, - Collection operations) { + SpecializedExposableEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, + boolean enabledByDefault, Collection operations) { super(discoverer, endpointBean, id, enabledByDefault, operations); } @@ -628,8 +570,7 @@ public class EndpointDiscovererTests { private final OperationInvoker invoker; - TestOperation(DiscoveredOperationMethod operationMethod, - OperationInvoker invoker) { + TestOperation(DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { super(operationMethod, invoker); this.invoker = invoker; } @@ -642,8 +583,7 @@ public class EndpointDiscovererTests { static class SpecializedOperation extends TestOperation { - SpecializedOperation(DiscoveredOperationMethod operationMethod, - OperationInvoker invoker) { + SpecializedOperation(DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { super(operationMethod, invoker); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java index 21f4444e5aa..4d762e78962 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java @@ -43,12 +43,9 @@ public class ConversionServiceParameterValueMapperTests { @Test public void mapParameterShouldDelegateToConversionService() { - DefaultFormattingConversionService conversionService = spy( - new DefaultFormattingConversionService()); - ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( - conversionService); - Object mapped = mapper - .mapParameterValue(new TestOperationParameter(Integer.class), "123"); + DefaultFormattingConversionService conversionService = spy(new DefaultFormattingConversionService()); + ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); + Object mapped = mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123"); assertThat(mapped).isEqualTo(123); verify(conversionService).convert("123", Integer.class); } @@ -58,11 +55,9 @@ public class ConversionServiceParameterValueMapperTests { ConversionService conversionService = mock(ConversionService.class); RuntimeException error = new RuntimeException(); given(conversionService.convert(any(), any())).willThrow(error); - ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( - conversionService); + ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class) - .isThrownBy(() -> mapper.mapParameterValue( - new TestOperationParameter(Integer.class), "123")) + .isThrownBy(() -> mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123")) .satisfies((ex) -> { assertThat(ex.getValue()).isEqualTo("123"); assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); @@ -73,8 +68,7 @@ public class ConversionServiceParameterValueMapperTests { @Test public void createShouldRegisterIsoOffsetDateTimeConverter() { ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(); - Object mapped = mapper.mapParameterValue( - new TestOperationParameter(OffsetDateTime.class), + Object mapped = mapper.mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00"); assertThat(mapped).isNotNull(); } @@ -82,11 +76,9 @@ public class ConversionServiceParameterValueMapperTests { @Test public void createWithConversionServiceShouldNotRegisterIsoOffsetDateTimeConverter() { ConversionService conversionService = new DefaultConversionService(); - ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( - conversionService); + ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class).isThrownBy(() -> mapper - .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), - "2011-12-03T10:15:30+01:00")); + .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00")); } private static class TestOperationParameter implements OperationParameter { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java index b3a223047b8..db508839652 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java @@ -42,8 +42,7 @@ public class IsoOffsetDateTimeConverterTests { public void registerConverterShouldRegister() { DefaultConversionService service = new DefaultConversionService(); IsoOffsetDateTimeConverter.registerConverter(service); - OffsetDateTime time = service.convert("2011-12-03T10:15:30+01:00", - OffsetDateTime.class); + OffsetDateTime time = service.convert("2011-12-03T10:15:30+01:00", OffsetDateTime.class); assertThat(time).isNotNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java index aea8f8c4e57..77999e76724 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java @@ -32,34 +32,29 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class OperationMethodParameterTests { - private Method method = ReflectionUtils.findMethod(getClass(), "example", - String.class, String.class); + private Method method = ReflectionUtils.findMethod(getClass(), "example", String.class, String.class); @Test public void getNameShouldReturnName() { - OperationMethodParameter parameter = new OperationMethodParameter("name", - this.method.getParameters()[0]); + OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.getName()).isEqualTo("name"); } @Test public void getTypeShouldReturnType() { - OperationMethodParameter parameter = new OperationMethodParameter("name", - this.method.getParameters()[0]); + OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.getType()).isEqualTo(String.class); } @Test public void isMandatoryWhenNoAnnotationShouldReturnTrue() { - OperationMethodParameter parameter = new OperationMethodParameter("name", - this.method.getParameters()[0]); + OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.isMandatory()).isTrue(); } @Test public void isMandatoryWhenNullableAnnotationShouldReturnFalse() { - OperationMethodParameter parameter = new OperationMethodParameter("name", - this.method.getParameters()[1]); + OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[1]); assertThat(parameter.isMandatory()).isFalse(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java index 112b7b070c6..6b78ba9a696 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java @@ -44,70 +44,65 @@ import static org.mockito.Mockito.mock; */ public class OperationMethodParametersTests { - private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", - String.class); + private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); - private Method exampleNoParamsMethod = ReflectionUtils.findMethod(getClass(), - "exampleNoParams"); + private Method exampleNoParamsMethod = ReflectionUtils.findMethod(getClass(), "exampleNoParams"); @Test public void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new OperationMethodParameters(null, - mock(ParameterNameDiscoverer.class))) + .isThrownBy(() -> new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class))) .withMessageContaining("Method must not be null"); } @Test public void createWhenParameterNameDiscovererIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, null)) .withMessageContaining("ParameterNameDiscoverer must not be null"); } @Test public void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, - mock(ParameterNameDiscoverer.class))) + .isThrownBy( + () -> new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class))) .withMessageContaining("Failed to extract parameter names"); } @Test public void hasParametersWhenHasParametersShouldReturnTrue() { - OperationMethodParameters parameters = new OperationMethodParameters( - this.exampleMethod, new DefaultParameterNameDiscoverer()); + OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, + new DefaultParameterNameDiscoverer()); assertThat(parameters.hasParameters()).isTrue(); } @Test public void hasParametersWhenHasNoParametersShouldReturnFalse() { - OperationMethodParameters parameters = new OperationMethodParameters( - this.exampleNoParamsMethod, new DefaultParameterNameDiscoverer()); + OperationMethodParameters parameters = new OperationMethodParameters(this.exampleNoParamsMethod, + new DefaultParameterNameDiscoverer()); assertThat(parameters.hasParameters()).isFalse(); } @Test public void getParameterCountShouldReturnParameterCount() { - OperationMethodParameters parameters = new OperationMethodParameters( - this.exampleMethod, new DefaultParameterNameDiscoverer()); + OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, + new DefaultParameterNameDiscoverer()); assertThat(parameters.getParameterCount()).isEqualTo(1); } @Test public void iteratorShouldIterateOperationParameters() { - OperationMethodParameters parameters = new OperationMethodParameters( - this.exampleMethod, new DefaultParameterNameDiscoverer()); + OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, + new DefaultParameterNameDiscoverer()); Iterator iterator = parameters.iterator(); - assertParameters(StreamSupport.stream( - Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), - false)); + assertParameters( + StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)); } @Test public void streamShouldStreamOperationParameters() { - OperationMethodParameters parameters = new OperationMethodParameters( - this.exampleMethod, new DefaultParameterNameDiscoverer()); + OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, + new DefaultParameterNameDiscoverer()); assertParameters(parameters.stream()); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java index 9f9d3b915b3..a41a4de1f0a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java @@ -34,41 +34,35 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException */ public class OperationMethodTests { - private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", - String.class); + private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); @Test public void createWhenMethodIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new OperationMethod(null, OperationType.READ)) + assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(null, OperationType.READ)) .withMessageContaining("Method must not be null"); } @Test public void createWhenOperationTypeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new OperationMethod(this.exampleMethod, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(this.exampleMethod, null)) .withMessageContaining("OperationType must not be null"); } @Test public void getMethodShouldReturnMethod() { - OperationMethod operationMethod = new OperationMethod(this.exampleMethod, - OperationType.READ); + OperationMethod operationMethod = new OperationMethod(this.exampleMethod, OperationType.READ); assertThat(operationMethod.getMethod()).isEqualTo(this.exampleMethod); } @Test public void getOperationTypeShouldReturnOperationType() { - OperationMethod operationMethod = new OperationMethod(this.exampleMethod, - OperationType.READ); + OperationMethod operationMethod = new OperationMethod(this.exampleMethod, OperationType.READ); assertThat(operationMethod.getOperationType()).isEqualTo(OperationType.READ); } @Test public void getParametersShouldReturnParameters() { - OperationMethod operationMethod = new OperationMethod(this.exampleMethod, - OperationType.READ); + OperationMethod operationMethod = new OperationMethod(this.exampleMethod, OperationType.READ); OperationParameters parameters = operationMethod.getParameters(); assertThat(parameters.getParameterCount()).isEqualTo(1); assertThat(parameters.iterator().next().getName()).isEqualTo("name"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java index 5bc70ef5e85..06072d5a1ef 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java @@ -50,72 +50,66 @@ public class ReflectiveOperationInvokerTests { @BeforeEach public void setup() { this.target = new Example(); - this.operationMethod = new OperationMethod( - ReflectionUtils.findMethod(Example.class, "reverse", String.class), + this.operationMethod = new OperationMethod(ReflectionUtils.findMethod(Example.class, "reverse", String.class), OperationType.READ); - this.parameterValueMapper = (parameter, value) -> (value != null) - ? value.toString() : null; + this.parameterValueMapper = (parameter, value) -> (value != null) ? value.toString() : null; } @Test public void createWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(null, - this.operationMethod, this.parameterValueMapper)) + .isThrownBy(() -> new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper)) .withMessageContaining("Target must not be null"); } @Test public void createWhenOperationMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, - this.parameterValueMapper)) + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper)) .withMessageContaining("OperationMethod must not be null"); } @Test public void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, - this.operationMethod, null)) + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, this.operationMethod, null)) .withMessageContaining("ParameterValueMapper must not be null"); } @Test public void invokeShouldInvokeMethod() { - ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, - this.operationMethod, this.parameterValueMapper); - Object result = invoker.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.singletonMap("name", "boot"))); + ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, + this.parameterValueMapper); + Object result = invoker + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", "boot"))); assertThat(result).isEqualTo("toob"); } @Test public void invokeWhenMissingNonNullableArgumentShouldThrowException() { - ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, - this.operationMethod, this.parameterValueMapper); - assertThatExceptionOfType(MissingParametersException.class).isThrownBy( - () -> invoker.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.singletonMap("name", null)))); + ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, + this.parameterValueMapper); + assertThatExceptionOfType(MissingParametersException.class).isThrownBy(() -> invoker + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null)))); } @Test public void invokeWhenMissingNullableArgumentShouldInvoke() { - OperationMethod operationMethod = new OperationMethod(ReflectionUtils.findMethod( - Example.class, "reverseNullable", String.class), OperationType.READ); - ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, - operationMethod, this.parameterValueMapper); - Object result = invoker.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.singletonMap("name", null))); + OperationMethod operationMethod = new OperationMethod( + ReflectionUtils.findMethod(Example.class, "reverseNullable", String.class), OperationType.READ); + ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, operationMethod, + this.parameterValueMapper); + Object result = invoker + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null))); assertThat(result).isEqualTo("llun"); } @Test public void invokeShouldResolveParameters() { - ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, - this.operationMethod, this.parameterValueMapper); - Object result = invoker.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.singletonMap("name", 1234))); + ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, + this.parameterValueMapper); + Object result = invoker + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", 1234))); assertThat(result).isEqualTo("4321"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java index f60b4a0ffdf..260a2988672 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java @@ -63,17 +63,16 @@ public class CachingOperationInvokerAdvisorTests { @Test public void applyWhenOperationIsNotReadShouldNotAddAdvise() { OperationParameters parameters = getParameters("get"); - OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), - OperationType.WRITE, parameters, this.invoker); + OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.WRITE, parameters, + this.invoker); assertThat(advised).isSameAs(this.invoker); } @Test public void applyWhenHasAtLeaseOneMandatoryParameterShouldNotAddAdvise() { - OperationParameters parameters = getParameters("getWithParameters", String.class, - String.class); - OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), - OperationType.READ, parameters, this.invoker); + OperationParameters parameters = getParameters("getWithParameters", String.class, String.class); + OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, + this.invoker); assertThat(advised).isSameAs(this.invoker); } @@ -81,8 +80,8 @@ public class CachingOperationInvokerAdvisorTests { public void applyWhenTimeToLiveReturnsNullShouldNotAddAdvise() { OperationParameters parameters = getParameters("get"); given(this.timeToLive.apply(any())).willReturn(null); - OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), - OperationType.READ, parameters, this.invoker); + OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, + this.invoker); assertThat(advised).isSameAs(this.invoker); verify(this.timeToLive).apply(EndpointId.of("foo")); } @@ -91,8 +90,8 @@ public class CachingOperationInvokerAdvisorTests { public void applyWhenTimeToLiveIsZeroShouldNotAddAdvise() { OperationParameters parameters = getParameters("get"); given(this.timeToLive.apply(any())).willReturn(0L); - OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), - OperationType.READ, parameters, this.invoker); + OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, + this.invoker); assertThat(advised).isSameAs(this.invoker); verify(this.timeToLive).apply(EndpointId.of("foo")); } @@ -106,37 +105,32 @@ public class CachingOperationInvokerAdvisorTests { @Test public void applyWithAllOptionalParametersShouldAddAdvise() { - OperationParameters parameters = getParameters("getWithAllOptionalParameters", - String.class, String.class); + OperationParameters parameters = getParameters("getWithAllOptionalParameters", String.class, String.class); given(this.timeToLive.apply(any())).willReturn(100L); assertAdviseIsApplied(parameters); } @Test public void applyWithSecurityContextShouldAddAdvise() { - OperationParameters parameters = getParameters("getWithSecurityContext", - SecurityContext.class, String.class); + OperationParameters parameters = getParameters("getWithSecurityContext", SecurityContext.class, String.class); given(this.timeToLive.apply(any())).willReturn(100L); assertAdviseIsApplied(parameters); } private void assertAdviseIsApplied(OperationParameters parameters) { - OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), - OperationType.READ, parameters, this.invoker); + OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, + this.invoker); assertThat(advised).isInstanceOf(CachingOperationInvoker.class); assertThat(advised).hasFieldOrPropertyWithValue("invoker", this.invoker); assertThat(advised).hasFieldOrPropertyWithValue("timeToLive", 100L); } - private OperationParameters getParameters(String methodName, - Class... parameterTypes) { + private OperationParameters getParameters(String methodName, Class... parameterTypes) { return getOperationMethod(methodName, parameterTypes).getParameters(); } - private OperationMethod getOperationMethod(String methodName, - Class... parameterTypes) { - Method method = ReflectionUtils.findMethod(TestOperations.class, methodName, - parameterTypes); + private OperationMethod getOperationMethod(String methodName, Class... parameterTypes) { + Method method = ReflectionUtils.findMethod(TestOperations.class, methodName, parameterTypes); return new OperationMethod(method, OperationType.READ); } @@ -150,13 +144,11 @@ public class CachingOperationInvokerAdvisorTests { return ""; } - public String getWithAllOptionalParameters(@Nullable String foo, - @Nullable String bar) { + public String getWithAllOptionalParameters(@Nullable String foo, @Nullable String bar) { return ""; } - public String getWithSecurityContext(SecurityContext securityContext, - @Nullable String bar) { + public String getWithSecurityContext(SecurityContext securityContext, @Nullable String bar) { return ""; } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java index 932106bcb0d..e1eeffbdd12 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java @@ -44,8 +44,8 @@ public class CachingOperationInvokerTests { @Test public void createInstanceWithTtlSetToZero() { - assertThatIllegalArgumentException().isThrownBy( - () -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) .withMessageContaining("TimeToLive"); } @@ -65,8 +65,7 @@ public class CachingOperationInvokerTests { private void assertCacheIsUsed(Map parameters) { OperationInvoker target = mock(OperationInvoker.class); Object expected = new Object(); - InvocationContext context = new InvocationContext(mock(SecurityContext.class), - parameters); + InvocationContext context = new InvocationContext(mock(SecurityContext.class), parameters); given(target.invoke(context)).willReturn(expected); CachingOperationInvoker invoker = new CachingOperationInvoker(target, 500L); Object response = invoker.invoke(context); @@ -83,8 +82,7 @@ public class CachingOperationInvokerTests { Map parameters = new HashMap<>(); parameters.put("test", "value"); parameters.put("something", null); - InvocationContext context = new InvocationContext(mock(SecurityContext.class), - parameters); + InvocationContext context = new InvocationContext(mock(SecurityContext.class), parameters); given(target.invoke(context)).willReturn(new Object()); CachingOperationInvoker invoker = new CachingOperationInvoker(target, 500L); invoker.invoke(context); @@ -112,8 +110,7 @@ public class CachingOperationInvokerTests { public void targetInvokedWhenCacheExpires() throws InterruptedException { OperationInvoker target = mock(OperationInvoker.class); Map parameters = new HashMap<>(); - InvocationContext context = new InvocationContext(mock(SecurityContext.class), - parameters); + InvocationContext context = new InvocationContext(mock(SecurityContext.class), parameters); given(target.invoke(context)).willReturn(new Object()); CachingOperationInvoker invoker = new CachingOperationInvoker(target, 50L); invoker.invoke(context); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java index 62e63aff66b..e90f62d6978 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java @@ -54,23 +54,21 @@ public class EndpointMBeanTests { private static final String[] NO_SIGNATURE = {}; - private TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( - new TestJmxOperation()); + private TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation()); private TestJmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); @Test public void createWhenResponseMapperIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) + assertThatIllegalArgumentException() + .isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) .withMessageContaining("ResponseMapper must not be null"); } @Test public void createWhenEndpointIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMBean( - mock(JmxOperationResponseMapper.class), null, null)) + .isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null)) .withMessageContaining("Endpoint must not be null"); } @@ -82,72 +80,59 @@ public class EndpointMBeanTests { } @Test - public void invokeShouldInvokeJmxOperation() - throws MBeanException, ReflectionException { + public void invokeShouldInvokeJmxOperation() throws MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); assertThat(result).isEqualTo("result"); } @Test - public void invokeWhenOperationFailedShouldTranslateException() - throws MBeanException, ReflectionException { - TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( - new TestJmxOperation((arguments) -> { - throw new FatalBeanException("test failure"); - })); + public void invokeWhenOperationFailedShouldTranslateException() throws MBeanException, ReflectionException { + TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation((arguments) -> { + throw new FatalBeanException("test failure"); + })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(MBeanException.class) .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(IllegalStateException.class) - .withMessageContaining("test failure"); + .withCauseInstanceOf(IllegalStateException.class).withMessageContaining("test failure"); } @Test public void invokeWhenOperationFailedWithJdkExceptionShouldReuseException() throws MBeanException, ReflectionException { - TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( - new TestJmxOperation((arguments) -> { - throw new UnsupportedOperationException("test failure"); - })); + TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation((arguments) -> { + throw new UnsupportedOperationException("test failure"); + })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(MBeanException.class) .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(UnsupportedOperationException.class) - .withMessageContaining("test failure"); + .withCauseInstanceOf(UnsupportedOperationException.class).withMessageContaining("test failure"); } @Test - public void invokeWhenActionNameIsNotAnOperationShouldThrowException() - throws MBeanException, ReflectionException { + public void invokeWhenActionNameIsNotAnOperationShouldThrowException() throws MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(ReflectionException.class) - .isThrownBy( - () -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) + .isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) .withCauseInstanceOf(IllegalArgumentException.class) .withMessageContaining("no operation named missingOperation"); } @Test - public void invokeShouldInvokeJmxOperationWithBeanClassLoader() - throws ReflectionException, MBeanException { + public void invokeShouldInvokeJmxOperationWithBeanClassLoader() throws ReflectionException, MBeanException { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( new TestJmxOperation((arguments) -> ClassUtils.getDefaultClassLoader())); - URLClassLoader beanClassLoader = new URLClassLoader(new URL[0], - getClass().getClassLoader()); - EndpointMBean bean = new EndpointMBean(this.responseMapper, beanClassLoader, - endpoint); + URLClassLoader beanClassLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); + EndpointMBean bean = new EndpointMBean(this.responseMapper, beanClassLoader, endpoint); Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); assertThat(result).isEqualTo(beanClassLoader); - assertThat(Thread.currentThread().getContextClassLoader()) - .isEqualTo(originalClassLoader); + assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(originalClassLoader); } @Test - public void invokeWhenOperationIsInvalidShouldThrowException() - throws MBeanException, ReflectionException { + public void invokeWhenOperationIsInvalidShouldThrowException() throws MBeanException, ReflectionException { TestJmxOperation operation = new TestJmxOperation() { @Override @@ -160,13 +145,11 @@ public class EndpointMBeanTests { EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(ReflectionException.class) .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withRootCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining("test failure"); + .withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining("test failure"); } @Test - public void invokeWhenMonoResultShouldBlockOnMono() - throws MBeanException, ReflectionException { + public void invokeWhenMonoResultShouldBlockOnMono() throws MBeanException, ReflectionException { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( new TestJmxOperation((arguments) -> Mono.just("monoResult"))); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); @@ -175,8 +158,7 @@ public class EndpointMBeanTests { } @Test - public void invokeShouldCallResponseMapper() - throws MBeanException, ReflectionException { + public void invokeShouldCallResponseMapper() throws MBeanException, ReflectionException { TestJmxOperationResponseMapper responseMapper = spy(this.responseMapper); EndpointMBean bean = new EndpointMBean(responseMapper, null, this.endpoint); bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); @@ -188,14 +170,13 @@ public class EndpointMBeanTests { public void getAttributeShouldThrowException() throws AttributeNotFoundException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); - assertThatExceptionOfType(AttributeNotFoundException.class) - .isThrownBy(() -> bean.getAttribute("test")) + assertThatExceptionOfType(AttributeNotFoundException.class).isThrownBy(() -> bean.getAttribute("test")) .withMessageContaining("EndpointMBeans do not support attributes"); } @Test - public void setAttributeShouldThrowException() throws AttributeNotFoundException, - InvalidAttributeValueException, MBeanException, ReflectionException { + public void setAttributeShouldThrowException() + throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class) .isThrownBy(() -> bean.setAttribute(new Attribute("test", "test"))) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java index 9010b846e08..52efb31eedd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java @@ -42,15 +42,13 @@ import static org.mockito.Mockito.verify; */ public class JacksonJmxOperationResponseMapperTests { - private JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper( - null); + private JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(null); private final BasicJsonTester json = new BasicJsonTester(getClass()); @Test public void createWhenObjectMapperIsNullShouldUseDefaultObjectMapper() { - JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper( - null); + JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(null); Object mapped = mapper.mapResponse(Collections.singleton("test")); assertThat(this.json.from(mapped.toString())).isEqualToJson("[test]"); } @@ -58,8 +56,7 @@ public class JacksonJmxOperationResponseMapperTests { @Test public void createWhenObjectMapperIsSpecifiedShouldUseObjectMapper() { ObjectMapper objectMapper = spy(ObjectMapper.class); - JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper( - objectMapper); + JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(objectMapper); Set response = Collections.singleton("test"); mapper.mapResponse(response); verify(objectMapper).convertValue(eq(response), any(JavaType.class)); @@ -68,8 +65,7 @@ public class JacksonJmxOperationResponseMapperTests { @Test public void mapResponseTypeWhenCharSequenceShouldReturnString() { assertThat(this.mapper.mapResponseType(String.class)).isEqualTo(String.class); - assertThat(this.mapper.mapResponseType(StringBuilder.class)) - .isEqualTo(String.class); + assertThat(this.mapper.mapResponseType(StringBuilder.class)).isEqualTo(String.class); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java index d22a9eeea62..01a1de77c44 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java @@ -56,8 +56,7 @@ public class JmxEndpointExporterTests { @Mock private MBeanServer mBeanServer; - private EndpointObjectNameFactory objectNameFactory = spy( - new TestEndpointObjectNameFactory()); + private EndpointObjectNameFactory objectNameFactory = spy(new TestEndpointObjectNameFactory()); private JmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); @@ -74,39 +73,36 @@ public class JmxEndpointExporterTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - this.exporter = new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, - this.responseMapper, this.endpoints); + this.exporter = new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, + this.endpoints); } @Test public void createWhenMBeanServerIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new JmxEndpointExporter(null, this.objectNameFactory, - this.responseMapper, this.endpoints)) + assertThatIllegalArgumentException().isThrownBy( + () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) .withMessageContaining("MBeanServer must not be null"); } @Test public void createWhenObjectNameFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, - this.responseMapper, this.endpoints)) + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) .withMessageContaining("ObjectNameFactory must not be null"); } @Test public void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, - this.objectNameFactory, null, this.endpoints)) + .isThrownBy( + () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) .withMessageContaining("ResponseMapper must not be null"); } @Test public void createWhenEndpointsIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, - this.objectNameFactory, this.responseMapper, null)) + assertThatIllegalArgumentException().isThrownBy( + () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) .withMessageContaining("Endpoints must not be null"); } @@ -114,11 +110,9 @@ public class JmxEndpointExporterTests { public void afterPropertiesSetShouldRegisterMBeans() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); - verify(this.mBeanServer).registerMBean(this.objectCaptor.capture(), - this.objectNameCaptor.capture()); + verify(this.mBeanServer).registerMBean(this.objectCaptor.capture(), this.objectNameCaptor.capture()); assertThat(this.objectCaptor.getValue()).isInstanceOf(EndpointMBean.class); - assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")) - .isEqualTo("test"); + assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test"); } @Test @@ -142,8 +136,7 @@ public class JmxEndpointExporterTests { given(this.mBeanServer.registerMBean(any(), any(ObjectName.class))) .willThrow(new MBeanRegistrationException(new RuntimeException())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); - assertThatExceptionOfType(MBeanExportException.class) - .isThrownBy(this.exporter::afterPropertiesSet) + assertThatExceptionOfType(MBeanExportException.class).isThrownBy(this.exporter::afterPropertiesSet) .withMessageContaining("Failed to register MBean for endpoint 'test"); } @@ -153,42 +146,35 @@ public class JmxEndpointExporterTests { this.exporter.afterPropertiesSet(); this.exporter.destroy(); verify(this.mBeanServer).unregisterMBean(this.objectNameCaptor.capture()); - assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")) - .isEqualTo("test"); + assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test"); } @Test public void unregisterWhenInstanceNotFoundShouldContinue() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); - willThrow(InstanceNotFoundException.class).given(this.mBeanServer) - .unregisterMBean(any(ObjectName.class)); + willThrow(InstanceNotFoundException.class).given(this.mBeanServer).unregisterMBean(any(ObjectName.class)); this.exporter.destroy(); } @Test - public void unregisterWhenUnregisterThrowsExceptionShouldThrowException() - throws Exception { + public void unregisterWhenUnregisterThrowsExceptionShouldThrowException() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); - willThrow(new MBeanRegistrationException(new RuntimeException())) - .given(this.mBeanServer).unregisterMBean(any(ObjectName.class)); - assertThatExceptionOfType(JmxException.class) - .isThrownBy(() -> this.exporter.destroy()).withMessageContaining( - "Failed to unregister MBean with ObjectName 'boot"); + willThrow(new MBeanRegistrationException(new RuntimeException())).given(this.mBeanServer) + .unregisterMBean(any(ObjectName.class)); + assertThatExceptionOfType(JmxException.class).isThrownBy(() -> this.exporter.destroy()) + .withMessageContaining("Failed to unregister MBean with ObjectName 'boot"); } /** * Test {@link EndpointObjectNameFactory}. */ - private static class TestEndpointObjectNameFactory - implements EndpointObjectNameFactory { + private static class TestEndpointObjectNameFactory implements EndpointObjectNameFactory { @Override - public ObjectName getObjectName(ExposableJmxEndpoint endpoint) - throws MalformedObjectNameException { - return (endpoint != null) ? new ObjectName( - "boot:type=Endpoint,name=" + endpoint.getEndpointId()) : null; + public ObjectName getObjectName(ExposableJmxEndpoint endpoint) throws MalformedObjectNameException { + return (endpoint != null) ? new ObjectName("boot:type=Endpoint,name=" + endpoint.getEndpointId()) : null; } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java index a260d4811f9..d40ae4b8dba 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java @@ -39,13 +39,11 @@ import static org.mockito.Mockito.mock; */ public class MBeanInfoFactoryTests { - private MBeanInfoFactory factory = new MBeanInfoFactory( - new TestJmxOperationResponseMapper()); + private MBeanInfoFactory factory = new MBeanInfoFactory(new TestJmxOperationResponseMapper()); @Test public void getMBeanInfoShouldReturnMBeanInfo() { - MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation())); + MBeanInfo info = this.factory.getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThat(info).isNotNull(); assertThat(info.getClassName()).isEqualTo(EndpointMBean.class.getName()); assertThat(info.getDescription()).isEqualTo("MBean operations for endpoint test"); @@ -62,26 +60,23 @@ public class MBeanInfoFactoryTests { @Test public void getMBeanInfoWhenReadOperationShouldHaveInfoImpact() { - MBeanInfo info = this.factory.getMBeanInfo( - new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); - assertThat(info.getOperations()[0].getImpact()) - .isEqualTo(MBeanOperationInfo.INFO); + MBeanInfo info = this.factory + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); + assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.INFO); } @Test public void getMBeanInfoWhenWriteOperationShouldHaveActionImpact() { - MBeanInfo info = this.factory.getMBeanInfo( - new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); - assertThat(info.getOperations()[0].getImpact()) - .isEqualTo(MBeanOperationInfo.ACTION); + MBeanInfo info = this.factory + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); + assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.ACTION); } @Test public void getMBeanInfoWhenDeleteOperationShouldHaveActionImpact() { - MBeanInfo info = this.factory.getMBeanInfo( - new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); - assertThat(info.getOperations()[0].getImpact()) - .isEqualTo(MBeanOperationInfo.ACTION); + MBeanInfo info = this.factory + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); + assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.ACTION); } @Test @@ -90,8 +85,7 @@ public class MBeanInfoFactoryTests { JmxOperationResponseMapper mapper = mock(JmxOperationResponseMapper.class); given(mapper.mapResponseType(String.class)).willReturn((Class) Integer.class); MBeanInfoFactory factory = new MBeanInfoFactory(mapper); - MBeanInfo info = factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation())); + MBeanInfo info = factory.getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation())); MBeanOperationInfo operationInfo = info.getOperations()[0]; assertThat(operationInfo.getReturnType()).isEqualTo(Integer.class.getName()); } @@ -102,8 +96,7 @@ public class MBeanInfoFactoryTests { parameters.add(mockParameter("one", String.class, "myone")); parameters.add(mockParameter("two", Object.class, null)); TestJmxOperation operation = new TestJmxOperation(parameters); - MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(operation)); + MBeanInfo info = this.factory.getMBeanInfo(new TestExposableJmxEndpoint(operation)); MBeanOperationInfo operationInfo = info.getOperations()[0]; MBeanParameterInfo[] signature = operationInfo.getSignature(); assertThat(signature).hasSize(2); @@ -116,8 +109,7 @@ public class MBeanInfoFactoryTests { } @SuppressWarnings({ "unchecked", "rawtypes" }) - private JmxOperationParameter mockParameter(String name, Class type, - String description) { + private JmxOperationParameter mockParameter(String name, Class type, String description) { JmxOperationParameter parameter = mock(JmxOperationParameter.class); given(parameter.getName()).willReturn(name); given(parameter.getType()).willReturn((Class) type); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestJmxOperation.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestJmxOperation.java index a7f0a57a099..8d7189df1c2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestJmxOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestJmxOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,7 @@ public class TestJmxOperation implements JmxOperation { @Override public Object invoke(InvocationContext context) { - return (this.invoke != null) ? this.invoke.apply(context.getArguments()) - : "result"; + return (this.invoke != null) ? this.invoke.apply(context.getArguments()) : "result"; } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java index 9db087046ab..d32b03c78ab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java @@ -60,22 +60,19 @@ public class DiscoveredJmxOperationTests { assertThat(getOperation("getInstant").getOutputType()).isEqualTo(String.class); assertThat(getOperation("getInteger").getOutputType()).isEqualTo(Integer.class); assertThat(getOperation("getVoid").getOutputType()).isEqualTo(void.class); - assertThat(getOperation("getApplicationContext").getOutputType()) - .isEqualTo(Object.class); + assertThat(getOperation("getApplicationContext").getOutputType()).isEqualTo(Object.class); } @Test public void getDescriptionWhenHasManagedOperationDescriptionShouldUseValueFromAnnotation() { - DiscoveredJmxOperation operation = getOperation( - "withManagedOperationDescription"); + DiscoveredJmxOperation operation = getOperation("withManagedOperationDescription"); assertThat(operation.getDescription()).isEqualTo("fromannotation"); } @Test public void getDescriptionWhenHasNoManagedOperationShouldGenerateDescription() { DiscoveredJmxOperation operation = getOperation("getEnum"); - assertThat(operation.getDescription()) - .isEqualTo("Invoke getEnum for endpoint test"); + assertThat(operation.getDescription()).isEqualTo("Invoke getEnum for endpoint test"); } @Test @@ -125,17 +122,16 @@ public class DiscoveredJmxOperationTests { Method method = findMethod(methodName); AnnotationAttributes annotationAttributes = new AnnotationAttributes(); annotationAttributes.put("produces", "application/xml"); - DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, - OperationType.READ, annotationAttributes); - DiscoveredJmxOperation operation = new DiscoveredJmxOperation( - EndpointId.of("test"), operationMethod, mock(OperationInvoker.class)); + DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, OperationType.READ, + annotationAttributes); + DiscoveredJmxOperation operation = new DiscoveredJmxOperation(EndpointId.of("test"), operationMethod, + mock(OperationInvoker.class)); return operation; } private Method findMethod(String methodName) { Map methods = new HashMap<>(); - ReflectionUtils.doWithMethods(Example.class, - (method) -> methods.put(method.getName(), method)); + ReflectionUtils.doWithMethods(Example.class, (method) -> methods.put(method.getName(), method)); return methods.get(methodName); } @@ -153,14 +149,13 @@ public class DiscoveredJmxOperationTests { ApplicationContext getApplicationContext(); - Object params(OperationType enumParam, Date dateParam, Instant instantParam, - Integer integerParam, ApplicationContext applicationContextParam); + Object params(OperationType enumParam, Date dateParam, Instant instantParam, Integer integerParam, + ApplicationContext applicationContextParam); @ManagedOperation(description = "fromannotation") Object withManagedOperationDescription(); - @ManagedOperationParameters({ - @ManagedOperationParameter(name = "a1", description = "d1"), + @ManagedOperationParameters({ @ManagedOperationParameter(name = "a1", description = "d1"), @ManagedOperationParameter(name = "a2", description = "d2") }) Object withManagedOperationParameters(Object one, Object two); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java index 8070c54c340..82e755eda09 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java @@ -60,8 +60,7 @@ public class JmxEndpointDiscovererTests { @Test public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { - load(EmptyConfiguration.class, - (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty()); + load(EmptyConfiguration.class, (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty()); } @Test @@ -71,29 +70,24 @@ public class JmxEndpointDiscovererTests { assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operationByName = mapOperations( endpoints.get(EndpointId.of("test")).getOperations()); - assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", - "update", "deleteSomething"); + assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", "update", "deleteSomething"); JmxOperation getAll = operationByName.get("getAll"); - assertThat(getAll.getDescription()) - .isEqualTo("Invoke getAll for endpoint test"); + assertThat(getAll.getDescription()).isEqualTo("Invoke getAll for endpoint test"); assertThat(getAll.getOutputType()).isEqualTo(Object.class); assertThat(getAll.getParameters()).isEmpty(); JmxOperation getSomething = operationByName.get("getSomething"); - assertThat(getSomething.getDescription()) - .isEqualTo("Invoke getSomething for endpoint test"); + assertThat(getSomething.getDescription()).isEqualTo("Invoke getSomething for endpoint test"); assertThat(getSomething.getOutputType()).isEqualTo(String.class); assertThat(getSomething.getParameters()).hasSize(1); hasDefaultParameter(getSomething, 0, String.class); JmxOperation update = operationByName.get("update"); - assertThat(update.getDescription()) - .isEqualTo("Invoke update for endpoint test"); + assertThat(update.getDescription()).isEqualTo("Invoke update for endpoint test"); assertThat(update.getOutputType()).isEqualTo(Void.TYPE); assertThat(update.getParameters()).hasSize(2); hasDefaultParameter(update, 0, String.class); hasDefaultParameter(update, 1, String.class); JmxOperation deleteSomething = operationByName.get("deleteSomething"); - assertThat(deleteSomething.getDescription()) - .isEqualTo("Invoke deleteSomething for endpoint test"); + assertThat(deleteSomething.getDescription()).isEqualTo("Invoke deleteSomething for endpoint test"); assertThat(deleteSomething.getOutputType()).isEqualTo(Void.TYPE); assertThat(deleteSomething.getParameters()).hasSize(1); hasDefaultParameter(deleteSomething, 0, String.class); @@ -104,17 +98,15 @@ public class JmxEndpointDiscovererTests { public void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverJmxEndpoints() { load(MultipleEndpointsConfiguration.class, (discoverer) -> { Map endpoints = discover(discoverer); - assertThat(endpoints).containsOnlyKeys(EndpointId.of("test"), - EndpointId.of("jmx")); + assertThat(endpoints).containsOnlyKeys(EndpointId.of("test"), EndpointId.of("jmx")); }); } @Test public void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { - load(TestJmxEndpointExtension.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); + load(TestJmxEndpointExtension.class, (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); } @Test @@ -133,8 +125,8 @@ public class JmxEndpointDiscovererTests { assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operationByName = mapOperations( endpoints.get(EndpointId.of("test")).getOperations()); - assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", - "update", "deleteSomething", "getAnother"); + assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", "update", "deleteSomething", + "getAnother"); JmxOperation getAnother = operationByName.get("getAnother"); assertThat(getAnother.getDescription()).isEqualTo("Get another thing"); assertThat(getAnother.getOutputType()).isEqualTo(Object.class); @@ -149,77 +141,64 @@ public class JmxEndpointDiscovererTests { assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operationByName = mapOperations( endpoints.get(EndpointId.of("test")).getOperations()); - assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", - "update", "deleteSomething"); + assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", "update", "deleteSomething"); JmxOperation getAll = operationByName.get("getAll"); assertThat(getInvoker(getAll)).isInstanceOf(CachingOperationInvoker.class); - assertThat(((CachingOperationInvoker) getInvoker(getAll)).getTimeToLive()) - .isEqualTo(500); + assertThat(((CachingOperationInvoker) getInvoker(getAll)).getTimeToLive()).isEqualTo(500); }); } @Test public void getEndpointsShouldCacheReadOperations() { - load(AdditionalOperationJmxEndpointConfiguration.class, (id) -> 500L, - (discoverer) -> { - Map endpoints = discover( - discoverer); - assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - Map operationByName = mapOperations( - endpoints.get(EndpointId.of("test")).getOperations()); - assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", - "update", "deleteSomething", "getAnother"); - JmxOperation getAll = operationByName.get("getAll"); - assertThat(getInvoker(getAll)) - .isInstanceOf(CachingOperationInvoker.class); - assertThat(((CachingOperationInvoker) getInvoker(getAll)) - .getTimeToLive()).isEqualTo(500); - JmxOperation getAnother = operationByName.get("getAnother"); - assertThat(getInvoker(getAnother)) - .isInstanceOf(CachingOperationInvoker.class); - assertThat(((CachingOperationInvoker) getInvoker(getAnother)) - .getTimeToLive()).isEqualTo(500); - }); + load(AdditionalOperationJmxEndpointConfiguration.class, (id) -> 500L, (discoverer) -> { + Map endpoints = discover(discoverer); + assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); + Map operationByName = mapOperations( + endpoints.get(EndpointId.of("test")).getOperations()); + assertThat(operationByName).containsOnlyKeys("getAll", "getSomething", "update", "deleteSomething", + "getAnother"); + JmxOperation getAll = operationByName.get("getAll"); + assertThat(getInvoker(getAll)).isInstanceOf(CachingOperationInvoker.class); + assertThat(((CachingOperationInvoker) getInvoker(getAll)).getTimeToLive()).isEqualTo(500); + JmxOperation getAnother = operationByName.get("getAnother"); + assertThat(getInvoker(getAnother)).isInstanceOf(CachingOperationInvoker.class); + assertThat(((CachingOperationInvoker) getInvoker(getAnother)).getTimeToLive()).isEqualTo(500); + }); } @Test public void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { - load(ClashingJmxEndpointConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); + load(ClashingJmxEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test public void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Found two endpoints with the id 'test': ")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { - load(ClashingOperationsEndpoint.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); + load(ClashingOperationsEndpoint.class, (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); } @Test public void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { - load(AdditionalClashingOperationsConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); + load(AdditionalClashingOperationsConfiguration.class, (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); } @Test public void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { - load(InvalidJmxExtensionConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); + load(InvalidJmxExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); } private Object getInvoker(JmxOperation operation) { @@ -227,21 +206,17 @@ public class JmxEndpointDiscovererTests { } private void assertJmxTestEndpoint(ExposableJmxEndpoint endpoint) { - Map operationsByName = mapOperations( - endpoint.getOperations()); - assertThat(operationsByName).containsOnlyKeys("getAll", "getSomething", "update", - "deleteSomething"); + Map operationsByName = mapOperations(endpoint.getOperations()); + assertThat(operationsByName).containsOnlyKeys("getAll", "getSomething", "update", "deleteSomething"); JmxOperation getAll = operationsByName.get("getAll"); assertThat(getAll.getDescription()).isEqualTo("Get all the things"); assertThat(getAll.getOutputType()).isEqualTo(Object.class); assertThat(getAll.getParameters()).isEmpty(); JmxOperation getSomething = operationsByName.get("getSomething"); - assertThat(getSomething.getDescription()) - .isEqualTo("Get something based on a timeUnit"); + assertThat(getSomething.getDescription()).isEqualTo("Get something based on a timeUnit"); assertThat(getSomething.getOutputType()).isEqualTo(String.class); assertThat(getSomething.getParameters()).hasSize(1); - hasDocumentedParameter(getSomething, 0, "unitMs", Long.class, - "Number of milliseconds"); + hasDocumentedParameter(getSomething, 0, "unitMs", Long.class, "Number of milliseconds"); JmxOperation update = operationsByName.get("update"); assertThat(update.getDescription()).isEqualTo("Update something based on bar"); assertThat(update.getOutputType()).isEqualTo(Void.TYPE); @@ -249,16 +224,14 @@ public class JmxEndpointDiscovererTests { hasDocumentedParameter(update, 0, "foo", String.class, "Foo identifier"); hasDocumentedParameter(update, 1, "bar", String.class, "Bar value"); JmxOperation deleteSomething = operationsByName.get("deleteSomething"); - assertThat(deleteSomething.getDescription()) - .isEqualTo("Delete something based on a timeUnit"); + assertThat(deleteSomething.getDescription()).isEqualTo("Delete something based on a timeUnit"); assertThat(deleteSomething.getOutputType()).isEqualTo(Void.TYPE); assertThat(deleteSomething.getParameters()).hasSize(1); - hasDocumentedParameter(deleteSomething, 0, "unitMs", Long.class, - "Number of milliseconds"); + hasDocumentedParameter(deleteSomething, 0, "unitMs", Long.class, "Number of milliseconds"); } - private void hasDocumentedParameter(JmxOperation operation, int index, String name, - Class type, String description) { + private void hasDocumentedParameter(JmxOperation operation, int index, String name, Class type, + String description) { assertThat(index).isLessThan(operation.getParameters().size()); JmxOperationParameter parameter = operation.getParameters().get(index); assertThat(parameter.getName()).isEqualTo(name); @@ -272,11 +245,9 @@ public class JmxEndpointDiscovererTests { assertThat(parameter.getType()).isEqualTo(type); } - private Map discover( - JmxEndpointDiscoverer discoverer) { + private Map discover(JmxEndpointDiscoverer discoverer) { Map byId = new HashMap<>(); - discoverer.getEndpoints() - .forEach((endpoint) -> byId.put(endpoint.getEndpointId(), endpoint)); + discoverer.getEndpoints().forEach((endpoint) -> byId.put(endpoint.getEndpointId(), endpoint)); return byId; } @@ -292,14 +263,11 @@ public class JmxEndpointDiscovererTests { private void load(Class configuration, Function timeToLive, Consumer consumer) { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - configuration)) { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { ConversionServiceParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - JmxEndpointDiscoverer discoverer = new JmxEndpointDiscoverer(context, - parameterMapper, - Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), - Collections.emptyList()); + JmxEndpointDiscoverer discoverer = new JmxEndpointDiscoverer(context, parameterMapper, + Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), Collections.emptyList()); consumer.accept(discoverer); } } @@ -470,16 +438,15 @@ public class JmxEndpointDiscovererTests { @ReadOperation @ManagedOperation(description = "Get something based on a timeUnit") - @ManagedOperationParameters({ @ManagedOperationParameter(name = "unitMs", - description = "Number of milliseconds") }) + @ManagedOperationParameters({ + @ManagedOperationParameter(name = "unitMs", description = "Number of milliseconds") }) public String getSomething(Long timeUnit) { return null; } @WriteOperation @ManagedOperation(description = "Update something based on bar") - @ManagedOperationParameters({ - @ManagedOperationParameter(name = "foo", description = "Foo identifier"), + @ManagedOperationParameters({ @ManagedOperationParameter(name = "foo", description = "Foo identifier"), @ManagedOperationParameter(name = "bar", description = "Bar value") }) public void update(String foo, String bar) { @@ -487,8 +454,8 @@ public class JmxEndpointDiscovererTests { @DeleteOperation @ManagedOperation(description = "Delete something based on a timeUnit") - @ManagedOperationParameters({ @ManagedOperationParameter(name = "unitMs", - description = "Number of milliseconds") }) + @ManagedOperationParameters({ + @ManagedOperationParameter(name = "unitMs", description = "Number of milliseconds") }) public void deleteSomething(Long timeUnit) { } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java index c54ffa829e1..1e856eed439 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java @@ -44,8 +44,7 @@ public class EndpointLinksResolverTests { Map links = new EndpointLinksResolver(Collections.emptyList()) .resolveLinks("https://api.example.com/actuator/"); assertThat(links).hasSize(1); - assertThat(links).hasEntrySatisfying("self", - linkWithHref("https://api.example.com/actuator")); + assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); } @Test @@ -53,8 +52,7 @@ public class EndpointLinksResolverTests { Map links = new EndpointLinksResolver(Collections.emptyList()) .resolveLinks("https://api.example.com/actuator"); assertThat(links).hasSize(1); - assertThat(links).hasEntrySatisfying("self", - linkWithHref("https://api.example.com/actuator")); + assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); } @Test @@ -67,13 +65,11 @@ public class EndpointLinksResolverTests { given(endpoint.isEnableByDefault()).willReturn(true); given(endpoint.getOperations()).willReturn(operations); String requestUrl = "https://api.example.com/actuator"; - Map links = new EndpointLinksResolver( - Collections.singletonList(endpoint)).resolveLinks(requestUrl); + Map links = new EndpointLinksResolver(Collections.singletonList(endpoint)) + .resolveLinks(requestUrl); assertThat(links).hasSize(3); - assertThat(links).hasEntrySatisfying("self", - linkWithHref("https://api.example.com/actuator")); - assertThat(links).hasEntrySatisfying("alpha", - linkWithHref("https://api.example.com/actuator/alpha")); + assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); + assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); assertThat(links).hasEntrySatisfying("alpha-name", linkWithHref("https://api.example.com/actuator/alpha/{name}")); } @@ -85,36 +81,30 @@ public class EndpointLinksResolverTests { given(servletEndpoint.isEnableByDefault()).willReturn(true); given(servletEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; - Map links = new EndpointLinksResolver( - Collections.singletonList(servletEndpoint)).resolveLinks(requestUrl); + Map links = new EndpointLinksResolver(Collections.singletonList(servletEndpoint)) + .resolveLinks(requestUrl); assertThat(links).hasSize(2); - assertThat(links).hasEntrySatisfying("self", - linkWithHref("https://api.example.com/actuator")); - assertThat(links).hasEntrySatisfying("alpha", - linkWithHref("https://api.example.com/actuator/alpha")); + assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); + assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); } @Test public void resolvedLinksContainsALinkForControllerEndpoint() { - ExposableControllerEndpoint controllerEndpoint = mock( - ExposableControllerEndpoint.class); + ExposableControllerEndpoint controllerEndpoint = mock(ExposableControllerEndpoint.class); given(controllerEndpoint.getEndpointId()).willReturn(EndpointId.of("alpha")); given(controllerEndpoint.isEnableByDefault()).willReturn(true); given(controllerEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; - Map links = new EndpointLinksResolver( - Collections.singletonList(controllerEndpoint)).resolveLinks(requestUrl); + Map links = new EndpointLinksResolver(Collections.singletonList(controllerEndpoint)) + .resolveLinks(requestUrl); assertThat(links).hasSize(2); - assertThat(links).hasEntrySatisfying("self", - linkWithHref("https://api.example.com/actuator")); - assertThat(links).hasEntrySatisfying("alpha", - linkWithHref("https://api.example.com/actuator/alpha")); + assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); + assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); } private WebOperation operationWithPath(String path, String id) { - WebOperationRequestPredicate predicate = new WebOperationRequestPredicate(path, - WebEndpointHttpMethod.GET, Collections.emptyList(), - Collections.emptyList()); + WebOperationRequestPredicate predicate = new WebOperationRequestPredicate(path, WebEndpointHttpMethod.GET, + Collections.emptyList(), Collections.emptyList()); WebOperation operation = mock(WebOperation.class); given(operation.getId()).willReturn(id); given(operation.getType()).willReturn(OperationType.READ); @@ -123,8 +113,7 @@ public class EndpointLinksResolverTests { } private Condition linkWithHref(String href) { - return new Condition<>((link) -> href.equals(link.getHref()), - "Link with href '%s'", href); + return new Condition<>((link) -> href.equals(link.getHref()), "Link with href '%s'", href); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java index cfc17ae6928..266f6bf7b62 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java @@ -64,20 +64,17 @@ public class EndpointMappingTests { @Test public void subPathWithALeadingSlashIsSeparatedFromBasePathBySingleSlash() { - assertThat(new EndpointMapping("/test").createSubPath("/one")) - .isEqualTo("/test/one"); + assertThat(new EndpointMapping("/test").createSubPath("/one")).isEqualTo("/test/one"); } @Test public void subPathWithoutALeadingSlashIsSeparatedFromBasePathBySingleSlash() { - assertThat(new EndpointMapping("/test").createSubPath("one")) - .isEqualTo("/test/one"); + assertThat(new EndpointMapping("/test").createSubPath("one")).isEqualTo("/test/one"); } @Test public void trailingSlashIsRemovedFromASubPath() { - assertThat(new EndpointMapping("/test").createSubPath("one/")) - .isEqualTo("/test/one"); + assertThat(new EndpointMapping("/test").createSubPath("one/")).isEqualTo("/test/one"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java index 4a8682162ef..baad9ade1ee 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java @@ -34,31 +34,27 @@ public class EndpointMediaTypesTests { @Test public void createWhenProducedIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMediaTypes(null, Collections.emptyList())) + assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(null, Collections.emptyList())) .withMessageContaining("Produced must not be null"); } @Test public void createWhenConsumedIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMediaTypes(Collections.emptyList(), null)) + assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(Collections.emptyList(), null)) .withMessageContaining("Consumed must not be null"); } @Test public void getProducedShouldReturnProduced() { List produced = Arrays.asList("a", "b", "c"); - EndpointMediaTypes types = new EndpointMediaTypes(produced, - Collections.emptyList()); + EndpointMediaTypes types = new EndpointMediaTypes(produced, Collections.emptyList()); assertThat(types.getProduced()).isEqualTo(produced); } @Test public void getConsumedShouldReturnConsumed() { List consumed = Arrays.asList("a", "b", "c"); - EndpointMediaTypes types = new EndpointMediaTypes(Collections.emptyList(), - consumed); + EndpointMediaTypes types = new EndpointMediaTypes(Collections.emptyList(), consumed); assertThat(types.getConsumed()).isEqualTo(consumed); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java index 37b8073b674..791fe23e5ca 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java @@ -41,15 +41,13 @@ public class EndpointServletTests { @Test public void createWhenServletClassIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointServlet((Class) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Class) null)) .withMessageContaining("Servlet must not be null"); } @Test public void createWhenServletIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointServlet((Servlet) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Servlet) null)) .withMessageContaining("Servlet must not be null"); } @@ -69,64 +67,59 @@ public class EndpointServletTests { @Test public void withInitParameterNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - assertThatIllegalArgumentException() - .isThrownBy(() -> endpointServlet.withInitParameter(null, "value")); + assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet.withInitParameter(null, "value")); } @Test public void withInitParameterEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - assertThatIllegalArgumentException() - .isThrownBy(() -> endpointServlet.withInitParameter(" ", "value")); + assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet.withInitParameter(" ", "value")); } @Test public void withInitParameterShouldReturnNewInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - assertThat(endpointServlet.withInitParameter("spring", "boot")) - .isNotSameAs(endpointServlet); + assertThat(endpointServlet.withInitParameter("spring", "boot")).isNotSameAs(endpointServlet); } @Test public void withInitParameterWhenHasExistingShouldMergeParameters() { - EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class) - .withInitParameter("a", "b").withInitParameter("c", "d"); - assertThat(endpointServlet.withInitParameter("a", "b1") - .withInitParameter("e", "f").getInitParameters()).containsExactly( - entry("a", "b1"), entry("c", "d"), entry("e", "f")); + EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") + .withInitParameter("c", "d"); + assertThat(endpointServlet.withInitParameter("a", "b1").withInitParameter("e", "f").getInitParameters()) + .containsExactly(entry("a", "b1"), entry("c", "d"), entry("e", "f")); } @Test public void withInitParametersNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet - .withInitParameters(Collections.singletonMap(null, "value"))); + assertThatIllegalArgumentException() + .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(null, "value"))); } @Test public void withInitParametersEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet - .withInitParameters(Collections.singletonMap(" ", "value"))); + assertThatIllegalArgumentException() + .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(" ", "value"))); } @Test public void withInitParametersShouldCreateNewInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - assertThat(endpointServlet - .withInitParameters(Collections.singletonMap("spring", "boot"))) - .isNotSameAs(endpointServlet); + assertThat(endpointServlet.withInitParameters(Collections.singletonMap("spring", "boot"))) + .isNotSameAs(endpointServlet); } @Test public void withInitParametersWhenHasExistingShouldMergeParameters() { - EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class) - .withInitParameter("a", "b").withInitParameter("c", "d"); + EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") + .withInitParameter("c", "d"); Map extra = new LinkedHashMap<>(); extra.put("a", "b1"); extra.put("e", "f"); - assertThat(endpointServlet.withInitParameters(extra).getInitParameters()) - .containsExactly(entry("a", "b1"), entry("c", "d"), entry("e", "f")); + assertThat(endpointServlet.withInitParameters(extra).getInitParameters()).containsExactly(entry("a", "b1"), + entry("c", "d"), entry("e", "f")); } @Test @@ -137,8 +130,7 @@ public class EndpointServletTests { @Test public void withLoadOnStartupSetShouldReturnValue() { - EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class) - .withLoadOnStartup(3); + EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withLoadOnStartup(3); assertThat(endpointServlet.getLoadOnStartup()).isEqualTo(3); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java index 2038acf2ea7..599af2bc88b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java @@ -42,16 +42,14 @@ public class PathMappedEndpointsTests { @Test public void createWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) + .isThrownBy(() -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) .withMessageContaining("Supplier must not be null"); } @Test public void createWhenSuppliersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PathMappedEndpoints(null, - (Collection>) null)) + .isThrownBy(() -> new PathMappedEndpoints(null, (Collection>) null)) .withMessageContaining("Suppliers must not be null"); } @@ -59,16 +57,14 @@ public class PathMappedEndpointsTests { public void iteratorShouldReturnPathMappedEndpoints() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped).hasSize(2); - assertThat(mapped).extracting("endpointId").containsExactly(EndpointId.of("e2"), - EndpointId.of("e3")); + assertThat(mapped).extracting("endpointId").containsExactly(EndpointId.of("e2"), EndpointId.of("e3")); } @Test public void streamShouldReturnPathMappedEndpoints() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.stream()).hasSize(2); - assertThat(mapped.stream()).extracting("endpointId") - .containsExactly(EndpointId.of("e2"), EndpointId.of("e3")); + assertThat(mapped.stream()).extracting("endpointId").containsExactly(EndpointId.of("e2"), EndpointId.of("e3")); } @Test @@ -86,8 +82,7 @@ public class PathMappedEndpointsTests { @Test public void getPathWhenContainsIdShouldReturnRootPath() { assertThat(createTestMapped(null).getPath(EndpointId.of("e2"))).isEqualTo("/p2"); - assertThat(createTestMapped("/x").getPath(EndpointId.of("e2"))) - .isEqualTo("/x/p2"); + assertThat(createTestMapped("/x").getPath(EndpointId.of("e2"))).isEqualTo("/x/p2"); } @Test @@ -105,8 +100,7 @@ public class PathMappedEndpointsTests { @Test public void getAllPathsShouldReturnAllPaths() { assertThat(createTestMapped(null).getAllPaths()).containsExactly("/p2", "/p3"); - assertThat(createTestMapped("/x").getAllPaths()).containsExactly("/x/p2", - "/x/p3"); + assertThat(createTestMapped("/x").getAllPaths()).containsExactly("/x/p2", "/x/p3"); } @Test @@ -147,8 +141,7 @@ public class PathMappedEndpointsTests { } - interface TestPathMappedEndpoint - extends ExposableEndpoint, PathMappedEndpoint { + interface TestPathMappedEndpoint extends ExposableEndpoint, PathMappedEndpoint { } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java index c99e613985e..16fde1aa4f4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java @@ -63,14 +63,12 @@ public class ServletEndpointRegistrarTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - given(this.servletContext.addServlet(any(String.class), any(Servlet.class))) - .willReturn(this.dynamic); + given(this.servletContext.addServlet(any(String.class), any(Servlet.class))).willReturn(this.dynamic); } @Test public void createWhenServletEndpointsIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ServletEndpointRegistrar(null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ServletEndpointRegistrar(null, null)) .withMessageContaining("ServletEndpoints must not be null"); } @@ -85,59 +83,45 @@ public class ServletEndpointRegistrarTests { } @Test - public void onStartupWhenHasEmptyBasePathShouldPrefixWithSlash() - throws ServletException { + public void onStartupWhenHasEmptyBasePathShouldPrefixWithSlash() throws ServletException { assertBasePath("", "/test/*"); } @Test - public void onStartupWhenHasRootBasePathShouldNotAddDuplicateSlash() - throws ServletException { + public void onStartupWhenHasRootBasePathShouldNotAddDuplicateSlash() throws ServletException { assertBasePath("/", "/test/*"); } - private void assertBasePath(String basePath, String expectedMapping) - throws ServletException { - ExposableServletEndpoint endpoint = mockEndpoint( - new EndpointServlet(TestServlet.class)); - ServletEndpointRegistrar registrar = new ServletEndpointRegistrar(basePath, - Collections.singleton(endpoint)); + private void assertBasePath(String basePath, String expectedMapping) throws ServletException { + ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class)); + ServletEndpointRegistrar registrar = new ServletEndpointRegistrar(basePath, Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); - verify(this.servletContext).addServlet(eq("test-actuator-endpoint"), - this.servlet.capture()); + verify(this.servletContext).addServlet(eq("test-actuator-endpoint"), this.servlet.capture()); assertThat(this.servlet.getValue()).isInstanceOf(TestServlet.class); verify(this.dynamic).addMapping(expectedMapping); } @Test - public void onStartupWhenHasInitParametersShouldRegisterInitParameters() - throws Exception { + public void onStartupWhenHasInitParametersShouldRegisterInitParameters() throws Exception { ExposableServletEndpoint endpoint = mockEndpoint( new EndpointServlet(TestServlet.class).withInitParameter("a", "b")); - ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", - Collections.singleton(endpoint)); + ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); verify(this.dynamic).setInitParameters(Collections.singletonMap("a", "b")); } @Test - public void onStartupWhenHasLoadOnStartupShouldRegisterLoadOnStartup() - throws Exception { - ExposableServletEndpoint endpoint = mockEndpoint( - new EndpointServlet(TestServlet.class).withLoadOnStartup(7)); - ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", - Collections.singleton(endpoint)); + public void onStartupWhenHasLoadOnStartupShouldRegisterLoadOnStartup() throws Exception { + ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class).withLoadOnStartup(7)); + ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); verify(this.dynamic).setLoadOnStartup(7); } @Test - public void onStartupWhenHasNotLoadOnStartupShouldRegisterDefaultValue() - throws Exception { - ExposableServletEndpoint endpoint = mockEndpoint( - new EndpointServlet(TestServlet.class)); - ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", - Collections.singleton(endpoint)); + public void onStartupWhenHasNotLoadOnStartupShouldRegisterDefaultValue() throws Exception { + ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class)); + ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); verify(this.dynamic).setLoadOnStartup(-1); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java index af37546978f..06a819afa90 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java @@ -41,20 +41,17 @@ public class WebOperationRequestPredicateTests { @Test public void predicatesWithIdenticalPathsWithVariablesAreEqual() { - assertThat(predicateWithPath("/path/{foo}")) - .isEqualTo(predicateWithPath("/path/{foo}")); + assertThat(predicateWithPath("/path/{foo}")).isEqualTo(predicateWithPath("/path/{foo}")); } @Test public void predicatesWhereOneHasAPathAndTheOtherHasAVariableAreNotEqual() { - assertThat(predicateWithPath("/path/{foo}")) - .isNotEqualTo(predicateWithPath("/path/foo")); + assertThat(predicateWithPath("/path/{foo}")).isNotEqualTo(predicateWithPath("/path/foo")); } @Test public void predicatesWithSinglePathVariablesInTheSamplePlaceAreEqual() { - assertThat(predicateWithPath("/path/{foo1}")) - .isEqualTo(predicateWithPath("/path/{foo2}")); + assertThat(predicateWithPath("/path/{foo1}")).isEqualTo(predicateWithPath("/path/{foo2}")); } @Test @@ -64,8 +61,8 @@ public class WebOperationRequestPredicateTests { } private WebOperationRequestPredicate predicateWithPath(String path) { - return new WebOperationRequestPredicate(path, WebEndpointHttpMethod.GET, - Collections.emptyList(), Collections.emptyList()); + return new WebOperationRequestPredicate(path, WebEndpointHttpMethod.GET, Collections.emptyList(), + Collections.emptyList()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java index d9f31987ee1..7d3fb3b0b20 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java @@ -80,43 +80,36 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").exchange().expectStatus().isOk() + .expectBody().jsonPath("All").isEqualTo(true)); } @Test public void readOperationWithEndpointsMappedToTheRoot() { - load(TestEndpointConfiguration.class, "", - (client) -> client.get().uri("/test").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, "", (client) -> client.get().uri("/test").exchange().expectStatus().isOk() + .expectBody().jsonPath("All").isEqualTo(true)); } @Test public void readOperationWithSelector() { - load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/test/one").exchange().expectStatus().isOk() - .expectBody().jsonPath("part").isEqualTo("one")); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/one").exchange().expectStatus().isOk() + .expectBody().jsonPath("part").isEqualTo("one")); } @Test public void readOperationWithSelectorContainingADot() { - load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/test/foo.bar").exchange().expectStatus() - .isOk().expectBody().jsonPath("part").isEqualTo("foo.bar")); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/foo.bar").exchange().expectStatus() + .isOk().expectBody().jsonPath("part").isEqualTo("foo.bar")); } @Test public void linksToOtherEndpointsAreProvided() { load(TestEndpointConfiguration.class, - (client) -> client.get().uri("").exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(3) - .jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false) - .jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false) - .jsonPath("_links.test-part.href").isNotEmpty() - .jsonPath("_links.test-part.templated").isEqualTo(true)); + (client) -> client.get().uri("").exchange().expectStatus().isOk().expectBody() + .jsonPath("_links.length()").isEqualTo(3).jsonPath("_links.self.href").isNotEmpty() + .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() + .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") + .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true)); } @Test @@ -127,51 +120,40 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test/").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/").exchange().expectStatus().isOk() + .expectBody().jsonPath("All").isEqualTo(true)); } @Test public void readOperationWithSingleQueryParameters() { - load(QueryEndpointConfiguration.class, - (client) -> client.get().uri("/query?one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query") - .isEqualTo("1 2")); + load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() + .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 2")); } @Test public void readOperationWithSingleQueryParametersAndMultipleValues() { - load(QueryEndpointConfiguration.class, - (client) -> client.get().uri("/query?one=1&one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query") - .isEqualTo("1,1 2")); + load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&one=1&two=2").exchange() + .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1,1 2")); } @Test public void readOperationWithListQueryParameterAndSingleValue() { - load(QueryWithListEndpointConfiguration.class, - (client) -> client.get().uri("/query?one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query") - .isEqualTo("1 [2]")); + load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() + .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2]")); } @Test public void readOperationWithListQueryParameterAndMultipleValues() { - load(QueryWithListEndpointConfiguration.class, - (client) -> client.get().uri("/query?one=1&two=2&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query") - .isEqualTo("1 [2, 2]")); + load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2&two=2") + .exchange().expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2, 2]")); } @Test public void readOperationWithMappingFailureProducesBadRequestResponse() { load(QueryEndpointConfiguration.class, (client) -> { - WebTestClient.BodyContentSpec body = client.get().uri("/query?two=two") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isBadRequest().expectBody(); - validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/query", - "Missing parameters: one"); + WebTestClient.BodyContentSpec body = client.get().uri("/query?two=two").accept(MediaType.APPLICATION_JSON) + .exchange().expectStatus().isBadRequest().expectBody(); + validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/query", "Missing parameters: one"); }); } @@ -181,32 +163,28 @@ public abstract class AbstractWebEndpointIntegrationTests body = new HashMap<>(); body.put("foo", "one"); body.put("bar", "two"); - client.post().uri("/test").syncBody(body).exchange().expectStatus() - .isNoContent().expectBody().isEmpty(); + client.post().uri("/test").syncBody(body).exchange().expectStatus().isNoContent().expectBody().isEmpty(); }); } @Test public void writeOperationWithVoidResponse() { load(VoidWriteResponseEndpointConfiguration.class, (context, client) -> { - client.post().uri("/voidwrite").exchange().expectStatus().isNoContent() - .expectBody().isEmpty(); + client.post().uri("/voidwrite").exchange().expectStatus().isNoContent().expectBody().isEmpty(); verify(context.getBean(EndpointDelegate.class)).write(); }); } @Test public void deleteOperation() { - load(TestEndpointConfiguration.class, - (client) -> client.delete().uri("/test/one").exchange().expectStatus() - .isOk().expectBody().jsonPath("part").isEqualTo("one")); + load(TestEndpointConfiguration.class, (client) -> client.delete().uri("/test/one").exchange().expectStatus() + .isOk().expectBody().jsonPath("part").isEqualTo("one")); } @Test public void deleteOperationWithVoidResponse() { load(VoidDeleteResponseEndpointConfiguration.class, (context, client) -> { - client.delete().uri("/voiddelete").exchange().expectStatus().isNoContent() - .expectBody().isEmpty(); + client.delete().uri("/voiddelete").exchange().expectStatus().isNoContent().expectBody().isEmpty(); verify(context.getBean(EndpointDelegate.class)).delete(); }); } @@ -216,8 +194,7 @@ public abstract class AbstractWebEndpointIntegrationTests { Map body = new HashMap<>(); body.put("foo", "one"); - client.post().uri("/test").syncBody(body).exchange().expectStatus() - .isNoContent().expectBody().isEmpty(); + client.post().uri("/test").syncBody(body).exchange().expectStatus().isNoContent().expectBody().isEmpty(); verify(context.getBean(EndpointDelegate.class)).write("one", null); }); } @@ -225,122 +202,105 @@ public abstract class AbstractWebEndpointIntegrationTests { - client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isNoContent().expectBody().isEmpty(); + client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange().expectStatus().isNoContent() + .expectBody().isEmpty(); verify(context.getBean(EndpointDelegate.class)).write(null, null); }); } @Test public void nullResponseFromReadOperationResultsInNotFoundResponseStatus() { - load(NullReadResponseEndpointConfiguration.class, (context, client) -> client - .get().uri("/nullread").exchange().expectStatus().isNotFound()); + load(NullReadResponseEndpointConfiguration.class, + (context, client) -> client.get().uri("/nullread").exchange().expectStatus().isNotFound()); } @Test public void nullResponseFromDeleteOperationResultsInNoContentResponseStatus() { - load(NullDeleteResponseEndpointConfiguration.class, (context, client) -> client - .delete().uri("/nulldelete").exchange().expectStatus().isNoContent()); + load(NullDeleteResponseEndpointConfiguration.class, + (context, client) -> client.delete().uri("/nulldelete").exchange().expectStatus().isNoContent()); } @Test public void nullResponseFromWriteOperationResultsInNoContentResponseStatus() { - load(NullWriteResponseEndpointConfiguration.class, (context, client) -> client - .post().uri("/nullwrite").exchange().expectStatus().isNoContent()); + load(NullWriteResponseEndpointConfiguration.class, + (context, client) -> client.post().uri("/nullwrite").exchange().expectStatus().isNoContent()); } @Test public void readOperationWithResourceResponse() { load(ResourceEndpointConfiguration.class, (context, client) -> { - byte[] responseBody = client.get().uri("/resource").exchange().expectStatus() - .isOk().expectHeader().contentType(MediaType.APPLICATION_OCTET_STREAM) - .returnResult(byte[].class).getResponseBodyContent(); + byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }); } @Test public void readOperationWithResourceWebOperationResponse() { - load(ResourceWebEndpointResponseEndpointConfiguration.class, - (context, client) -> { - byte[] responseBody = client.get().uri("/resource").exchange() - .expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .returnResult(byte[].class).getResponseBodyContent(); - assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, - 9); - }); + load(ResourceWebEndpointResponseEndpointConfiguration.class, (context, client) -> { + byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) + .getResponseBodyContent(); + assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + }); } @Test public void readOperationWithMonoResponse() { - load(MonoResponseEndpointConfiguration.class, - (client) -> client.get().uri("/mono").exchange().expectStatus().isOk() - .expectBody().jsonPath("a").isEqualTo("alpha")); + load(MonoResponseEndpointConfiguration.class, (client) -> client.get().uri("/mono").exchange().expectStatus() + .isOk().expectBody().jsonPath("a").isEqualTo("alpha")); } @Test public void readOperationWithCustomMediaType() { - load(CustomMediaTypesEndpointConfiguration.class, - (client) -> client.get().uri("/custommediatypes").exchange() - .expectStatus().isOk().expectHeader() - .valueMatches("Content-Type", "text/plain(;charset=.*)?")); + load(CustomMediaTypesEndpointConfiguration.class, (client) -> client.get().uri("/custommediatypes").exchange() + .expectStatus().isOk().expectHeader().valueMatches("Content-Type", "text/plain(;charset=.*)?")); } @Test public void readOperationWithMissingRequiredParametersReturnsBadRequestResponse() { load(RequiredParameterEndpointConfiguration.class, (client) -> { WebTestClient.BodyContentSpec body = client.get().uri("/requiredparameters") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isBadRequest().expectBody(); - validateErrorBody(body, HttpStatus.BAD_REQUEST, - "/endpoints/requiredparameters", "Missing parameters: foo"); + .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest().expectBody(); + validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/requiredparameters", "Missing parameters: foo"); }); } @Test public void readOperationWithMissingNullableParametersIsOk() { - load(RequiredParameterEndpointConfiguration.class, (client) -> client.get() - .uri("/requiredparameters?foo=hello").exchange().expectStatus().isOk()); + load(RequiredParameterEndpointConfiguration.class, + (client) -> client.get().uri("/requiredparameters?foo=hello").exchange().expectStatus().isOk()); } @Test public void endpointsProducePrimaryMediaTypeByDefault() { - load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/test").exchange().expectStatus().isOk() - .expectHeader() - .valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").exchange().expectStatus().isOk() + .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test public void endpointsProduceSecondaryMediaTypeWhenRequested() { - load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/test").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectHeader() - .valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").accept(MediaType.APPLICATION_JSON) + .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test public void linksProducesPrimaryMediaTypeByDefault() { - load(TestEndpointConfiguration.class, - (client) -> client.get().uri("").exchange().expectStatus().isOk() - .expectHeader() - .valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("").exchange().expectStatus().isOk() + .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test public void linksProducesSecondaryMediaTypeWhenRequested() { - load(TestEndpointConfiguration.class, - (client) -> client.get().uri("").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectHeader() - .valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, (client) -> client.get().uri("").accept(MediaType.APPLICATION_JSON) + .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test public void principalIsNullWhenRequestHasNoPrincipal() { load(PrincipalEndpointConfiguration.class, - (client) -> client.get().uri("/principal") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() .isOk().expectBody(String.class).isEqualTo("None")); } @@ -349,9 +309,8 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalEndpointConfiguration.class); - }, (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("Alice")); + }, (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isOk().expectBody(String.class).isEqualTo("Alice")); } @Test @@ -359,17 +318,15 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalQueryEndpointConfiguration.class); - }, (client) -> client.get().uri("/principalquery?principal=Zoe") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("Zoe")); + }, (client) -> client.get().uri("/principalquery?principal=Zoe").accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("Zoe")); } @Test public void securityContextIsAvailableAndHasNullPrincipalWhenRequestHasNoPrincipal() { load(SecurityContextEndpointConfiguration.class, - (client) -> client.get().uri("/securitycontext") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("None")); + (client) -> client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("None")); } @Test @@ -377,17 +334,15 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(SecurityContextEndpointConfiguration.class); - }, (client) -> client.get().uri("/securitycontext") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("Alice")); + }, (client) -> client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isOk().expectBody(String.class).isEqualTo("Alice")); } @Test public void userInRoleReturnsFalseWhenRequestHasNoPrincipal() { load(UserInRoleEndpointConfiguration.class, - (client) -> client.get().uri("/userinrole?role=ADMIN") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("ADMIN: false")); + (client) -> client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); } @Test @@ -395,9 +350,8 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); - }, (client) -> client.get().uri("/userinrole?role=ADMIN") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("ADMIN: false")); + }, (client) -> client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); } @Test @@ -405,22 +359,19 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); - }, (client) -> client.get().uri("/userinrole?role=ACTUATOR") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("ACTUATOR: true")); + }, (client) -> client.get().uri("/userinrole?role=ACTUATOR").accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("ACTUATOR: true")); } protected abstract int getPort(T context); - protected void validateErrorBody(WebTestClient.BodyContentSpec body, - HttpStatus status, String path, String message) { - body.jsonPath("status").isEqualTo(status.value()).jsonPath("error") - .isEqualTo(status.getReasonPhrase()).jsonPath("path").isEqualTo(path) - .jsonPath("message").isEqualTo(message); + protected void validateErrorBody(WebTestClient.BodyContentSpec body, HttpStatus status, String path, + String message) { + body.jsonPath("status").isEqualTo(status.value()).jsonPath("error").isEqualTo(status.getReasonPhrase()) + .jsonPath("path").isEqualTo(path).jsonPath("message").isEqualTo(message); } - private void load(Class configuration, - BiConsumer consumer) { + private void load(Class configuration, BiConsumer consumer) { load((context) -> context.register(configuration), "/endpoints", consumer); } @@ -429,14 +380,11 @@ public abstract class AbstractWebEndpointIntegrationTests clientConsumer.accept(client)); } - protected void load(Consumer contextCustomizer, - Consumer clientConsumer) { - load(contextCustomizer, "/endpoints", - (context, client) -> clientConsumer.accept(client)); + protected void load(Consumer contextCustomizer, Consumer clientConsumer) { + load(contextCustomizer, "/endpoints", (context, client) -> clientConsumer.accept(client)); } - protected void load(Class configuration, String endpointPath, - Consumer clientConsumer) { + protected void load(Class configuration, String endpointPath, Consumer clientConsumer) { load((context) -> context.register(configuration), endpointPath, (context, client) -> clientConsumer.accept(client)); } @@ -446,16 +394,13 @@ public abstract class AbstractWebEndpointIntegrationTests queryWithParameterList(@Selector String list, - String one, List two) { + public Map queryWithParameterList(@Selector String list, String one, List two) { return Collections.singletonMap("query", list + " " + one + " " + two); } @@ -793,9 +734,7 @@ public abstract class AbstractWebEndpointIntegrationTests read() { - return new WebEndpointResponse<>( - new ByteArrayResource(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }), - 200); + return new WebEndpointResponse<>(new ByteArrayResource(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }), 200); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/BaseConfiguration.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/BaseConfiguration.java index 3f97a674264..33a9bb2e9ae 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/BaseConfiguration.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/BaseConfiguration.java @@ -56,20 +56,17 @@ class BaseConfiguration { @Bean public EndpointMediaTypes endpointMediaTypes() { - List mediaTypes = Arrays.asList("application/vnd.test+json", - "application/json"); + List mediaTypes = Arrays.asList("application/vnd.test+json", "application/json"); return new EndpointMediaTypes(mediaTypes, mediaTypes); } @Bean - public WebEndpointDiscoverer webEndpointDiscoverer( - EndpointMediaTypes endpointMediaTypes, + public WebEndpointDiscoverer webEndpointDiscoverer(EndpointMediaTypes endpointMediaTypes, ApplicationContext applicationContext) { ParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - return new WebEndpointDiscoverer(applicationContext, parameterMapper, - endpointMediaTypes, null, Collections.emptyList(), - Collections.emptyList()); + return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes, null, + Collections.emptyList(), Collections.emptyList()); } @Bean diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java index 30ade20487d..7cab2b4783d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java @@ -54,40 +54,31 @@ public class ControllerEndpointDiscovererTests { @Test public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run(assertDiscoverer( - (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); + .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test public void getEndpointsShouldIncludeControllerEndpoints() { - this.contextRunner.withUserConfiguration(TestControllerEndpoint.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()) - .isEqualTo(EndpointId.of("testcontroller")); - assertThat(endpoint.getController()) - .isInstanceOf(TestControllerEndpoint.class); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + this.contextRunner.withUserConfiguration(TestControllerEndpoint.class).run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestControllerEndpoint.class); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test public void getEndpointsShouldDiscoverProxyControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyControllerEndpoint.class) - .withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); + Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints).hasSize(1); ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()) - .isEqualTo(EndpointId.of("testcontroller")); - assertThat(endpoint.getController()) - .isInstanceOf(TestProxyControllerEndpoint.class); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestProxyControllerEndpoint.class); assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); })); } @@ -96,31 +87,24 @@ public class ControllerEndpointDiscovererTests { public void getEndpointsShouldIncludeRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestRestControllerEndpoint.class) .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); + Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints).hasSize(1); ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()) - .isEqualTo(EndpointId.of("testrestcontroller")); - assertThat(endpoint.getController()) - .isInstanceOf(TestRestControllerEndpoint.class); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestRestControllerEndpoint.class); })); } @Test public void getEndpointsShouldDiscoverProxyRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyRestControllerEndpoint.class) - .withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); + Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints).hasSize(1); ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()) - .isEqualTo(EndpointId.of("testrestcontroller")); - assertThat(endpoint.getController()) - .isInstanceOf(TestProxyRestControllerEndpoint.class); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestProxyRestControllerEndpoint.class); assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); })); } @@ -129,30 +113,26 @@ public class ControllerEndpointDiscovererTests { public void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); - List ids = endpoints.stream() - .map(ExposableEndpoint::getEndpointId) + Collection endpoints = discoverer.getEndpoints(); + List ids = endpoints.stream().map(ExposableEndpoint::getEndpointId) .collect(Collectors.toList()); - assertThat(ids).containsOnly(EndpointId.of("testcontroller"), - EndpointId.of("testrestcontroller")); + assertThat(ids).containsOnly(EndpointId.of("testcontroller"), EndpointId.of("testrestcontroller")); })); } @Test public void getEndpointWhenEndpointHasOperationsShouldThrowException() { this.contextRunner.withUserConfiguration(TestControllerWithOperation.class) - .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( - IllegalStateException.class).isThrownBy(discoverer::getEndpoints) - .withMessageContaining( - "ControllerEndpoints must not declare operations"))); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining("ControllerEndpoints must not declare operations"))); } private ContextConsumer assertDiscoverer( Consumer consumer) { return (context) -> { - ControllerEndpointDiscoverer discoverer = new ControllerEndpointDiscoverer( - context, null, Collections.emptyList()); + ControllerEndpointDiscoverer discoverer = new ControllerEndpointDiscoverer(context, null, + Collections.emptyList()); consumer.accept(discoverer); }; } @@ -163,8 +143,7 @@ public class ControllerEndpointDiscovererTests { } @Configuration(proxyBeanMethods = false) - @Import({ TestEndpoint.class, TestControllerEndpoint.class, - TestRestControllerEndpoint.class }) + @Import({ TestEndpoint.class, TestControllerEndpoint.class, TestRestControllerEndpoint.class }) static class WithRegularEndpointConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java index ed7279da863..ac359db7325 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java @@ -63,37 +63,30 @@ public class ServletEndpointDiscovererTests { @Test public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run(assertDiscoverer( - (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); + .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test public void getEndpointsShouldIncludeServletEndpoints() { - this.contextRunner.withUserConfiguration(TestServletEndpoint.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableServletEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()) - .isEqualTo(EndpointId.of("testservlet")); - assertThat(endpoint.getEndpointServlet()).isNotNull(); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + this.contextRunner.withUserConfiguration(TestServletEndpoint.class).run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableServletEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testservlet")); + assertThat(endpoint.getEndpointServlet()).isNotNull(); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test public void getEndpointsShouldDiscoverProxyServletEndpoints() { this.contextRunner.withUserConfiguration(TestProxyServletEndpoint.class) - .withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); + Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints).hasSize(1); ExposableServletEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()) - .isEqualTo(EndpointId.of("testservlet")); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testservlet")); assertThat(endpoint.getEndpointServlet()).isNotNull(); assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); })); @@ -103,10 +96,8 @@ public class ServletEndpointDiscovererTests { public void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer - .getEndpoints(); - List ids = endpoints.stream() - .map(ExposableEndpoint::getEndpointId) + Collection endpoints = discoverer.getEndpoints(); + List ids = endpoints.stream().map(ExposableEndpoint::getEndpointId) .collect(Collectors.toList()); assertThat(ids).containsOnly(EndpointId.of("testservlet")); })); @@ -115,43 +106,37 @@ public class ServletEndpointDiscovererTests { @Test public void getEndpointWhenEndpointHasOperationsShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class) - .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( - IllegalStateException.class).isThrownBy(discoverer::getEndpoints) - .withMessageContaining( - "ServletEndpoints must not declare operations"))); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining("ServletEndpoints must not declare operations"))); } @Test public void getEndpointWhenEndpointNotASupplierShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointNotASupplier.class) - .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( - IllegalStateException.class).isThrownBy(discoverer::getEndpoints) - .withMessageContaining("must be a supplier"))); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(discoverer::getEndpoints).withMessageContaining("must be a supplier"))); } @Test public void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { - this.contextRunner - .withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) - .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( - IllegalStateException.class).isThrownBy(discoverer::getEndpoints) - .withMessageContaining( - "must supply an EndpointServlet"))); + this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(discoverer::getEndpoints).withMessageContaining("must supply an EndpointServlet"))); } @Test public void getEndpointWhenEndpointSuppliesNullShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfNull.class) - .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( - IllegalStateException.class).isThrownBy(discoverer::getEndpoints) - .withMessageContaining("must not supply null"))); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(discoverer::getEndpoints).withMessageContaining("must not supply null"))); } private ContextConsumer assertDiscoverer( Consumer consumer) { return (context) -> { - ServletEndpointDiscoverer discoverer = new ServletEndpointDiscoverer(context, - null, Collections.emptyList()); + ServletEndpointDiscoverer discoverer = new ServletEndpointDiscoverer(context, null, + Collections.emptyList()); consumer.accept(discoverer); }; } @@ -211,8 +196,7 @@ public class ServletEndpointDiscovererTests { private static class TestServlet extends GenericServlet { @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java index 437a7ee9ed5..8f5a0c4545f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java @@ -70,24 +70,21 @@ public class WebEndpointDiscovererTests { @Test public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { - load(EmptyConfiguration.class, - (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty()); + load(EmptyConfiguration.class, (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty()); } @Test public void getEndpointsWhenWebExtensionIsMissingEndpointShouldThrowException() { load(TestWebEndpointExtensionConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Invalid extension 'endpointExtension': no endpoint found with id '" - + "test'")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Invalid extension 'endpointExtension': no endpoint found with id '" + "test'")); } @Test public void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverWebEndpoints() { load(MultipleEndpointsConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); }); } @@ -95,191 +92,156 @@ public class WebEndpointDiscovererTests { @Test public void getEndpointsWhenHasWebExtensionShouldOverrideStandardEndpoint() { load(OverriddenOperationWebEndpointExtensionConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); - assertThat(requestPredicates(endpoint)).has( - requestPredicates(path("test").httpMethod(WebEndpointHttpMethod.GET) - .consumes().produces("application/json"))); + assertThat(requestPredicates(endpoint)).has(requestPredicates( + path("test").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/json"))); }); } @Test public void getEndpointsWhenExtensionAddsOperationShouldHaveBothOperations() { load(AdditionalOperationWebEndpointConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); assertThat(requestPredicates(endpoint)).has(requestPredicates( - path("test").httpMethod(WebEndpointHttpMethod.GET).consumes() - .produces("application/json"), - path("test/{id}").httpMethod(WebEndpointHttpMethod.GET).consumes() - .produces("application/json"))); + path("test").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/json"), + path("test/{id}").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/json"))); }); } @Test public void getEndpointsWhenPredicateForWriteOperationThatReturnsVoidShouldHaveNoProducedMediaTypes() { load(VoidWriteOperationEndpointConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("voidwrite")); ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("voidwrite")); assertThat(requestPredicates(endpoint)).has(requestPredicates( - path("voidwrite").httpMethod(WebEndpointHttpMethod.POST).produces() - .consumes("application/json"))); + path("voidwrite").httpMethod(WebEndpointHttpMethod.POST).produces().consumes("application/json"))); }); } @Test public void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingWebEndpointConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Found multiple extensions for the endpoint bean " - + "testEndpoint (testExtensionOne, testExtensionTwo)")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("Found multiple extensions for the endpoint bean " + + "testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test public void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Found two endpoints with the id 'test': ")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpointConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: " - + "[web request predicate GET to path 'test' " - + "produces: application/json] to clashingOperationsEndpoint")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("Unable to map duplicate endpoint operations: " + + "[web request predicate GET to path 'test' " + + "produces: application/json] to clashingOperationsEndpoint")); } @Test public void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidWebExtensionConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Endpoint bean 'nonWebEndpoint' cannot support the " - + "extension bean 'nonWebWebEndpointExtension'")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("Endpoint bean 'nonWebEndpoint' cannot support the " + + "extension bean 'nonWebWebEndpointExtension'")); } @Test public void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingSelectorsWebEndpointExtensionConfiguration.class, - (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints) - .withMessageContaining( - "Unable to map duplicate endpoint operations") - .withMessageContaining( - "to testEndpoint (clashingSelectorsExtension)")); + (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("Unable to map duplicate endpoint operations") + .withMessageContaining("to testEndpoint (clashingSelectorsExtension)")); } @Test public void getEndpointsWhenHasCacheWithTtlShouldCacheReadOperationWithTtlValue() { - load((id) -> 500L, EndpointId::toString, TestEndpointConfiguration.class, - (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); - assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); - assertThat(endpoint.getOperations()).hasSize(1); - WebOperation operation = endpoint.getOperations().iterator().next(); - Object invoker = ReflectionTestUtils.getField(operation, "invoker"); - assertThat(invoker).isInstanceOf(CachingOperationInvoker.class); - assertThat(((CachingOperationInvoker) invoker).getTimeToLive()) - .isEqualTo(500); - }); + load((id) -> 500L, EndpointId::toString, TestEndpointConfiguration.class, (discoverer) -> { + Map endpoints = mapEndpoints(discoverer.getEndpoints()); + assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); + ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); + assertThat(endpoint.getOperations()).hasSize(1); + WebOperation operation = endpoint.getOperations().iterator().next(); + Object invoker = ReflectionTestUtils.getField(operation, "invoker"); + assertThat(invoker).isInstanceOf(CachingOperationInvoker.class); + assertThat(((CachingOperationInvoker) invoker).getTimeToLive()).isEqualTo(500); + }); } @Test public void getEndpointsWhenOperationReturnsResourceShouldProduceApplicationOctetStream() { load(ResourceEndpointConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("resource")); ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("resource")); - assertThat(requestPredicates(endpoint)).has(requestPredicates( - path("resource").httpMethod(WebEndpointHttpMethod.GET).consumes() - .produces("application/octet-stream"))); + assertThat(requestPredicates(endpoint)).has(requestPredicates(path("resource") + .httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/octet-stream"))); }); } @Test public void getEndpointsWhenHasCustomMediaTypeShouldProduceCustomMediaType() { load(CustomMediaTypesEndpointConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("custommediatypes")); - ExposableWebEndpoint endpoint = endpoints - .get(EndpointId.of("custommediatypes")); + ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("custommediatypes")); assertThat(requestPredicates(endpoint)).has(requestPredicates( - path("custommediatypes").httpMethod(WebEndpointHttpMethod.GET) - .consumes().produces("text/plain"), - path("custommediatypes").httpMethod(WebEndpointHttpMethod.POST) - .consumes().produces("a/b", "c/d"), - path("custommediatypes").httpMethod(WebEndpointHttpMethod.DELETE) - .consumes().produces("text/plain"))); + path("custommediatypes").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("text/plain"), + path("custommediatypes").httpMethod(WebEndpointHttpMethod.POST).consumes().produces("a/b", "c/d"), + path("custommediatypes").httpMethod(WebEndpointHttpMethod.DELETE).consumes() + .produces("text/plain"))); }); } @Test public void getEndpointsWhenHasCustomPathShouldReturnCustomPath() { - load((id) -> null, (id) -> "custom/" + id, - AdditionalOperationWebEndpointConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); - assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); - ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); - Condition> expected = requestPredicates( - path("custom/test").httpMethod(WebEndpointHttpMethod.GET) - .consumes().produces("application/json"), - path("custom/test/{id}").httpMethod(WebEndpointHttpMethod.GET) - .consumes().produces("application/json")); - assertThat(requestPredicates(endpoint)).has(expected); - }); + load((id) -> null, (id) -> "custom/" + id, AdditionalOperationWebEndpointConfiguration.class, (discoverer) -> { + Map endpoints = mapEndpoints(discoverer.getEndpoints()); + assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); + ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); + Condition> expected = requestPredicates( + path("custom/test").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/json"), + path("custom/test/{id}").httpMethod(WebEndpointHttpMethod.GET).consumes() + .produces("application/json")); + assertThat(requestPredicates(endpoint)).has(expected); + }); } private void load(Class configuration, Consumer consumer) { this.load((id) -> null, EndpointId::toString, configuration, consumer); } - private void load(Function timeToLive, - PathMapper endpointPathMapper, Class configuration, + private void load(Function timeToLive, PathMapper endpointPathMapper, Class configuration, Consumer consumer) { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - configuration)) { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { ConversionServiceParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - EndpointMediaTypes mediaTypes = new EndpointMediaTypes( - Collections.singletonList("application/json"), + EndpointMediaTypes mediaTypes = new EndpointMediaTypes(Collections.singletonList("application/json"), Collections.singletonList("application/json")); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(context, - parameterMapper, mediaTypes, + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(context, parameterMapper, mediaTypes, Collections.singletonList(endpointPathMapper), - Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), - Collections.emptyList()); + Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), Collections.emptyList()); consumer.accept(discoverer); } } - private Map mapEndpoints( - Collection endpoints) { + private Map mapEndpoints(Collection endpoints) { Map endpointById = new HashMap<>(); - endpoints.forEach( - (endpoint) -> endpointById.put(endpoint.getEndpointId(), endpoint)); + endpoints.forEach((endpoint) -> endpointById.put(endpoint.getEndpointId(), endpoint)); return endpointById; } - private List requestPredicates( - ExposableWebEndpoint endpoint) { - return endpoint.getOperations().stream().map(WebOperation::getRequestPredicate) - .collect(Collectors.toList()); + private List requestPredicates(ExposableWebEndpoint endpoint) { + return endpoint.getOperations().stream().map(WebOperation::getRequestPredicate).collect(Collectors.toList()); } private Condition> requestPredicates( @@ -290,8 +252,7 @@ public class WebEndpointDiscovererTests { } Map matchCounts = new HashMap<>(); for (WebOperationRequestPredicate predicate : predicates) { - matchCounts.put(predicate, Stream.of(matchers) - .filter((matcher) -> matcher.matches(predicate)).count()); + matchCounts.put(predicate, Stream.of(matchers).filter((matcher) -> matcher.matches(predicate)).count()); } return matchCounts.values().stream().noneMatch((count) -> count != 1); }, Arrays.toString(matchers)); @@ -670,18 +631,15 @@ public class WebEndpointDiscovererTests { private boolean matches(WebOperationRequestPredicate predicate) { return (this.path == null || this.path.equals(predicate.getPath())) - && (this.httpMethod == null - || this.httpMethod == predicate.getHttpMethod()) - && (this.produces == null || this.produces - .equals(new ArrayList<>(predicate.getProduces()))) - && (this.consumes == null || this.consumes - .equals(new ArrayList<>(predicate.getConsumes()))); + && (this.httpMethod == null || this.httpMethod == predicate.getHttpMethod()) + && (this.produces == null || this.produces.equals(new ArrayList<>(predicate.getProduces()))) + && (this.consumes == null || this.consumes.equals(new ArrayList<>(predicate.getConsumes()))); } @Override public String toString() { - return "Request predicate with path = '" + this.path + "', httpMethod = '" - + this.httpMethod + "', produces = '" + this.produces + "'"; + return "Request predicate with path = '" + this.path + "', httpMethod = '" + this.httpMethod + + "', produces = '" + this.produces + "'"; } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java index 1e9570e31a9..d5e63ca99ec 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java @@ -60,8 +60,8 @@ import org.springframework.web.filter.OncePerRequestFilter; * @author Andy Wilkinson * @see JerseyEndpointResourceFactory */ -public class JerseyWebEndpointIntegrationTests extends - AbstractWebEndpointIntegrationTests { +public class JerseyWebEndpointIntegrationTests + extends AbstractWebEndpointIntegrationTests { public JerseyWebEndpointIntegrationTests() { super(JerseyWebEndpointIntegrationTests::createApplicationContext, @@ -74,8 +74,7 @@ public class JerseyWebEndpointIntegrationTests extends return context; } - private static void applyAuthenticatedConfiguration( - AnnotationConfigServletWebServerApplicationContext context) { + private static void applyAuthenticatedConfiguration(AnnotationConfigServletWebServerApplicationContext context) { context.register(AuthenticatedConfiguration.class); } @@ -85,8 +84,8 @@ public class JerseyWebEndpointIntegrationTests extends } @Override - protected void validateErrorBody(WebTestClient.BodyContentSpec body, - HttpStatus status, String path, String message) { + protected void validateErrorBody(WebTestClient.BodyContentSpec body, HttpStatus status, String path, + String message) { // Jersey doesn't support the general error page handling } @@ -99,26 +98,20 @@ public class JerseyWebEndpointIntegrationTests extends } @Bean - public ServletRegistrationBean servletContainer( - ResourceConfig resourceConfig) { - return new ServletRegistrationBean<>(new ServletContainer(resourceConfig), - "/*"); + public ServletRegistrationBean servletContainer(ResourceConfig resourceConfig) { + return new ServletRegistrationBean<>(new ServletContainer(resourceConfig), "/*"); } @Bean - public ResourceConfig resourceConfig(Environment environment, - WebEndpointDiscoverer endpointDiscoverer, + public ResourceConfig resourceConfig(Environment environment, WebEndpointDiscoverer endpointDiscoverer, EndpointMediaTypes endpointMediaTypes) { ResourceConfig resourceConfig = new ResourceConfig(); - Collection resources = new JerseyEndpointResourceFactory() - .createEndpointResources( - new EndpointMapping(environment.getProperty("endpointPath")), - endpointDiscoverer.getEndpoints(), endpointMediaTypes, - new EndpointLinksResolver(endpointDiscoverer.getEndpoints())); + Collection resources = new JerseyEndpointResourceFactory().createEndpointResources( + new EndpointMapping(environment.getProperty("endpointPath")), endpointDiscoverer.getEndpoints(), + endpointMediaTypes, new EndpointLinksResolver(endpointDiscoverer.getEndpoints())); resourceConfig.registerResources(new HashSet<>(resources)); resourceConfig.register(JacksonFeature.class); - resourceConfig.register(new ObjectMapperContextResolver(new ObjectMapper()), - ContextResolver.class); + resourceConfig.register(new ObjectMapperContextResolver(new ObjectMapper()), ContextResolver.class); return resourceConfig; } @@ -132,17 +125,14 @@ public class JerseyWebEndpointIntegrationTests extends return new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(new UsernamePasswordAuthenticationToken( - "Alice", "secret", + context.setAuthentication(new UsernamePasswordAuthenticationToken("Alice", "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR")))); SecurityContextHolder.setContext(context); try { - filterChain.doFilter(new SecurityContextHolderAwareRequestWrapper( - request, "ROLE_"), response); + filterChain.doFilter(new SecurityContextHolderAwareRequestWrapper(request, "ROLE_"), response); } finally { SecurityContextHolder.clearContext(); @@ -154,8 +144,7 @@ public class JerseyWebEndpointIntegrationTests extends } - private static final class ObjectMapperContextResolver - implements ContextResolver { + private static final class ObjectMapperContextResolver implements ContextResolver { private final ObjectMapper objectMapper; diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java index 433484f28f2..be6b93444cb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java @@ -61,56 +61,48 @@ import org.springframework.web.util.DefaultUriBuilderFactory; public class ControllerEndpointHandlerMappingIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new) - .withUserConfiguration(EndpointConfiguration.class, - ExampleWebFluxEndpoint.class); + AnnotationConfigReactiveWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, + ExampleWebFluxEndpoint.class); @Test public void get() { - this.contextRunner.run(withWebTestClient( - (webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() - .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_PLAIN) - .expectBody(String.class).isEqualTo("One"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") + .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); } @Test public void getWithUnacceptableContentType() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() - .uri("/actuator/example/one").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") + .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test public void post() { - this.contextRunner.run(withWebTestClient( - (webTestClient) -> webTestClient.post().uri("/actuator/example/two") - .syncBody(Collections.singletonMap("id", "test")).exchange() - .expectStatus().isCreated().expectHeader() - .valueEquals(HttpHeaders.LOCATION, "/example/test"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") + .syncBody(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() + .valueEquals(HttpHeaders.LOCATION, "/example/test"))); } private ContextConsumer withWebTestClient( Consumer webClient) { return (context) -> { - int port = ((AnnotationConfigReactiveWebServerApplicationContext) context - .getSourceApplicationContext()).getWebServer().getPort(); + int port = ((AnnotationConfigReactiveWebServerApplicationContext) context.getSourceApplicationContext()) + .getWebServer().getPort(); WebTestClient webTestClient = createWebTestClient(port); webClient.accept(webTestClient); }; } private WebTestClient createWebTestClient(int port) { - DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( - "http://localhost:" + port); + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://localhost:" + port); uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory) - .responseTimeout(Duration.ofMinutes(2)).build(); + return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(Duration.ofMinutes(2)) + .build(); } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, WebFluxAutoConfiguration.class }) static class EndpointConfiguration { @@ -125,10 +117,8 @@ public class ControllerEndpointHandlerMappingIntegrationTests { } @Bean - public ControllerEndpointDiscoverer webEndpointDiscoverer( - ApplicationContext applicationContext) { - return new ControllerEndpointDiscoverer(applicationContext, null, - Collections.emptyList()); + public ControllerEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext) { + return new ControllerEndpointDiscoverer(applicationContext, null, Collections.emptyList()); } @Bean @@ -150,8 +140,7 @@ public class ControllerEndpointHandlerMappingIntegrationTests { @PostMapping("/two") public ResponseEntity two(@RequestBody Map content) { - return ResponseEntity.created(URI.create("/example/" + content.get("id"))) - .build(); + return ResponseEntity.created(URI.create("/example/" + content.get("id"))).build(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java index 03d843f60f4..841c75ac1d6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java @@ -55,8 +55,7 @@ public class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("", first, second); - assertThat(getHandler(mapping, HttpMethod.GET, "/first")) - .isEqualTo(handlerOf(first.getController(), "get")); + assertThat(getHandler(mapping, HttpMethod.GET, "/first")).isEqualTo(handlerOf(first.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.POST, "/second")) .isEqualTo(handlerOf(second.getController(), "save")); assertThat(getHandler(mapping, HttpMethod.GET, "/third")).isNull(); @@ -66,8 +65,7 @@ public class ControllerEndpointHandlerMappingTests { public void mappingWithPrefix() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); - ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, - second); + ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); assertThat(getHandler(mapping, HttpMethod.GET, "/actuator/first")) .isEqualTo(handlerOf(first.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.POST, "/actuator/second")) @@ -90,33 +88,28 @@ public class ControllerEndpointHandlerMappingTests { public void mappingNarrowedToMethod() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); - assertThatExceptionOfType(MethodNotAllowedException.class).isThrownBy( - () -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); + assertThatExceptionOfType(MethodNotAllowedException.class) + .isThrownBy(() -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); } - private Object getHandler(ControllerEndpointHandlerMapping mapping, HttpMethod method, - String requestURI) { - return mapping.getHandler(exchange(method, requestURI)) - .block(Duration.ofSeconds(30)); + private Object getHandler(ControllerEndpointHandlerMapping mapping, HttpMethod method, String requestURI) { + return mapping.getHandler(exchange(method, requestURI)).block(Duration.ofSeconds(30)); } - private ControllerEndpointHandlerMapping createMapping(String prefix, - ExposableControllerEndpoint... endpoints) { - ControllerEndpointHandlerMapping mapping = new ControllerEndpointHandlerMapping( - new EndpointMapping(prefix), Arrays.asList(endpoints), null); + private ControllerEndpointHandlerMapping createMapping(String prefix, ExposableControllerEndpoint... endpoints) { + ControllerEndpointHandlerMapping mapping = new ControllerEndpointHandlerMapping(new EndpointMapping(prefix), + Arrays.asList(endpoints), null); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); return mapping; } private HandlerMethod handlerOf(Object source, String methodName) { - return new HandlerMethod(source, - ReflectionUtils.findMethod(source.getClass(), methodName)); + return new HandlerMethod(source, ReflectionUtils.findMethod(source.getClass(), methodName)); } private MockServerWebExchange exchange(HttpMethod method, String requestURI) { - return MockServerWebExchange - .from(MockServerHttpRequest.method(method, requestURI).build()); + return MockServerWebExchange.from(MockServerHttpRequest.method(method, requestURI).build()); } private ExposableControllerEndpoint firstEndpoint() { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java index 6f0f93d892b..f493387a6a8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java @@ -54,8 +54,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @see WebFluxEndpointHandlerMapping */ -public class WebFluxEndpointIntegrationTests extends - AbstractWebEndpointIntegrationTests { +public class WebFluxEndpointIntegrationTests + extends AbstractWebEndpointIntegrationTests { public WebFluxEndpointIntegrationTests() { super(WebFluxEndpointIntegrationTests::createApplicationContext, @@ -69,30 +69,27 @@ public class WebFluxEndpointIntegrationTests extends return context; } - private static void applyAuthenticatedConfiguration( - AnnotationConfigReactiveWebServerApplicationContext context) { + private static void applyAuthenticatedConfiguration(AnnotationConfigReactiveWebServerApplicationContext context) { context.register(AuthenticatedConfiguration.class); } @Test public void responseToOptionsRequestIncludesCorsHeaders() { - load(TestEndpointConfiguration.class, (client) -> client.options().uri("/test") - .accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST") - .header("Origin", "https://example.com").exchange().expectStatus().isOk() - .expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com") - .expectHeader().valueEquals("Access-Control-Allow-Methods", "GET,POST")); + load(TestEndpointConfiguration.class, + (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") + .exchange().expectStatus().isOk().expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test public void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { - byte[] responseBody = client.get().uri("/resource") - .header("Range", "bytes=0-3").exchange().expectStatus() + byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .returnResult(byte[].class).getResponseBodyContent(); + .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3); }); } @@ -120,16 +117,13 @@ public class WebFluxEndpointIntegrationTests extends } @Bean - public WebFluxEndpointHandlerMapping webEndpointHandlerMapping( - Environment environment, WebEndpointDiscoverer endpointDiscoverer, - EndpointMediaTypes endpointMediaTypes) { + public WebFluxEndpointHandlerMapping webEndpointHandlerMapping(Environment environment, + WebEndpointDiscoverer endpointDiscoverer, EndpointMediaTypes endpointMediaTypes) { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedOrigins(Arrays.asList("https://example.com")); corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST")); - return new WebFluxEndpointHandlerMapping( - new EndpointMapping(environment.getProperty("endpointPath")), - endpointDiscoverer.getEndpoints(), endpointMediaTypes, - corsConfiguration, + return new WebFluxEndpointHandlerMapping(new EndpointMapping(environment.getProperty("endpointPath")), + endpointDiscoverer.getEndpoints(), endpointMediaTypes, corsConfiguration, new EndpointLinksResolver(endpointDiscoverer.getEndpoints())); } @@ -145,11 +139,9 @@ public class WebFluxEndpointIntegrationTests extends @Bean public WebFilter webFilter() { - return (exchange, chain) -> chain.filter(exchange) - .subscriberContext(ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("Alice", "secret", - Arrays.asList(new SimpleGrantedAuthority( - "ROLE_ACTUATOR"))))); + return (exchange, chain) -> chain.filter(exchange).subscriberContext( + ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("Alice", + "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR"))))); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java index 0d2ac2760ec..3206c09a7af 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java @@ -60,57 +60,48 @@ import org.springframework.web.util.DefaultUriBuilderFactory; public class ControllerEndpointHandlerMappingIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withUserConfiguration(EndpointConfiguration.class, - ExampleMvcEndpoint.class); + AnnotationConfigServletWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, + ExampleMvcEndpoint.class); @Test public void get() { - this.contextRunner.run(withWebTestClient( - (webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() - .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_PLAIN) - .expectBody(String.class).isEqualTo("One"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") + .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); } @Test public void getWithUnacceptableContentType() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() - .uri("/actuator/example/one").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") + .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test public void post() { - this.contextRunner.run(withWebTestClient( - (webTestClient) -> webTestClient.post().uri("/actuator/example/two") - .syncBody(Collections.singletonMap("id", "test")).exchange() - .expectStatus().isCreated().expectHeader() - .valueEquals(HttpHeaders.LOCATION, "/example/test"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") + .syncBody(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() + .valueEquals(HttpHeaders.LOCATION, "/example/test"))); } - private ContextConsumer withWebTestClient( - Consumer webClient) { + private ContextConsumer withWebTestClient(Consumer webClient) { return (context) -> { - int port = ((AnnotationConfigServletWebServerApplicationContext) context - .getSourceApplicationContext()).getWebServer().getPort(); + int port = ((AnnotationConfigServletWebServerApplicationContext) context.getSourceApplicationContext()) + .getWebServer().getPort(); WebTestClient webTestClient = createWebTestClient(port); webClient.accept(webTestClient); }; } private WebTestClient createWebTestClient(int port) { - DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( - "http://localhost:" + port); + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://localhost:" + port); uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory) - .responseTimeout(Duration.ofMinutes(2)).build(); + return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(Duration.ofMinutes(2)) + .build(); } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) static class EndpointConfiguration { @Bean @@ -119,10 +110,8 @@ public class ControllerEndpointHandlerMappingIntegrationTests { } @Bean - public ControllerEndpointDiscoverer webEndpointDiscoverer( - ApplicationContext applicationContext) { - return new ControllerEndpointDiscoverer(applicationContext, null, - Collections.emptyList()); + public ControllerEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext) { + return new ControllerEndpointDiscoverer(applicationContext, null, Collections.emptyList()); } @Bean @@ -144,8 +133,7 @@ public class ControllerEndpointHandlerMappingIntegrationTests { @PostMapping("/two") public ResponseEntity two(@RequestBody Map content) { - return ResponseEntity.created(URI.create("/example/" + content.get("id"))) - .build(); + return ResponseEntity.created(URI.create("/example/" + content.get("id"))).build(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java index f0a3c324470..0a370439cd3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java @@ -63,8 +63,7 @@ public class ControllerEndpointHandlerMappingTests { public void mappingWithPrefix() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); - ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, - second); + ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); assertThat(mapping.getHandler(request("GET", "/actuator/first")).getHandler()) .isEqualTo(handlerOf(first.getController(), "get")); assertThat(mapping.getHandler(request("POST", "/actuator/second")).getHandler()) @@ -91,18 +90,16 @@ public class ControllerEndpointHandlerMappingTests { assertThat(mapping.getHandler(request("GET", "/"))).isNull(); } - private ControllerEndpointHandlerMapping createMapping(String prefix, - ExposableControllerEndpoint... endpoints) { - ControllerEndpointHandlerMapping mapping = new ControllerEndpointHandlerMapping( - new EndpointMapping(prefix), Arrays.asList(endpoints), null); + private ControllerEndpointHandlerMapping createMapping(String prefix, ExposableControllerEndpoint... endpoints) { + ControllerEndpointHandlerMapping mapping = new ControllerEndpointHandlerMapping(new EndpointMapping(prefix), + Arrays.asList(endpoints), null); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); return mapping; } private HandlerMethod handlerOf(Object source, String methodName) { - return new HandlerMethod(source, - ReflectionUtils.findMethod(source.getClass(), methodName)); + return new HandlerMethod(source, ReflectionUtils.findMethod(source.getClass(), methodName)); } private MockHttpServletRequest request(String method, String requestURI) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java index 8eb92bd35a4..21f24e2dce4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java @@ -64,8 +64,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @see WebMvcEndpointHandlerMapping */ -public class MvcWebEndpointIntegrationTests extends - AbstractWebEndpointIntegrationTests { +public class MvcWebEndpointIntegrationTests + extends AbstractWebEndpointIntegrationTests { public MvcWebEndpointIntegrationTests() { super(MvcWebEndpointIntegrationTests::createApplicationContext, @@ -78,30 +78,27 @@ public class MvcWebEndpointIntegrationTests extends return context; } - private static void applyAuthenticatedConfiguration( - AnnotationConfigServletWebServerApplicationContext context) { + private static void applyAuthenticatedConfiguration(AnnotationConfigServletWebServerApplicationContext context) { context.register(AuthenticatedConfiguration.class); } @Test public void responseToOptionsRequestIncludesCorsHeaders() { - load(TestEndpointConfiguration.class, (client) -> client.options().uri("/test") - .accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST") - .header("Origin", "https://example.com").exchange().expectStatus().isOk() - .expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com") - .expectHeader().valueEquals("Access-Control-Allow-Methods", "GET,POST")); + load(TestEndpointConfiguration.class, + (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") + .exchange().expectStatus().isOk().expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test public void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { - byte[] responseBody = client.get().uri("/resource") - .header("Range", "bytes=0-3").exchange().expectStatus() + byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .returnResult(byte[].class).getResponseBodyContent(); + .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3); }); } @@ -122,8 +119,7 @@ public class MvcWebEndpointIntegrationTests extends AnnotationConfigServletWebServerApplicationContext context = createApplicationContext(); context.register(TestEndpointConfiguration.class); context.refresh(); - WebMvcEndpointHandlerMapping bean = context - .getBean(WebMvcEndpointHandlerMapping.class); + WebMvcEndpointHandlerMapping bean = context.getBean(WebMvcEndpointHandlerMapping.class); return bean.match(request, "/spring"); } @@ -133,8 +129,7 @@ public class MvcWebEndpointIntegrationTests extends } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class }) static class WebMvcConfiguration { @@ -145,16 +140,13 @@ public class MvcWebEndpointIntegrationTests extends } @Bean - public WebMvcEndpointHandlerMapping webEndpointHandlerMapping( - Environment environment, WebEndpointDiscoverer endpointDiscoverer, - EndpointMediaTypes endpointMediaTypes) { + public WebMvcEndpointHandlerMapping webEndpointHandlerMapping(Environment environment, + WebEndpointDiscoverer endpointDiscoverer, EndpointMediaTypes endpointMediaTypes) { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedOrigins(Arrays.asList("https://example.com")); corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST")); - return new WebMvcEndpointHandlerMapping( - new EndpointMapping(environment.getProperty("endpointPath")), - endpointDiscoverer.getEndpoints(), endpointMediaTypes, - corsConfiguration, + return new WebMvcEndpointHandlerMapping(new EndpointMapping(environment.getProperty("endpointPath")), + endpointDiscoverer.getEndpoints(), endpointMediaTypes, corsConfiguration, new EndpointLinksResolver(endpointDiscoverer.getEndpoints())); } @@ -168,17 +160,14 @@ public class MvcWebEndpointIntegrationTests extends return new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(new UsernamePasswordAuthenticationToken( - "Alice", "secret", + context.setAuthentication(new UsernamePasswordAuthenticationToken("Alice", "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR")))); SecurityContextHolder.setContext(context); try { - filterChain.doFilter(new SecurityContextHolderAwareRequestWrapper( - request, "ROLE_"), response); + filterChain.doFilter(new SecurityContextHolderAwareRequestWrapper(request, "ROLE_"), response); } finally { SecurityContextHolder.clearContext(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java index 48dbe4f34f9..fe1c40c6a9e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java @@ -45,16 +45,14 @@ public class WebMvcTagsTests { this.request.setAttribute( "org.springframework.data.rest.webmvc.RepositoryRestHandlerMapping.EFFECTIVE_REPOSITORY_RESOURCE_LOOKUP_PATH", new PathPatternParser().parse("/api/cities")); - this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - "/api/{repository}"); + this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/{repository}"); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("/api/cities"); } @Test public void uriTagValueIsBestMatchingPatternWhenAvailable() { - this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - "/spring"); + this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/spring"); this.response.setStatus(301); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("/spring"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java index abef8fd38e4..2d9b2f5deef 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java @@ -54,8 +54,8 @@ abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { private final TestContext testContext; - protected AbstractWebEndpointRunner(Class testClass, String name, - ContextFactory contextFactory) throws InitializationError { + protected AbstractWebEndpointRunner(Class testClass, String name, ContextFactory contextFactory) + throws InitializationError { super(testClass); this.name = name; this.testContext = new TestContext(testClass, contextFactory); @@ -104,8 +104,7 @@ abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { } @Override - protected Statement withBefores(FrameworkMethod method, Object target, - Statement statement) { + protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { Statement delegate = super.withBefores(method, target, statement); return new Statement() { @@ -119,8 +118,7 @@ abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { } @Override - protected Statement withAfters(FrameworkMethod method, Object target, - Statement statement) { + protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) { Statement delegate = super.withAfters(method, target, statement); return new Statement() { @@ -175,37 +173,33 @@ abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { private ConfigurableApplicationContext createApplicationContext() { Class[] members = this.testClass.getDeclaredClasses(); - List> configurationClasses = Stream.of(members) - .filter(this::isConfiguration).collect(Collectors.toList()); - return this.contextFactory - .createContext(new ArrayList<>(configurationClasses)); + List> configurationClasses = Stream.of(members).filter(this::isConfiguration) + .collect(Collectors.toList()); + return this.contextFactory.createContext(new ArrayList<>(configurationClasses)); } private boolean isConfiguration(Class candidate) { - return MergedAnnotations.from(candidate, SearchStrategy.EXHAUSTIVE) - .isPresent(Configuration.class); + return MergedAnnotations.from(candidate, SearchStrategy.EXHAUSTIVE).isPresent(Configuration.class); } private WebTestClient createWebTestClient() { DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( "http://localhost:" + determinePort()); uriBuilderFactory.setEncodingMode(EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory) - .responseTimeout(TIMEOUT).build(); + return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(TIMEOUT).build(); } private int determinePort() { if (this.applicationContext instanceof AnnotationConfigServletWebServerApplicationContext) { - return ((AnnotationConfigServletWebServerApplicationContext) this.applicationContext) - .getWebServer().getPort(); + return ((AnnotationConfigServletWebServerApplicationContext) this.applicationContext).getWebServer() + .getPort(); } return this.applicationContext.getBean(PortHolder.class).getPort(); } private void injectIfPossible(Class target, Object value) { ReflectionUtils.doWithFields(target, (field) -> { - if (Modifier.isStatic(field.getModifiers()) - && field.getType().isInstance(value)) { + if (Modifier.isStatic(field.getModifiers()) && field.getType().isInstance(value)) { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, null, value); } @@ -214,16 +208,13 @@ abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { private void capturePropertySources() { this.propertySources = new ArrayList<>(); - this.applicationContext.getEnvironment().getPropertySources() - .forEach(this.propertySources::add); + this.applicationContext.getEnvironment().getPropertySources().forEach(this.propertySources::add); } private void restorePropertySources() { List names = new ArrayList<>(); - MutablePropertySources propertySources = this.applicationContext - .getEnvironment().getPropertySources(); - propertySources - .forEach((propertySource) -> names.add(propertySource.getName())); + MutablePropertySources propertySources = this.applicationContext.getEnvironment().getPropertySources(); + propertySources.forEach((propertySource) -> names.add(propertySource.getName())); names.forEach(propertySources::remove); this.propertySources.forEach(propertySources::addLast); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java index 2579c484384..7f8e7d398fa 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java @@ -69,8 +69,7 @@ class JerseyEndpointsRunner extends AbstractWebEndpointRunner { } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - JerseyAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, JerseyAutoConfiguration.class }) static class JerseyEndpointConfiguration { private final ApplicationContext applicationContext; @@ -95,18 +94,14 @@ class JerseyEndpointsRunner extends AbstractWebEndpointRunner { } private void customize(ResourceConfig config) { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON, - ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, - mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer( - this.applicationContext, new ConversionServiceParameterValueMapper(), - endpointMediaTypes, null, Collections.emptyList(), + List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON, ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), Collections.emptyList()); - Collection resources = new JerseyEndpointResourceFactory() - .createEndpointResources(new EndpointMapping("/actuator"), - discoverer.getEndpoints(), endpointMediaTypes, - new EndpointLinksResolver(discoverer.getEndpoints())); + Collection resources = new JerseyEndpointResourceFactory().createEndpointResources( + new EndpointMapping("/actuator"), discoverer.getEndpoints(), endpointMediaTypes, + new EndpointLinksResolver(discoverer.getEndpoints())); config.registerResources(new HashSet<>(resources)); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java index 72893d7a9e5..88ce60914a2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class WebEndpointRunners extends Suite { super(testClass, createRunners(testClass)); } - private static List createRunners(Class testClass) - throws InitializationError { + private static List createRunners(Class testClass) throws InitializationError { List runners = new ArrayList<>(); runners.add(new WebFluxEndpointsRunner(testClass)); runners.add(new WebMvcEndpointRunner(testClass)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java index 80fd9c3be1b..9c5a17633f2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java @@ -68,10 +68,8 @@ class WebFluxEndpointsRunner extends AbstractWebEndpointRunner { } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - WebFluxAutoConfiguration.class }) - static class WebFluxEndpointConfiguration - implements ApplicationListener { + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, WebFluxAutoConfiguration.class }) + static class WebFluxEndpointConfiguration implements ApplicationListener { private final ApplicationContext applicationContext; @@ -103,18 +101,13 @@ class WebFluxEndpointsRunner extends AbstractWebEndpointRunner { @Bean public WebFluxEndpointHandlerMapping webEndpointReactiveHandlerMapping() { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, - ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, - mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer( - this.applicationContext, new ConversionServiceParameterValueMapper(), - endpointMediaTypes, null, Collections.emptyList(), + List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), Collections.emptyList()); - return new WebFluxEndpointHandlerMapping(new EndpointMapping("/actuator"), - discoverer.getEndpoints(), endpointMediaTypes, - new CorsConfiguration(), - new EndpointLinksResolver(discoverer.getEndpoints())); + return new WebFluxEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), + endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java index 25c9a58c1ba..947bcb4116a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java @@ -66,9 +66,8 @@ class WebMvcEndpointRunner extends AbstractWebEndpointRunner { } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) static class WebMvcEndpointConfiguration { private final ApplicationContext applicationContext; @@ -84,18 +83,13 @@ class WebMvcEndpointRunner extends AbstractWebEndpointRunner { @Bean public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping() { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, - ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, - mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer( - this.applicationContext, new ConversionServiceParameterValueMapper(), - endpointMediaTypes, null, Collections.emptyList(), + List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), Collections.emptyList()); - return new WebMvcEndpointHandlerMapping(new EndpointMapping("/actuator"), - discoverer.getEndpoints(), endpointMediaTypes, - new CorsConfiguration(), - new EndpointLinksResolver(discoverer.getEndpoints())); + return new WebMvcEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), + endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java index 8a789ca0a54..7a891e65545 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java @@ -60,12 +60,9 @@ public class EnvironmentEndpointTests { @Test public void basicResponse() { ConfigurableEnvironment environment = emptyEnvironment(); - environment.getPropertySources() - .addLast(singleKeyPropertySource("one", "my.key", "first")); - environment.getPropertySources() - .addLast(singleKeyPropertySource("two", "my.key", "second")); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); + environment.getPropertySources().addLast(singleKeyPropertySource("one", "my.key", "first")); + environment.getPropertySources().addLast(singleKeyPropertySource("two", "my.key", "second")); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); assertThat(descriptor.getActiveProfiles()).isEmpty(); Map sources = propertySources(descriptor); assertThat(sources.keySet()).containsExactly("one", "two"); @@ -77,43 +74,30 @@ public class EnvironmentEndpointTests { public void compositeSourceIsHandledCorrectly() { ConfigurableEnvironment environment = emptyEnvironment(); CompositePropertySource source = new CompositePropertySource("composite"); - source.addPropertySource( - new MapPropertySource("one", Collections.singletonMap("foo", "bar"))); - source.addPropertySource( - new MapPropertySource("two", Collections.singletonMap("foo", "spam"))); + source.addPropertySource(new MapPropertySource("one", Collections.singletonMap("foo", "bar"))); + source.addPropertySource(new MapPropertySource("two", Collections.singletonMap("foo", "spam"))); environment.getPropertySources().addFirst(source); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); Map sources = propertySources(descriptor); assertThat(sources.keySet()).containsExactly("composite:one", "composite:two"); - assertThat(sources.get("composite:one").getProperties().get("foo").getValue()) - .isEqualTo("bar"); - assertThat(sources.get("composite:two").getProperties().get("foo").getValue()) - .isEqualTo("spam"); + assertThat(sources.get("composite:one").getProperties().get("foo").getValue()).isEqualTo("bar"); + assertThat(sources.get("composite:two").getProperties().get("foo").getValue()).isEqualTo("spam"); } @Test public void sensitiveKeysHaveTheirValuesSanitized() { - TestPropertyValues - .of("dbPassword=123456", "apiKey=123456", "mySecret=123456", - "myCredentials=123456", "VCAP_SERVICES=123456") - .applyToSystemProperties(() -> { - EnvironmentDescriptor descriptor = new EnvironmentEndpoint( - new StandardEnvironment()).environment(null); - Map systemProperties = propertySources( - descriptor).get("systemProperties").getProperties(); - assertThat(systemProperties.get("dbPassword").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("apiKey").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("mySecret").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("myCredentials").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("VCAP_SERVICES").getValue()) - .isEqualTo("******"); - PropertyValueDescriptor command = systemProperties - .get("sun.java.command"); + TestPropertyValues.of("dbPassword=123456", "apiKey=123456", "mySecret=123456", "myCredentials=123456", + "VCAP_SERVICES=123456").applyToSystemProperties(() -> { + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()) + .environment(null); + Map systemProperties = propertySources(descriptor) + .get("systemProperties").getProperties(); + assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("mySecret").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("myCredentials").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("VCAP_SERVICES").getValue()).isEqualTo("******"); + PropertyValueDescriptor command = systemProperties.get("sun.java.command"); if (command != null) { assertThat(command.getValue()).isEqualTo("******"); } @@ -123,119 +107,96 @@ public class EnvironmentEndpointTests { @Test public void sensitiveKeysMatchingCredentialsPatternHaveTheirValuesSanitized() { - TestPropertyValues.of("my.services.amqp-free.credentials.uri=123456", - "credentials.http_api_uri=123456", - "my.services.cleardb-free.credentials=123456", - "foo.mycredentials.uri=123456").applyToSystemProperties(() -> { - EnvironmentDescriptor descriptor = new EnvironmentEndpoint( - new StandardEnvironment()).environment(null); - Map systemProperties = propertySources( - descriptor).get("systemProperties").getProperties(); - assertThat(systemProperties - .get("my.services.amqp-free.credentials.uri").getValue()) - .isEqualTo("******"); - assertThat( - systemProperties.get("credentials.http_api_uri").getValue()) - .isEqualTo("******"); - assertThat(systemProperties - .get("my.services.cleardb-free.credentials").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("foo.mycredentials.uri").getValue()) + TestPropertyValues + .of("my.services.amqp-free.credentials.uri=123456", "credentials.http_api_uri=123456", + "my.services.cleardb-free.credentials=123456", "foo.mycredentials.uri=123456") + .applyToSystemProperties(() -> { + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()) + .environment(null); + Map systemProperties = propertySources(descriptor) + .get("systemProperties").getProperties(); + assertThat(systemProperties.get("my.services.amqp-free.credentials.uri").getValue()) .isEqualTo("******"); + assertThat(systemProperties.get("credentials.http_api_uri").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("my.services.cleardb-free.credentials").getValue()) + .isEqualTo("******"); + assertThat(systemProperties.get("foo.mycredentials.uri").getValue()).isEqualTo("******"); return null; }); } @Test public void sensitiveKeysMatchingCustomNameHaveTheirValuesSanitized() { - TestPropertyValues.of("dbPassword=123456", "apiKey=123456") - .applyToSystemProperties(() -> { - EnvironmentEndpoint endpoint = new EnvironmentEndpoint( - new StandardEnvironment()); - endpoint.setKeysToSanitize("key"); - EnvironmentDescriptor descriptor = endpoint.environment(null); - Map systemProperties = propertySources( - descriptor).get("systemProperties").getProperties(); - assertThat(systemProperties.get("dbPassword").getValue()) - .isEqualTo("123456"); - assertThat(systemProperties.get("apiKey").getValue()) - .isEqualTo("******"); - return null; - }); + TestPropertyValues.of("dbPassword=123456", "apiKey=123456").applyToSystemProperties(() -> { + EnvironmentEndpoint endpoint = new EnvironmentEndpoint(new StandardEnvironment()); + endpoint.setKeysToSanitize("key"); + EnvironmentDescriptor descriptor = endpoint.environment(null); + Map systemProperties = propertySources(descriptor).get("systemProperties") + .getProperties(); + assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("123456"); + assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******"); + return null; + }); } @Test public void sensitiveKeysMatchingCustomPatternHaveTheirValuesSanitized() { - TestPropertyValues.of("dbPassword=123456", "apiKey=123456") - .applyToSystemProperties(() -> { - EnvironmentEndpoint endpoint = new EnvironmentEndpoint( - new StandardEnvironment()); - endpoint.setKeysToSanitize(".*pass.*"); - EnvironmentDescriptor descriptor = endpoint.environment(null); - Map systemProperties = propertySources( - descriptor).get("systemProperties").getProperties(); - assertThat(systemProperties.get("dbPassword").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("apiKey").getValue()) - .isEqualTo("123456"); - return null; - }); + TestPropertyValues.of("dbPassword=123456", "apiKey=123456").applyToSystemProperties(() -> { + EnvironmentEndpoint endpoint = new EnvironmentEndpoint(new StandardEnvironment()); + endpoint.setKeysToSanitize(".*pass.*"); + EnvironmentDescriptor descriptor = endpoint.environment(null); + Map systemProperties = propertySources(descriptor).get("systemProperties") + .getProperties(); + assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("123456"); + return null; + }); } @Test public void propertyWithPlaceholderResolved() { ConfigurableEnvironment environment = emptyEnvironment(); - TestPropertyValues.of("my.foo: ${bar.blah}", "bar.blah: hello") - .applyTo(environment); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); - assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo") - .getValue()).isEqualTo("hello"); + TestPropertyValues.of("my.foo: ${bar.blah}", "bar.blah: hello").applyTo(environment); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); + assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()).isEqualTo("hello"); } @Test public void propertyWithPlaceholderNotResolved() { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: ${bar.blah}").applyTo(environment); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); - assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo") - .getValue()).isEqualTo("${bar.blah}"); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); + assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) + .isEqualTo("${bar.blah}"); } @Test public void propertyWithSensitivePlaceholderResolved() { ConfigurableEnvironment environment = emptyEnvironment(); - TestPropertyValues - .of("my.foo: http://${bar.password}://hello", "bar.password: hello") - .applyTo(environment); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); - assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo") - .getValue()).isEqualTo("http://******://hello"); + TestPropertyValues.of("my.foo: http://${bar.password}://hello", "bar.password: hello").applyTo(environment); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); + assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) + .isEqualTo("http://******://hello"); } @Test public void propertyWithSensitivePlaceholderNotResolved() { ConfigurableEnvironment environment = emptyEnvironment(); - TestPropertyValues.of("my.foo: http://${bar.password}://hello") - .applyTo(environment); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); - assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo") - .getValue()).isEqualTo("http://${bar.password}://hello"); + TestPropertyValues.of("my.foo: http://${bar.password}://hello").applyTo(environment); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); + assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) + .isEqualTo("http://${bar.password}://hello"); } @Test @SuppressWarnings("unchecked") public void propertyWithTypeOtherThanStringShouldNotFail() { ConfigurableEnvironment environment = emptyEnvironment(); - environment.getPropertySources().addFirst(singleKeyPropertySource("test", "foo", - Collections.singletonMap("bar", "baz"))); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); - Map foo = (Map) propertySources(descriptor) - .get("test").getProperties().get("foo").getValue(); + environment.getPropertySources() + .addFirst(singleKeyPropertySource("test", "foo", Collections.singletonMap("bar", "baz"))); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); + Map foo = (Map) propertySources(descriptor).get("test").getProperties() + .get("foo").getValue(); assertThat(foo.get("bar")).isEqualTo("baz"); } @@ -243,23 +204,18 @@ public class EnvironmentEndpointTests { public void propertyEntry() { TestPropertyValues.of("my.foo=another").applyToSystemProperties(() -> { StandardEnvironment environment = new StandardEnvironment(); - TestPropertyValues.of("my.foo=bar", "my.foo2=bar2").applyTo(environment, - TestPropertyValues.Type.MAP, "test"); - EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment) - .environmentEntry("my.foo"); + TestPropertyValues.of("my.foo=bar", "my.foo2=bar2").applyTo(environment, TestPropertyValues.Type.MAP, + "test"); + EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment).environmentEntry("my.foo"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getProperty()).isNotNull(); assertThat(descriptor.getProperty().getSource()).isEqualTo("test"); assertThat(descriptor.getProperty().getValue()).isEqualTo("bar"); - Map sources = propertySources( - descriptor); - assertThat(sources.keySet()).containsExactly("test", "systemProperties", - "systemEnvironment"); + Map sources = propertySources(descriptor); + assertThat(sources.keySet()).containsExactly("test", "systemProperties", "systemEnvironment"); assertPropertySourceEntryDescriptor(sources.get("test"), "bar", null); - assertPropertySourceEntryDescriptor(sources.get("systemProperties"), - "another", null); - assertPropertySourceEntryDescriptor(sources.get("systemEnvironment"), null, - null); + assertPropertySourceEntryDescriptor(sources.get("systemProperties"), "another", null); + assertPropertySourceEntryDescriptor(sources.get("systemEnvironment"), null, null); return null; }); } @@ -267,10 +223,8 @@ public class EnvironmentEndpointTests { @Test public void propertyEntryNotFound() { ConfigurableEnvironment environment = emptyEnvironment(); - environment.getPropertySources() - .addFirst(singleKeyPropertySource("test", "foo", "bar")); - EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment) - .environmentEntry("does.not.exist"); + environment.getPropertySources().addFirst(singleKeyPropertySource("test", "foo", "bar")); + EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment).environmentEntry("does.not.exist"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getProperty()).isNull(); Map sources = propertySources(descriptor); @@ -281,50 +235,40 @@ public class EnvironmentEndpointTests { @Test public void multipleSourcesWithSameProperty() { ConfigurableEnvironment environment = emptyEnvironment(); - environment.getPropertySources() - .addFirst(singleKeyPropertySource("one", "a", "alpha")); - environment.getPropertySources() - .addFirst(singleKeyPropertySource("two", "a", "apple")); - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment) - .environment(null); + environment.getPropertySources().addFirst(singleKeyPropertySource("one", "a", "alpha")); + environment.getPropertySources().addFirst(singleKeyPropertySource("two", "a", "apple")); + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); Map sources = propertySources(descriptor); assertThat(sources.keySet()).containsExactly("two", "one"); - assertThat(sources.get("one").getProperties().get("a").getValue()) - .isEqualTo("alpha"); - assertThat(sources.get("two").getProperties().get("a").getValue()) - .isEqualTo("apple"); + assertThat(sources.get("one").getProperties().get("a").getValue()).isEqualTo("alpha"); + assertThat(sources.get("two").getProperties().get("a").getValue()).isEqualTo("apple"); } private static ConfigurableEnvironment emptyEnvironment() { StandardEnvironment environment = new StandardEnvironment(); - environment.getPropertySources() - .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); - environment.getPropertySources() - .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment.getPropertySources().remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + environment.getPropertySources().remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); return environment; } - private MapPropertySource singleKeyPropertySource(String name, String key, - Object value) { + private MapPropertySource singleKeyPropertySource(String name, String key, Object value) { return new MapPropertySource(name, Collections.singletonMap(key, value)); } - private Map propertySources( - EnvironmentDescriptor descriptor) { + private Map propertySources(EnvironmentDescriptor descriptor) { Map sources = new LinkedHashMap<>(); descriptor.getPropertySources().forEach((d) -> sources.put(d.getName(), d)); return sources; } - private Map propertySources( - EnvironmentEntryDescriptor descriptor) { + private Map propertySources(EnvironmentEntryDescriptor descriptor) { Map sources = new LinkedHashMap<>(); descriptor.getPropertySources().forEach((d) -> sources.put(d.getName(), d)); return sources; } - private void assertPropertySourceEntryDescriptor(PropertySourceEntryDescriptor actual, - Object value, String origin) { + private void assertPropertySourceEntryDescriptor(PropertySourceEntryDescriptor actual, Object value, + String origin) { assertThat(actual).isNotNull(); if (value != null) { assertThat(actual.getProperty().getValue()).isEqualTo(value); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java index 1933b9da0e5..5f9f033b331 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java @@ -52,31 +52,28 @@ public class EnvironmentEndpointWebIntegrationTests { @Test public void sub() { - client.get().uri("/actuator/env/foo").exchange().expectStatus().isOk() - .expectBody().jsonPath("property.source").isEqualTo("test") - .jsonPath("property.value").isEqualTo("bar"); + client.get().uri("/actuator/env/foo").exchange().expectStatus().isOk().expectBody().jsonPath("property.source") + .isEqualTo("test").jsonPath("property.value").isEqualTo("bar"); } @Test public void regex() { Map map = new HashMap<>(); map.put("food", null); - EnvironmentEndpointWebIntegrationTests.context.getEnvironment() - .getPropertySources().addFirst(new MapPropertySource("null-value", map)); - client.get().uri("/actuator/env?pattern=foo.*").exchange().expectStatus().isOk() - .expectBody().jsonPath(forProperty("test", "foo")).isEqualTo("bar") - .jsonPath(forProperty("test", "fool")).isEqualTo("baz"); + EnvironmentEndpointWebIntegrationTests.context.getEnvironment().getPropertySources() + .addFirst(new MapPropertySource("null-value", map)); + client.get().uri("/actuator/env?pattern=foo.*").exchange().expectStatus().isOk().expectBody() + .jsonPath(forProperty("test", "foo")).isEqualTo("bar").jsonPath(forProperty("test", "fool")) + .isEqualTo("baz"); } @Test public void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("unresolved-placeholder", map)); - client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk() - .expectBody().jsonPath("property.value").isEqualTo("${my.bar}") - .jsonPath(forPropertyEntry("unresolved-placeholder")) + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("unresolved-placeholder", map)); + client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() + .jsonPath("property.value").isEqualTo("${my.bar}").jsonPath(forPropertyEntry("unresolved-placeholder")) .isEqualTo("${my.bar}"); } @@ -85,18 +82,16 @@ public class EnvironmentEndpointWebIntegrationTests { Map map = new HashMap<>(); map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); - context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("placeholder", map)); - client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk() - .expectBody().jsonPath("property.value").isEqualTo("******") - .jsonPath(forPropertyEntry("placeholder")).isEqualTo("******"); + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); + client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() + .jsonPath("property.value").isEqualTo("******").jsonPath(forPropertyEntry("placeholder")) + .isEqualTo("******"); } @Test public void nestedPathForUnknownKeyShouldReturn404AndBody() { - client.get().uri("/actuator/env/this.does.not.exist").exchange().expectStatus() - .isNotFound().expectBody().jsonPath("property").doesNotExist() - .jsonPath("propertySources[?(@.name=='test')]").exists() + client.get().uri("/actuator/env/this.does.not.exist").exchange().expectStatus().isNotFound().expectBody() + .jsonPath("property").doesNotExist().jsonPath("propertySources[?(@.name=='test')]").exists() .jsonPath("propertySources[?(@.name=='systemProperties')]").exists() .jsonPath("propertySources[?(@.name=='systemEnvironment')]").exists(); } @@ -105,12 +100,9 @@ public class EnvironmentEndpointWebIntegrationTests { public void nestedPathMatchedByRegexWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("unresolved-placeholder", map)); - client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk() - .expectBody() - .jsonPath( - "propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("unresolved-placeholder", map)); + client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() + .jsonPath("propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") .isEqualTo("${my.bar}"); } @@ -119,16 +111,13 @@ public class EnvironmentEndpointWebIntegrationTests { Map map = new HashMap<>(); map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); - context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("placeholder", map)); - client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk() - .expectBody().jsonPath(forProperty("placeholder", "my.foo")) - .isEqualTo("******"); + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); + client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() + .jsonPath(forProperty("placeholder", "my.foo")).isEqualTo("******"); } private String forProperty(String source, String name) { - return "propertySources[?(@.name=='" + source + "')].properties.['" + name - + "'].value"; + return "propertySources[?(@.name=='" + source + "')].properties.['" + name + "'].value"; } private String forPropertyEntry(String source) { @@ -144,8 +133,7 @@ public class EnvironmentEndpointWebIntegrationTests { } @Bean - public EnvironmentEndpointWebExtension environmentEndpointWebExtension( - EnvironmentEndpoint endpoint) { + public EnvironmentEndpointWebExtension environmentEndpointWebExtension(EnvironmentEndpoint endpoint) { return new EnvironmentEndpointWebExtension(endpoint); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java index 022401c84de..9eb805a64c2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java @@ -40,15 +40,13 @@ public class FlywayEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withBean("endpoint", FlywayEndpoint.class); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class).withBean("endpoint", FlywayEndpoint.class); @Test public void flywayReportIsProduced() { this.contextRunner.run((context) -> { - Map flywayBeans = context - .getBean(FlywayEndpoint.class).flywayBeans().getContexts() - .get(context.getId()).getFlywayBeans(); + Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() + .getContexts().get(context.getId()).getFlywayBeans(); assertThat(flywayBeans).hasSize(1); assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); }); @@ -62,9 +60,8 @@ public class FlywayEndpointTests { flyway.baseline(); flyway.migrate(); }).run((context) -> { - Map flywayBeans = context - .getBean(FlywayEndpoint.class).flywayBeans().getContexts() - .get(context.getId()).getFlywayBeans(); + Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() + .getContexts().get(context.getId()).getFlywayBeans(); assertThat(flywayBeans).hasSize(1); assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); }); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java index 773ea6ffa36..a7c990213b2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java @@ -49,10 +49,8 @@ public class CompositeHealthIndicatorTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - given(this.one.health()) - .willReturn(new Health.Builder().unknown().withDetail("1", "1").build()); - given(this.two.health()) - .willReturn(new Health.Builder().unknown().withDetail("2", "2").build()); + given(this.one.health()).willReturn(new Health.Builder().unknown().withDetail("1", "1").build()); + given(this.two.health()).willReturn(new Health.Builder().unknown().withDetail("2", "2").build()); this.healthAggregator = new OrderedHealthAggregator(); } @@ -62,8 +60,7 @@ public class CompositeHealthIndicatorTests { Map indicators = new HashMap<>(); indicators.put("one", this.one); indicators.put("two", this.two); - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator, indicators); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator, indicators); Health result = composite.health(); assertThat(result.getDetails()).hasSize(2); assertThat(result.getDetails()).containsEntry("one", @@ -77,17 +74,15 @@ public class CompositeHealthIndicatorTests { Map indicators = new HashMap<>(); indicators.put("db1", this.one); indicators.put("db2", this.two); - CompositeHealthIndicator innerComposite = new CompositeHealthIndicator( - this.healthAggregator, indicators); - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator, Collections.singletonMap("db", innerComposite)); + CompositeHealthIndicator innerComposite = new CompositeHealthIndicator(this.healthAggregator, indicators); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator, + Collections.singletonMap("db", innerComposite)); Health result = composite.health(); ObjectMapper mapper = new ObjectMapper(); - assertThat(mapper.writeValueAsString(result)).isEqualTo( - "{\"status\":\"UNKNOWN\",\"details\":{\"db\":{\"status\":\"UNKNOWN\"" + assertThat(mapper.writeValueAsString(result)) + .isEqualTo("{\"status\":\"UNKNOWN\",\"details\":{\"db\":{\"status\":\"UNKNOWN\"" + ",\"details\":{\"db1\":{\"status\":\"UNKNOWN\",\"details\"" - + ":{\"1\":\"1\"}},\"db2\":{\"status\":\"UNKNOWN\",\"details\"" - + ":{\"2\":\"2\"}}}}}}"); + + ":{\"1\":\"1\"}},\"db2\":{\"status\":\"UNKNOWN\",\"details\"" + ":{\"2\":\"2\"}}}}}}"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java index f945bdf486b..c18ca8aca45 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java @@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class CompositeReactiveHealthIndicatorTests { - private static final Health UNKNOWN_HEALTH = Health.unknown() - .withDetail("detail", "value").build(); + private static final Health UNKNOWN_HEALTH = Health.unknown().withDetail("detail", "value").build(); private static final Health HEALTHY = Health.up().build(); @@ -43,9 +42,8 @@ public class CompositeReactiveHealthIndicatorTests { @Test public void singleIndicator() { - CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator( - this.healthAggregator, new DefaultReactiveHealthIndicatorRegistry( - Collections.singletonMap("test", () -> Mono.just(HEALTHY)))); + CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator(this.healthAggregator, + new DefaultReactiveHealthIndicatorRegistry(Collections.singletonMap("test", () -> Mono.just(HEALTHY)))); StepVerifier.create(indicator.health()).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).containsOnlyKeys("test"); @@ -59,11 +57,10 @@ public class CompositeReactiveHealthIndicatorTests { for (int i = 0; i < 50; i++) { indicators.put("test" + i, new TimeoutHealth(10000, Status.UP)); } - CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator( - this.healthAggregator, + CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator(this.healthAggregator, new DefaultReactiveHealthIndicatorRegistry(indicators)); - StepVerifier.withVirtualTime(indicator::health).expectSubscription() - .thenAwait(Duration.ofMillis(10000)).consumeNextWith((h) -> { + StepVerifier.withVirtualTime(indicator::health).expectSubscription().thenAwait(Duration.ofMillis(10000)) + .consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).hasSize(50); }).verifyComplete(); @@ -75,10 +72,8 @@ public class CompositeReactiveHealthIndicatorTests { Map indicators = new HashMap<>(); indicators.put("slow", new TimeoutHealth(10000, Status.UP)); indicators.put("fast", new TimeoutHealth(10, Status.UP)); - CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator( - this.healthAggregator, - new DefaultReactiveHealthIndicatorRegistry(indicators)) - .timeoutStrategy(100, UNKNOWN_HEALTH); + CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator(this.healthAggregator, + new DefaultReactiveHealthIndicatorRegistry(indicators)).timeoutStrategy(100, UNKNOWN_HEALTH); StepVerifier.create(indicator.health()).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).containsOnlyKeys("slow", "fast"); @@ -92,12 +87,10 @@ public class CompositeReactiveHealthIndicatorTests { Map indicators = new HashMap<>(); indicators.put("slow", new TimeoutHealth(10000, Status.UP)); indicators.put("fast", new TimeoutHealth(10, Status.UP)); - CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator( - this.healthAggregator, - new DefaultReactiveHealthIndicatorRegistry(indicators)) - .timeoutStrategy(20000, null); - StepVerifier.withVirtualTime(indicator::health).expectSubscription() - .thenAwait(Duration.ofMillis(10000)).consumeNextWith((h) -> { + CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator(this.healthAggregator, + new DefaultReactiveHealthIndicatorRegistry(indicators)).timeoutStrategy(20000, null); + StepVerifier.withVirtualTime(indicator::health).expectSubscription().thenAwait(Duration.ofMillis(10000)) + .consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).containsOnlyKeys("slow", "fast"); assertThat(h.getDetails().get("slow")).isEqualTo(HEALTHY); @@ -118,8 +111,7 @@ public class CompositeReactiveHealthIndicatorTests { @Override public Mono health() { - return Mono.delay(Duration.ofMillis(this.timeout)) - .map((l) -> Health.status(this.status).build()); + return Mono.delay(Duration.ofMillis(this.timeout)).map((l) -> Health.status(this.status).build()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java index 5024074862d..3f38d58b863 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java @@ -43,10 +43,8 @@ public class DefaultHealthIndicatorRegistryTests { @BeforeEach public void setUp() { - given(this.one.health()) - .willReturn(new Health.Builder().unknown().withDetail("1", "1").build()); - given(this.two.health()) - .willReturn(new Health.Builder().unknown().withDetail("2", "2").build()); + given(this.one.health()).willReturn(new Health.Builder().unknown().withDetail("1", "1").build()); + given(this.two.health()).willReturn(new Health.Builder().unknown().withDetail("2", "2").build()); this.registry = new DefaultHealthIndicatorRegistry(); } @@ -62,10 +60,8 @@ public class DefaultHealthIndicatorRegistryTests { @Test public void registerAlreadyUsedName() { this.registry.register("one", this.one); - assertThatIllegalStateException() - .isThrownBy(() -> this.registry.register("one", this.two)) - .withMessageContaining( - "HealthIndicator with name 'one' already registered"); + assertThatIllegalStateException().isThrownBy(() -> this.registry.register("one", this.two)) + .withMessageContaining("HealthIndicator with name 'one' already registered"); } @Test @@ -100,8 +96,7 @@ public class DefaultHealthIndicatorRegistryTests { public void getAllIsImmutable() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); - assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(snapshot::clear); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(snapshot::clear); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java index 47f9fe4025d..5e584c0579e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java @@ -44,10 +44,8 @@ public class DefaultReactiveHealthIndicatorRegistryTests { @BeforeEach public void setUp() { - given(this.one.health()).willReturn( - Mono.just(new Health.Builder().unknown().withDetail("1", "1").build())); - given(this.two.health()).willReturn( - Mono.just(new Health.Builder().unknown().withDetail("2", "2").build())); + given(this.one.health()).willReturn(Mono.just(new Health.Builder().unknown().withDetail("1", "1").build())); + given(this.two.health()).willReturn(Mono.just(new Health.Builder().unknown().withDetail("2", "2").build())); this.registry = new DefaultReactiveHealthIndicatorRegistry(); } @@ -63,10 +61,8 @@ public class DefaultReactiveHealthIndicatorRegistryTests { @Test public void registerAlreadyUsedName() { this.registry.register("one", this.one); - assertThatIllegalStateException() - .isThrownBy(() -> this.registry.register("one", this.two)) - .withMessageContaining( - "HealthIndicator with name 'one' already registered"); + assertThatIllegalStateException().isThrownBy(() -> this.registry.register("one", this.two)) + .withMessageContaining("HealthIndicator with name 'one' already registered"); } @Test @@ -101,8 +97,7 @@ public class DefaultReactiveHealthIndicatorRegistryTests { public void getAllIsImmutable() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); - assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(snapshot::clear); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(snapshot::clear); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java index 658bc85334b..ec80e6853f1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java @@ -35,19 +35,18 @@ import static org.assertj.core.api.Assertions.entry; */ public class HealthEndpointTests { - private static final HealthIndicator one = () -> new Health.Builder() - .status(Status.UP).withDetail("first", "1").build(); + private static final HealthIndicator one = () -> new Health.Builder().status(Status.UP).withDetail("first", "1") + .build(); - private static final HealthIndicator two = () -> new Health.Builder() - .status(Status.UP).withDetail("second", "2").build(); + private static final HealthIndicator two = () -> new Health.Builder().status(Status.UP).withDetail("second", "2") + .build(); @Test public void statusAndFullDetailsAreExposed() { Map healthIndicators = new HashMap<>(); healthIndicators.put("up", one); healthIndicators.put("upAgain", two); - HealthEndpoint endpoint = new HealthEndpoint( - createHealthIndicator(healthIndicators)); + HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator(healthIndicators)); Health health = endpoint.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsOnlyKeys("up", "upAgain"); @@ -59,8 +58,7 @@ public class HealthEndpointTests { @Test public void statusForComponentIsExposed() { - HealthEndpoint endpoint = new HealthEndpoint( - createHealthIndicator(Collections.singletonMap("test", one))); + HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator(Collections.singletonMap("test", one))); Health health = endpoint.healthForComponent("test"); assertThat(health).isNotNull(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -69,19 +67,17 @@ public class HealthEndpointTests { @Test public void statusForUnknownComponentReturnNull() { - HealthEndpoint endpoint = new HealthEndpoint( - createHealthIndicator(Collections.emptyMap())); + HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator(Collections.emptyMap())); Health health = endpoint.healthForComponent("does-not-exist"); assertThat(health).isNull(); } @Test public void statusForComponentInstanceIsExposed() { - CompositeHealthIndicator compositeIndicator = new CompositeHealthIndicator( - new OrderedHealthAggregator(), + CompositeHealthIndicator compositeIndicator = new CompositeHealthIndicator(new OrderedHealthAggregator(), Collections.singletonMap("sub", () -> Health.down().build())); - HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator( - Collections.singletonMap("test", compositeIndicator))); + HealthEndpoint endpoint = new HealthEndpoint( + createHealthIndicator(Collections.singletonMap("test", compositeIndicator))); Health health = endpoint.healthForComponentInstance("test", "sub"); assertThat(health).isNotNull(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -90,27 +86,24 @@ public class HealthEndpointTests { @Test public void statusForUnknownComponentInstanceReturnNull() { - CompositeHealthIndicator compositeIndicator = new CompositeHealthIndicator( - new OrderedHealthAggregator(), + CompositeHealthIndicator compositeIndicator = new CompositeHealthIndicator(new OrderedHealthAggregator(), Collections.singletonMap("sub", () -> Health.down().build())); - HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator( - Collections.singletonMap("test", compositeIndicator))); + HealthEndpoint endpoint = new HealthEndpoint( + createHealthIndicator(Collections.singletonMap("test", compositeIndicator))); Health health = endpoint.healthForComponentInstance("test", "does-not-exist"); assertThat(health).isNull(); } @Test public void statusForComponentInstanceThatIsNotACompositeReturnNull() { - HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator( - Collections.singletonMap("test", () -> Health.up().build()))); + HealthEndpoint endpoint = new HealthEndpoint( + createHealthIndicator(Collections.singletonMap("test", () -> Health.up().build()))); Health health = endpoint.healthForComponentInstance("test", "does-not-exist"); assertThat(health).isNull(); } - private HealthIndicator createHealthIndicator( - Map healthIndicators) { - return new CompositeHealthIndicator(new OrderedHealthAggregator(), - healthIndicators); + private HealthIndicator createHealthIndicator(Map healthIndicators) { + return new CompositeHealthIndicator(new OrderedHealthAggregator(), healthIndicators); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java index 8c07f7c3292..5a3470ec827 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java @@ -52,62 +52,51 @@ public class HealthEndpointWebIntegrationTests { @Test public void whenHealthIsUp200ResponseIsReturned() { - client.get().uri("/actuator/health").exchange().expectStatus().isOk().expectBody() - .jsonPath("status").isEqualTo("UP").jsonPath("details.alpha.status") - .isEqualTo("UP").jsonPath("details.bravo.status").isEqualTo("UP"); + client.get().uri("/actuator/health").exchange().expectStatus().isOk().expectBody().jsonPath("status") + .isEqualTo("UP").jsonPath("details.alpha.status").isEqualTo("UP").jsonPath("details.bravo.status") + .isEqualTo("UP"); } @Test public void whenHealthIsDown503ResponseIsReturned() throws Exception { - withHealthIndicator("charlie", () -> Health.down().build(), - () -> Mono.just(Health.down().build()), () -> { - client.get().uri("/actuator/health").exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody() - .jsonPath("status").isEqualTo("DOWN") - .jsonPath("details.alpha.status").isEqualTo("UP") - .jsonPath("details.bravo.status").isEqualTo("UP") - .jsonPath("details.charlie.status").isEqualTo("DOWN"); - return null; - }); + withHealthIndicator("charlie", () -> Health.down().build(), () -> Mono.just(Health.down().build()), () -> { + client.get().uri("/actuator/health").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody().jsonPath("status").isEqualTo("DOWN").jsonPath("details.alpha.status").isEqualTo("UP") + .jsonPath("details.bravo.status").isEqualTo("UP").jsonPath("details.charlie.status") + .isEqualTo("DOWN"); + return null; + }); } @Test public void whenComponentHealthIsDown503ResponseIsReturned() throws Exception { - withHealthIndicator("charlie", () -> Health.down().build(), - () -> Mono.just(Health.down().build()), () -> { - client.get().uri("/actuator/health/charlie").exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody() - .jsonPath("status").isEqualTo("DOWN"); - return null; - }); + withHealthIndicator("charlie", () -> Health.down().build(), () -> Mono.just(Health.down().build()), () -> { + client.get().uri("/actuator/health/charlie").exchange().expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN"); + return null; + }); } @Test - public void whenComponentInstanceHealthIsDown503ResponseIsReturned() - throws Exception { - CompositeHealthIndicator composite = new CompositeHealthIndicator( - new OrderedHealthAggregator(), + public void whenComponentInstanceHealthIsDown503ResponseIsReturned() throws Exception { + CompositeHealthIndicator composite = new CompositeHealthIndicator(new OrderedHealthAggregator(), Collections.singletonMap("one", () -> Health.down().build())); CompositeReactiveHealthIndicator reactiveComposite = new CompositeReactiveHealthIndicator( - new OrderedHealthAggregator(), - new DefaultReactiveHealthIndicatorRegistry(Collections.singletonMap("one", - () -> Mono.just(Health.down().build())))); + new OrderedHealthAggregator(), new DefaultReactiveHealthIndicatorRegistry( + Collections.singletonMap("one", () -> Mono.just(Health.down().build())))); withHealthIndicator("charlie", composite, reactiveComposite, () -> { client.get().uri("/actuator/health/charlie/one").exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody() - .jsonPath("status").isEqualTo("DOWN"); + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN"); return null; }); } private void withHealthIndicator(String name, HealthIndicator healthIndicator, - ReactiveHealthIndicator reactiveHealthIndicator, Callable action) - throws Exception { + ReactiveHealthIndicator reactiveHealthIndicator, Callable action) throws Exception { Consumer unregister; Consumer reactiveUnregister; try { - ReactiveHealthIndicatorRegistry registry = context - .getBean(ReactiveHealthIndicatorRegistry.class); + ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class); registry.register(name, reactiveHealthIndicator); reactiveUnregister = registry::unregister; } @@ -131,8 +120,7 @@ public class HealthEndpointWebIntegrationTests { public void whenHealthIndicatorIsRemovedResponseIsAltered() { Consumer reactiveRegister = null; try { - ReactiveHealthIndicatorRegistry registry = context - .getBean(ReactiveHealthIndicatorRegistry.class); + ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class); ReactiveHealthIndicator unregistered = registry.unregister("bravo"); reactiveRegister = (name) -> registry.register(name, unregistered); } @@ -142,10 +130,9 @@ public class HealthEndpointWebIntegrationTests { HealthIndicatorRegistry registry = context.getBean(HealthIndicatorRegistry.class); HealthIndicator bravo = registry.unregister("bravo"); try { - client.get().uri("/actuator/health").exchange().expectStatus().isOk() - .expectBody().jsonPath("status").isEqualTo("UP") - .jsonPath("details.alpha.status").isEqualTo("UP") - .jsonPath("details.bravo.status").doesNotExist(); + client.get().uri("/actuator/health").exchange().expectStatus().isOk().expectBody().jsonPath("status") + .isEqualTo("UP").jsonPath("details.alpha.status").isEqualTo("UP").jsonPath("details.bravo.status") + .doesNotExist(); } finally { registry.register("bravo", bravo); @@ -159,10 +146,8 @@ public class HealthEndpointWebIntegrationTests { public static class TestConfiguration { @Bean - public HealthIndicatorRegistry healthIndicatorFactory( - Map healthIndicators) { - return new HealthIndicatorRegistryFactory() - .createHealthIndicatorRegistry(healthIndicators); + public HealthIndicatorRegistry healthIndicatorFactory(Map healthIndicators) { + return new HealthIndicatorRegistryFactory().createHealthIndicatorRegistry(healthIndicators); } @Bean @@ -171,24 +156,19 @@ public class HealthEndpointWebIntegrationTests { Map reactiveHealthIndicators, Map healthIndicators) { return new ReactiveHealthIndicatorRegistryFactory() - .createReactiveHealthIndicatorRegistry(reactiveHealthIndicators, - healthIndicators); + .createReactiveHealthIndicatorRegistry(reactiveHealthIndicators, healthIndicators); } @Bean public HealthEndpoint healthEndpoint(HealthIndicatorRegistry registry) { - return new HealthEndpoint(new CompositeHealthIndicator( - new OrderedHealthAggregator(), registry)); + return new HealthEndpoint(new CompositeHealthIndicator(new OrderedHealthAggregator(), registry)); } @Bean @ConditionalOnWebApplication(type = Type.SERVLET) - public HealthEndpointWebExtension healthWebEndpointExtension( - HealthEndpoint healthEndpoint) { - return new HealthEndpointWebExtension(healthEndpoint, - new HealthWebEndpointResponseMapper(new HealthStatusHttpMapper(), - ShowDetails.ALWAYS, - new HashSet<>(Arrays.asList("ACTUATOR")))); + public HealthEndpointWebExtension healthWebEndpointExtension(HealthEndpoint healthEndpoint) { + return new HealthEndpointWebExtension(healthEndpoint, new HealthWebEndpointResponseMapper( + new HealthStatusHttpMapper(), ShowDetails.ALWAYS, new HashSet<>(Arrays.asList("ACTUATOR")))); } @Bean @@ -196,10 +176,8 @@ public class HealthEndpointWebIntegrationTests { public ReactiveHealthEndpointWebExtension reactiveHealthWebEndpointExtension( ReactiveHealthIndicatorRegistry registry, HealthEndpoint healthEndpoint) { return new ReactiveHealthEndpointWebExtension( - new CompositeReactiveHealthIndicator(new OrderedHealthAggregator(), - registry), - new HealthWebEndpointResponseMapper(new HealthStatusHttpMapper(), - ShowDetails.ALWAYS, + new CompositeReactiveHealthIndicator(new OrderedHealthAggregator(), registry), + new HealthWebEndpointResponseMapper(new HealthStatusHttpMapper(), ShowDetails.ALWAYS, new HashSet<>(Arrays.asList("ACTUATOR")))); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java index 23ac0e02491..fd5cfd5144c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java @@ -32,8 +32,7 @@ public class HealthIndicatorReactiveAdapterTests { @Test public void delegateReturnsHealth() { HealthIndicator delegate = mock(HealthIndicator.class); - HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter( - delegate); + HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); Health status = Health.up().build(); given(delegate.health()).willReturn(status); StepVerifier.create(adapter.health()).expectNext(status).verifyComplete(); @@ -42,8 +41,7 @@ public class HealthIndicatorReactiveAdapterTests { @Test public void delegateThrowError() { HealthIndicator delegate = mock(HealthIndicator.class); - HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter( - delegate); + HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); given(delegate.health()).willThrow(new IllegalStateException("Expected")); StepVerifier.create(adapter.health()).expectError(IllegalStateException.class); } @@ -52,13 +50,9 @@ public class HealthIndicatorReactiveAdapterTests { public void delegateRunsOnTheElasticScheduler() { String currentThread = Thread.currentThread().getName(); HealthIndicator delegate = () -> Health - .status(Thread.currentThread().getName().equals(currentThread) - ? Status.DOWN : Status.UP) - .build(); - HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter( - delegate); - StepVerifier.create(adapter.health()).expectNext(Health.status(Status.UP).build()) - .verifyComplete(); + .status(Thread.currentThread().getName().equals(currentThread) ? Status.DOWN : Status.UP).build(); + HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); + StepVerifier.create(adapter.health()).expectNext(Health.status(Status.UP).build()).verifyComplete(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index 38921dd5515..c30b05ef0fb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -37,8 +37,7 @@ public class HealthTests { @Test public void statusMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Health.Builder(null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new Health.Builder(null, null)) .withMessageContaining("Status must not be null"); } @@ -51,18 +50,15 @@ public class HealthTests { @Test public void createWithDetails() { - Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .build(); + Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsOnly(entry("a", "b")); } @Test public void equalsAndHashCode() { - Health h1 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .build(); - Health h2 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .build(); + Health h1 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); + Health h2 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); Health h3 = new Health.Builder(Status.UP).build(); assertThat(h1).isEqualTo(h1); assertThat(h1).isEqualTo(h2); @@ -75,16 +71,14 @@ public class HealthTests { @Test public void withException() { RuntimeException ex = new RuntimeException("bang"); - Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .withException(ex).build(); + Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).withException(ex).build(); assertThat(health.getDetails()).containsOnly(entry("a", "b"), entry("error", "java.lang.RuntimeException: bang")); } @Test public void withDetails() { - Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .withDetail("c", "d").build(); + Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).withDetail("c", "d").build(); assertThat(health.getDetails()).containsOnly(entry("a", "b"), entry("c", "d")); } @@ -115,8 +109,7 @@ public class HealthTests { details1.put("a", "e"); details1.put("1", "2"); Health health = Health.up().withDetails(details1).withDetails(details2).build(); - assertThat(health.getDetails()).containsOnly(entry("a", "e"), entry("c", "d"), - entry("1", "2")); + assertThat(health.getDetails()).containsOnly(entry("a", "e"), entry("c", "d"), entry("1", "2")); } @Test @@ -152,8 +145,7 @@ public class HealthTests { RuntimeException ex = new RuntimeException("bang"); Health health = Health.down(ex).build(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat(health.getDetails()) - .containsOnly(entry("error", "java.lang.RuntimeException: bang")); + assertThat(health.getDetails()).containsOnly(entry("error", "java.lang.RuntimeException: bang")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java index ced782db210..fc442fbd0aa 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java @@ -53,8 +53,7 @@ public class HealthWebEndpointResponseMapperTests { HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.NEVER); Supplier supplier = mockSupplier(); SecurityContext securityContext = mock(SecurityContext.class); - WebEndpointResponse response = mapper.mapDetails(supplier, - securityContext); + WebEndpointResponse response = mapper.mapDetails(supplier, securityContext); assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); verifyZeroInteractions(supplier); verifyZeroInteractions(securityContext); @@ -62,12 +61,10 @@ public class HealthWebEndpointResponseMapperTests { @Test public void mapDetailsWithUnauthorizedUserDoesNotInvokeSupplier() { - HealthWebEndpointResponseMapper mapper = createMapper( - ShowDetails.WHEN_AUTHORIZED); + HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.WHEN_AUTHORIZED); Supplier supplier = mockSupplier(); SecurityContext securityContext = mockSecurityContext("USER"); - WebEndpointResponse response = mapper.mapDetails(supplier, - securityContext); + WebEndpointResponse response = mapper.mapDetails(supplier, securityContext); assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); assertThat(response.getBody()).isNull(); verifyZeroInteractions(supplier); @@ -76,15 +73,12 @@ public class HealthWebEndpointResponseMapperTests { @Test public void mapDetailsWithAuthorizedUserInvokeSupplier() { - HealthWebEndpointResponseMapper mapper = createMapper( - ShowDetails.WHEN_AUTHORIZED); + HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.WHEN_AUTHORIZED); Supplier supplier = mockSupplier(); given(supplier.get()).willReturn(Health.down().build()); SecurityContext securityContext = mockSecurityContext("ACTUATOR"); - WebEndpointResponse response = mapper.mapDetails(supplier, - securityContext); - assertThat(response.getStatus()) - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value()); + WebEndpointResponse response = mapper.mapDetails(supplier, securityContext); + assertThat(response.getStatus()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value()); assertThat(response.getBody().getStatus()).isEqualTo(Status.DOWN); verify(supplier).get(); verify(securityContext).isUserInRole("ACTUATOR"); @@ -95,8 +89,7 @@ public class HealthWebEndpointResponseMapperTests { HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.ALWAYS); Supplier supplier = mockSupplier(); SecurityContext securityContext = mock(SecurityContext.class); - WebEndpointResponse response = mapper.mapDetails(supplier, - securityContext); + WebEndpointResponse response = mapper.mapDetails(supplier, securityContext); assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); assertThat(response.getBody()).isNull(); verify(supplier).get(); @@ -112,17 +105,15 @@ public class HealthWebEndpointResponseMapperTests { List associatedRoles = Arrays.asList(roles); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); - given(securityContext.isUserInRole(anyString())) - .will((Answer) (invocation) -> { - String expectedRole = invocation.getArgument(0); - return associatedRoles.contains(expectedRole); - }); + given(securityContext.isUserInRole(anyString())).will((Answer) (invocation) -> { + String expectedRole = invocation.getArgument(0); + return associatedRoles.contains(expectedRole); + }); return securityContext; } private HealthWebEndpointResponseMapper createMapper(ShowDetails showDetails) { - return new HealthWebEndpointResponseMapper(this.statusHttpMapper, showDetails, - this.authorizedRoles); + return new HealthWebEndpointResponseMapper(this.statusHttpMapper, showDetails, this.authorizedRoles); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java index 9c2d99d3469..76f3068c93a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java @@ -46,21 +46,18 @@ public class OrderedHealthAggregatorTests { healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.DOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.DOWN); } @Test public void customOrder() { - this.healthAggregator.setStatusOrder(Status.UNKNOWN, Status.UP, - Status.OUT_OF_SERVICE, Status.DOWN); + this.healthAggregator.setStatusOrder(Status.UNKNOWN, Status.UP, Status.OUT_OF_SERVICE, Status.DOWN); Map healths = new HashMap<>(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.UNKNOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.UNKNOWN); } @Test @@ -71,22 +68,19 @@ public class OrderedHealthAggregatorTests { healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.DOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.DOWN); } @Test public void customOrderWithCustomStatus() { - this.healthAggregator.setStatusOrder( - Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM")); + this.healthAggregator.setStatusOrder(Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM")); Map healths = new HashMap<>(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.DOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.DOWN); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java index a0f5eee4019..b5c073fdc30 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java @@ -39,18 +39,15 @@ public class ReactiveHealthIndicatorRegistryFactoryTests { @Test public void defaultHealthIndicatorNameFactory() { - ReactiveHealthIndicatorRegistry registry = this.factory - .createReactiveHealthIndicatorRegistry(Collections - .singletonMap("myHealthIndicator", () -> Mono.just(UP)), null); + ReactiveHealthIndicatorRegistry registry = this.factory.createReactiveHealthIndicatorRegistry( + Collections.singletonMap("myHealthIndicator", () -> Mono.just(UP)), null); assertThat(registry.getAll()).containsOnlyKeys("my"); } @Test public void healthIndicatorIsAdapted() { - ReactiveHealthIndicatorRegistry registry = this.factory - .createReactiveHealthIndicatorRegistry( - Collections.singletonMap("test", () -> Mono.just(UP)), - Collections.singletonMap("regular", () -> DOWN)); + ReactiveHealthIndicatorRegistry registry = this.factory.createReactiveHealthIndicatorRegistry( + Collections.singletonMap("test", () -> Mono.just(UP)), Collections.singletonMap("regular", () -> DOWN)); assertThat(registry.getAll()).containsOnlyKeys("test", "regular"); StepVerifier.create(registry.get("regular").health()).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.DOWN); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java index 149ce84da19..37f8ff78084 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java @@ -54,13 +54,11 @@ public class InfluxDbHealthIndicatorTests { @Test public void influxDbIsDown() { InfluxDB influxDB = mock(InfluxDB.class); - given(influxDB.ping()) - .willThrow(new InfluxDBException(new IOException("Connection failed"))); + given(influxDB.ping()).willThrow(new InfluxDBException(new IOException("Connection failed"))); InfluxDbHealthIndicator healthIndicator = new InfluxDbHealthIndicator(influxDB); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); verify(influxDB).ping(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java index 41488bbd71d..f9036979fcb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java @@ -38,8 +38,7 @@ public class EnvironmentInfoContributorTests { @Test public void extractOnlyInfoProperty() { - TestPropertyValues.of("info.app=my app", "info.version=1.0.0", "foo=bar") - .applyTo(this.environment); + TestPropertyValues.of("info.app=my app", "info.version=1.0.0", "foo=bar").applyTo(this.environment); Info actual = contributeFrom(this.environment); assertThat(actual.get("app", String.class)).isEqualTo("my app"); assertThat(actual.get("version", String.class)).isEqualTo("1.0.0"); @@ -56,15 +55,13 @@ public class EnvironmentInfoContributorTests { @Test @SuppressWarnings("unchecked") public void propertiesFromEnvironmentShouldBindCorrectly() { - TestPropertyValues.of("INFO_ENVIRONMENT_FOO=green").applyTo(this.environment, - Type.SYSTEM_ENVIRONMENT); + TestPropertyValues.of("INFO_ENVIRONMENT_FOO=green").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT); Info actual = contributeFrom(this.environment); assertThat(actual.get("environment", Map.class)).containsEntry("foo", "green"); } private static Info contributeFrom(ConfigurableEnvironment environment) { - EnvironmentInfoContributor contributor = new EnvironmentInfoContributor( - environment); + EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(environment); Info.Builder builder = new Info.Builder(); contributor.contribute(builder); return builder.build(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java index 8ad4da4d11c..848f6551289 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java @@ -40,8 +40,7 @@ public class GitInfoContributorTests { Properties properties = new Properties(); properties.put("branch", "master"); properties.put("commit.time", "2016-03-04T14:36:33+0100"); - GitInfoContributor contributor = new GitInfoContributor( - new GitProperties(properties)); + GitInfoContributor contributor = new GitInfoContributor(new GitProperties(properties)); Map content = contributor.generateContent(); assertThat(content.get("commit")).isInstanceOf(Map.class); Map commit = (Map) content.get("commit"); @@ -56,8 +55,7 @@ public class GitInfoContributorTests { Properties properties = new Properties(); properties.put("branch", "master"); properties.put("commit.id", "8e29a0b0d423d2665c6ee5171947c101a5c15681"); - GitInfoContributor contributor = new GitInfoContributor( - new GitProperties(properties)); + GitInfoContributor contributor = new GitInfoContributor(new GitProperties(properties)); Map content = contributor.generateContent(); assertThat(content.get("commit")).isInstanceOf(Map.class); Map commit = (Map) content.get("commit"); @@ -72,8 +70,7 @@ public class GitInfoContributorTests { properties.put("branch", "master"); properties.put("commit.id", "1b3cec34f7ca0a021244452f2cae07a80497a7c7"); properties.put("commit.id.abbrev", "1b3cec3"); - GitInfoContributor contributor = new GitInfoContributor( - new GitProperties(properties), Mode.FULL); + GitInfoContributor contributor = new GitInfoContributor(new GitProperties(properties), Mode.FULL); Map content = contributor.generateContent(); Map commit = (Map) content.get("commit"); assertThat(commit.get("id")).isInstanceOf(Map.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java index 0e259e03716..0334e87d8be 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java @@ -36,9 +36,8 @@ public class InfoEndpointTests { @Test public void info() { - InfoEndpoint endpoint = new InfoEndpoint( - Arrays.asList((builder) -> builder.withDetail("key1", "value1"), - (builder) -> builder.withDetail("key2", "value2"))); + InfoEndpoint endpoint = new InfoEndpoint(Arrays.asList((builder) -> builder.withDetail("key1", "value1"), + (builder) -> builder.withDetail("key2", "value2"))); Map info = endpoint.info(); assertThat(info).hasSize(2); assertThat(info).containsEntry("key1", "value1"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java index 2b353bb389c..7a28647f245 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java @@ -46,11 +46,10 @@ public class InfoEndpointWebIntegrationTests { @Test public void info() { - client.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody().jsonPath("beanName1.key11") - .isEqualTo("value11").jsonPath("beanName1.key12").isEqualTo("value12") - .jsonPath("beanName2.key21").isEqualTo("value21") - .jsonPath("beanName2.key22").isEqualTo("value22"); + client.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() + .expectBody().jsonPath("beanName1.key11").isEqualTo("value11").jsonPath("beanName1.key12") + .isEqualTo("value12").jsonPath("beanName2.key21").isEqualTo("value21").jsonPath("beanName2.key22") + .isEqualTo("value22"); } @Configuration(proxyBeanMethods = false) @@ -58,8 +57,7 @@ public class InfoEndpointWebIntegrationTests { @Bean public InfoEndpoint endpoint(ObjectProvider infoContributors) { - return new InfoEndpoint( - infoContributors.orderedStream().collect(Collectors.toList())); + return new InfoEndpoint(infoContributors.orderedStream().collect(Collectors.toList())); } @Bean diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java index c0e9b96ef19..02107342fe9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java @@ -32,8 +32,7 @@ public class InfoTests { @Test public void infoIsImmutable() { Info info = new Info.Builder().withDetail("foo", "bar").build(); - assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(info.getDetails()::clear); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(info.getDetails()::clear); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java index 102f82db6a8..a8c533e3101 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java @@ -30,8 +30,7 @@ public class SimpleInfoContributorTests { @Test public void prefixIsMandatory() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SimpleInfoContributor(null, new Object())); + assertThatIllegalArgumentException().isThrownBy(() -> new SimpleInfoContributor(null, new Object())); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java index b3e5313018a..86c7e4752e3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java @@ -40,17 +40,16 @@ public class IntegrationGraphEndpointWebIntegrationTests { @Test public void graph() { - client.get().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("contentDescriptor.providerVersion").isNotEmpty() + client.get().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isOk().expectBody().jsonPath("contentDescriptor.providerVersion").isNotEmpty() .jsonPath("contentDescriptor.providerFormatVersion").isEqualTo(1.0f) .jsonPath("contentDescriptor.provider").isEqualTo("spring-integration"); } @Test public void rebuild() { - client.post().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNoContent(); + client.post().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isNoContent(); } @Configuration(proxyBeanMethods = false) @@ -58,8 +57,7 @@ public class IntegrationGraphEndpointWebIntegrationTests { public static class TestConfiguration { @Bean - public IntegrationGraphEndpoint endpoint( - IntegrationGraphServer integrationGraphServer) { + public IntegrationGraphEndpoint endpoint(IntegrationGraphServer integrationGraphServer) { return new IntegrationGraphEndpoint(integrationGraphServer); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java index 2a23093252f..ded220843cd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java @@ -53,8 +53,7 @@ public class DataSourceHealthIndicatorTests { @BeforeEach public void init() { EmbeddedDatabaseConnection db = EmbeddedDatabaseConnection.HSQL; - this.dataSource = new SingleConnectionDataSource( - db.getUrl("testdb") + ";shutdown=true", "sa", "", false); + this.dataSource = new SingleConnectionDataSource(db.getUrl("testdb") + ";shutdown=true", "sa", "", false); this.dataSource.setDriverClassName(db.getDriverClassName()); } @@ -70,22 +69,19 @@ public class DataSourceHealthIndicatorTests { this.indicator.setDataSource(this.dataSource); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnly( - entry("database", "HSQL Database Engine"), entry("result", 1L), + assertThat(health.getDetails()).containsOnly(entry("database", "HSQL Database Engine"), entry("result", 1L), entry("validationQuery", DatabaseDriver.HSQLDB.getValidationQuery())); } @Test public void healthIndicatorWithCustomValidationQuery() { String customValidationQuery = "SELECT COUNT(*) from FOO"; - new JdbcTemplate(this.dataSource) - .execute("CREATE TABLE FOO (id INTEGER IDENTITY PRIMARY KEY)"); + new JdbcTemplate(this.dataSource).execute("CREATE TABLE FOO (id INTEGER IDENTITY PRIMARY KEY)"); this.indicator.setDataSource(this.dataSource); this.indicator.setQuery(customValidationQuery); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnly( - entry("database", "HSQL Database Engine"), entry("result", 0L), + assertThat(health.getDetails()).containsOnly(entry("database", "HSQL Database Engine"), entry("result", 0L), entry("validationQuery", customValidationQuery)); } @@ -96,19 +92,16 @@ public class DataSourceHealthIndicatorTests { this.indicator.setQuery(invalidValidationQuery); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat(health.getDetails()).contains( - entry("database", "HSQL Database Engine"), + assertThat(health.getDetails()).contains(entry("database", "HSQL Database Engine"), entry("validationQuery", invalidValidationQuery)); - assertThat(health.getDetails()).containsOnlyKeys("database", "error", - "validationQuery"); + assertThat(health.getDetails()).containsOnlyKeys("database", "error", "validationQuery"); } @Test public void healthIndicatorCloseConnection() throws Exception { DataSource dataSource = mock(DataSource.class); Connection connection = mock(Connection.class); - given(connection.getMetaData()) - .willReturn(this.dataSource.getConnection().getMetaData()); + given(connection.getMetaData()).willReturn(this.dataSource.getConnection().getMetaData()); given(dataSource.getConnection()).willReturn(connection); this.indicator.setDataSource(dataSource); Health health = this.indicator.health(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java index 162bb5d06ff..7f520357282 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java @@ -61,8 +61,7 @@ public class JmsHealthIndicatorTests { @Test public void jmsBrokerIsDown() throws JMSException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); - given(connectionFactory.createConnection()) - .willThrow(new JMSException("test", "123")); + given(connectionFactory.createConnection()).willThrow(new JMSException("test", "123")); JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); Health health = indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -72,8 +71,7 @@ public class JmsHealthIndicatorTests { @Test public void jmsBrokerCouldNotRetrieveProviderMetadata() throws JMSException { ConnectionMetaData connectionMetaData = mock(ConnectionMetaData.class); - given(connectionMetaData.getJMSProviderName()) - .willThrow(new JMSException("test", "123")); + given(connectionMetaData.getJMSProviderName()).willThrow(new JMSException("test", "123")); Connection connection = mock(Connection.class); given(connection.getMetaData()).willReturn(connectionMetaData); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); @@ -116,8 +114,7 @@ public class JmsHealthIndicatorTests { JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); Health health = indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection closed"); + assertThat((String) health.getDetails().get("error")).contains("Connection closed"); } private static final class UnresponsiveStartAnswer implements Answer { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java index 288b3bc3c32..de264b5358e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java @@ -41,8 +41,7 @@ public class LdapHealthIndicatorTests { @SuppressWarnings("unchecked") public void ldapIsUp() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); - given(ldapTemplate.executeReadOnly((ContextExecutor) any())) - .willReturn("3"); + given(ldapTemplate.executeReadOnly((ContextExecutor) any())).willReturn("3"); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -55,13 +54,11 @@ public class LdapHealthIndicatorTests { public void ldapIsDown() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); given(ldapTemplate.executeReadOnly((ContextExecutor) any())) - .willThrow(new CommunicationException( - new javax.naming.CommunicationException("Connection failed"))); + .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); verify(ldapTemplate).executeReadOnly((ContextExecutor) any()); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java index b5abfe386b4..852e737051f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java @@ -45,16 +45,15 @@ import static org.assertj.core.api.Assertions.assertThat; public class LiquibaseEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - LiquibaseAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test public void liquibaseReportIsReturned() { this.contextRunner.withUserConfiguration(Config.class).run((context) -> { - Map liquibaseBeans = context - .getBean(LiquibaseEndpoint.class).liquibaseBeans().getContexts() - .get(context.getId()).getLiquibaseBeans(); + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class).liquibaseBeans() + .getContexts().get(context.getId()).getLiquibaseBeans(); assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); } @@ -65,25 +64,21 @@ public class LiquibaseEndpointTests { .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA", "spring.datasource.schema=classpath:/db/create-custom-schema.sql") .run((context) -> { - Map liquibaseBeans = context - .getBean(LiquibaseEndpoint.class).liquibaseBeans() - .getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()) - .hasSize(1); + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); } @Test public void invokeWithCustomTables() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues( - "spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", - "spring.liquibase.database-change-log-table=liquibase_database_changelog") + this.contextRunner.withUserConfiguration(Config.class) + .withPropertyValues("spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", + "spring.liquibase.database-change-log-table=liquibase_database_changelog") .run((context) -> { - Map liquibaseBeans = context - .getBean(LiquibaseEndpoint.class).liquibaseBeans() - .getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()) - .hasSize(1); + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java index 77407c03823..beca8a574bd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java @@ -70,8 +70,7 @@ public class LogFileWebEndpointTests { this.environment.setProperty("logging.file.name", this.logFile.getAbsolutePath()); Resource resource = this.endpoint.logFile(); assertThat(resource).isNotNull(); - assertThat(StreamUtils.copyToString(resource.getInputStream(), - StandardCharsets.UTF_8)).isEqualTo("--TEST--"); + assertThat(StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8)).isEqualTo("--TEST--"); } @Test @@ -80,18 +79,15 @@ public class LogFileWebEndpointTests { this.environment.setProperty("logging.file", this.logFile.getAbsolutePath()); Resource resource = this.endpoint.logFile(); assertThat(resource).isNotNull(); - assertThat(StreamUtils.copyToString(resource.getInputStream(), - StandardCharsets.UTF_8)).isEqualTo("--TEST--"); + assertThat(StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8)).isEqualTo("--TEST--"); } @Test public void resourceResponseWithExternalLogFile() throws Exception { - LogFileWebEndpoint endpoint = new LogFileWebEndpoint(this.environment, - this.logFile); + LogFileWebEndpoint endpoint = new LogFileWebEndpoint(this.environment, this.logFile); Resource resource = endpoint.logFile(); assertThat(resource).isNotNull(); - assertThat(StreamUtils.copyToString(resource.getInputStream(), - StandardCharsets.UTF_8)).isEqualTo("--TEST--"); + assertThat(StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8)).isEqualTo("--TEST--"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java index c89ec789309..fee3560c8a2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java @@ -66,21 +66,16 @@ public class LogFileWebEndpointWebIntegrationTests { @Test public void getRequestProducesResponseWithLogFile() { - TestPropertyValues.of("logging.file.name:" + this.logFile.getAbsolutePath()) - .applyTo(context); - client.get().uri("/actuator/logfile").exchange().expectStatus().isOk() - .expectHeader().contentType("text/plain; charset=UTF-8") - .expectBody(String.class).isEqualTo("--TEST--"); + TestPropertyValues.of("logging.file.name:" + this.logFile.getAbsolutePath()).applyTo(context); + client.get().uri("/actuator/logfile").exchange().expectStatus().isOk().expectHeader() + .contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); } @Test public void getRequestThatAcceptsTextPlainProducesResponseWithLogFile() { - TestPropertyValues.of("logging.file:" + this.logFile.getAbsolutePath()) - .applyTo(context); - client.get().uri("/actuator/logfile").accept(MediaType.TEXT_PLAIN).exchange() - .expectStatus().isOk().expectHeader() - .contentType("text/plain; charset=UTF-8").expectBody(String.class) - .isEqualTo("--TEST--"); + TestPropertyValues.of("logging.file:" + this.logFile.getAbsolutePath()).applyTo(context); + client.get().uri("/actuator/logfile").accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() + .expectHeader().contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java index 6e6011ea6aa..50e07fc489a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java @@ -46,27 +46,24 @@ public class LoggersEndpointTests { @Test @SuppressWarnings("unchecked") public void loggersShouldReturnLoggerConfigurations() { - given(this.loggingSystem.getLoggerConfigurations()).willReturn(Collections - .singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); - given(this.loggingSystem.getSupportedLogLevels()) - .willReturn(EnumSet.allOf(LogLevel.class)); + given(this.loggingSystem.getLoggerConfigurations()) + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); Map result = new LoggersEndpoint(this.loggingSystem).loggers(); - Map loggers = (Map) result - .get("loggers"); + Map loggers = (Map) result.get("loggers"); Set levels = (Set) result.get("levels"); LoggerLevels rootLevels = loggers.get("ROOT"); assertThat(rootLevels.getConfiguredLevel()).isNull(); assertThat(rootLevels.getEffectiveLevel()).isEqualTo("DEBUG"); - assertThat(levels).containsExactly(LogLevel.OFF, LogLevel.FATAL, LogLevel.ERROR, - LogLevel.WARN, LogLevel.INFO, LogLevel.DEBUG, LogLevel.TRACE); + assertThat(levels).containsExactly(LogLevel.OFF, LogLevel.FATAL, LogLevel.ERROR, LogLevel.WARN, LogLevel.INFO, + LogLevel.DEBUG, LogLevel.TRACE); } @Test public void loggerLevelsWhenNameSpecifiedShouldReturnLevels() { given(this.loggingSystem.getLoggerConfiguration("ROOT")) .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); - LoggerLevels levels = new LoggersEndpoint(this.loggingSystem) - .loggerLevels("ROOT"); + LoggerLevels levels = new LoggersEndpoint(this.loggingSystem).loggerLevels("ROOT"); assertThat(levels.getConfiguredLevel()).isNull(); assertThat(levels.getEffectiveLevel()).isEqualTo("DEBUG"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java index 9e29d829717..830dd0a19c7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java @@ -67,80 +67,66 @@ public class LoggersEndpointWebIntegrationTests { public void resetMocks() { this.loggingSystem = context.getBean(LoggingSystem.class); Mockito.reset(this.loggingSystem); - given(this.loggingSystem.getSupportedLogLevels()) - .willReturn(EnumSet.allOf(LogLevel.class)); + given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); } @Test public void getLoggerShouldReturnAllLoggerConfigurations() { - given(this.loggingSystem.getLoggerConfigurations()).willReturn(Collections - .singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); - client.get().uri("/actuator/loggers").exchange().expectStatus().isOk() - .expectBody().jsonPath("$.length()").isEqualTo(2).jsonPath("levels") - .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", - "TRACE")) - .jsonPath("loggers.length()").isEqualTo(1) - .jsonPath("loggers.ROOT.length()").isEqualTo(2) - .jsonPath("loggers.ROOT.configuredLevel").isEqualTo(null) - .jsonPath("loggers.ROOT.effectiveLevel").isEqualTo("DEBUG"); + given(this.loggingSystem.getLoggerConfigurations()) + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + client.get().uri("/actuator/loggers").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") + .isEqualTo(2).jsonPath("levels") + .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE")) + .jsonPath("loggers.length()").isEqualTo(1).jsonPath("loggers.ROOT.length()").isEqualTo(2) + .jsonPath("loggers.ROOT.configuredLevel").isEqualTo(null).jsonPath("loggers.ROOT.effectiveLevel") + .isEqualTo("DEBUG"); } @Test public void getLoggerShouldReturnLogLevels() { given(this.loggingSystem.getLoggerConfiguration("ROOT")) .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); - client.get().uri("/actuator/loggers/ROOT").exchange().expectStatus().isOk() - .expectBody().jsonPath("$.length()").isEqualTo(2) - .jsonPath("configuredLevel").isEqualTo(null).jsonPath("effectiveLevel") - .isEqualTo("DEBUG"); + client.get().uri("/actuator/loggers/ROOT").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") + .isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null).jsonPath("effectiveLevel").isEqualTo("DEBUG"); } @Test public void getLoggersWhenLoggerNotFoundShouldReturnNotFound() { - client.get().uri("/actuator/loggers/com.does.not.exist").exchange().expectStatus() - .isNotFound(); + client.get().uri("/actuator/loggers/com.does.not.exist").exchange().expectStatus().isNotFound(); } @Test public void setLoggerUsingApplicationJsonShouldSetLogLevel() { - client.post().uri("/actuator/loggers/ROOT") - .contentType(MediaType.APPLICATION_JSON) - .syncBody(Collections.singletonMap("configuredLevel", "debug")).exchange() - .expectStatus().isNoContent(); + client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) + .syncBody(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); } @Test public void setLoggerUsingActuatorV2JsonShouldSetLogLevel() { - client.post().uri("/actuator/loggers/ROOT") - .contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) - .syncBody(Collections.singletonMap("configuredLevel", "debug")).exchange() - .expectStatus().isNoContent(); + client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) + .syncBody(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); } @Test public void setLoggerWithWrongLogLevelResultInBadRequestResponse() { - client.post().uri("/actuator/loggers/ROOT") - .contentType(MediaType.APPLICATION_JSON) - .syncBody(Collections.singletonMap("configuredLevel", "other")).exchange() - .expectStatus().isBadRequest(); + client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) + .syncBody(Collections.singletonMap("configuredLevel", "other")).exchange().expectStatus() + .isBadRequest(); verifyZeroInteractions(this.loggingSystem); } @Test public void setLoggerWithNullLogLevel() { - client.post().uri("/actuator/loggers/ROOT") - .contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) - .syncBody(Collections.singletonMap("configuredLevel", null)).exchange() - .expectStatus().isNoContent(); + client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) + .syncBody(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", null); } @Test public void setLoggerWithNoLogLevel() { - client.post().uri("/actuator/loggers/ROOT") - .contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) + client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) .syncBody(Collections.emptyMap()).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", null); } @@ -149,10 +135,9 @@ public class LoggersEndpointWebIntegrationTests { public void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() { given(this.loggingSystem.getLoggerConfiguration("com.png")) .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); - client.get().uri("/actuator/loggers/com.png").exchange().expectStatus().isOk() - .expectBody().jsonPath("$.length()").isEqualTo(2) - .jsonPath("configuredLevel").isEqualTo(null).jsonPath("effectiveLevel") - .isEqualTo("DEBUG"); + client.get().uri("/actuator/loggers/com.png").exchange().expectStatus().isOk().expectBody() + .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) + .jsonPath("effectiveLevel").isEqualTo("DEBUG"); } private JSONArray jsonArrayOf(Object... entries) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java index 7e93c71f7f6..4a3bb6a1ec7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java @@ -54,8 +54,7 @@ public class MailHealthIndicatorTests { @BeforeEach public void setup() { Session session = Session.getDefaultInstance(new Properties()); - session.addProvider(new Provider(Type.TRANSPORT, "success", - SuccessTransport.class.getName(), "Test", "1.0.0")); + session.addProvider(new Provider(Type.TRANSPORT, "success", SuccessTransport.class.getName(), "Test", "1.0.0")); this.mailSender = mock(JavaMailSenderImpl.class); given(this.mailSender.getHost()).willReturn("smtp.acme.org"); given(this.mailSender.getPort()).willReturn(25); @@ -73,8 +72,7 @@ public class MailHealthIndicatorTests { @Test public void smtpIsDown() throws MessagingException { - willThrow(new MessagingException("A test exception")).given(this.mailSender) - .testConnection(); + willThrow(new MessagingException("A test exception")).given(this.mailSender).testConnection(); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails().get("location")).isEqualTo("smtp.acme.org:25"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java index 6f723e8409e..079dbf8bb00 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java @@ -30,15 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; public class HeapDumpWebEndpointTests { @Test - public void parallelRequestProducesTooManyRequestsResponse() - throws InterruptedException { + public void parallelRequestProducesTooManyRequestsResponse() throws InterruptedException { CountDownLatch dumpingLatch = new CountDownLatch(1); CountDownLatch blockingLatch = new CountDownLatch(1); HeapDumpWebEndpoint slowEndpoint = new HeapDumpWebEndpoint(2500) { @Override - protected HeapDumper createHeapDumper() - throws HeapDumperUnavailableException { + protected HeapDumper createHeapDumper() throws HeapDumperUnavailableException { return (file, live) -> { dumpingLatch.countDown(); blockingLatch.await(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java index a907ff36356..c81e4528d21 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java @@ -60,15 +60,13 @@ public class HeapDumpWebEndpointWebIntegrationTests { @Test public void invokeWhenNotAvailableShouldReturnServiceUnavailableStatus() { this.endpoint.setAvailable(false); - client.get().uri("/actuator/heapdump").exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + client.get().uri("/actuator/heapdump").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } @Test public void getRequestShouldReturnHeapDumpInResponseBody() throws Exception { - client.get().uri("/actuator/heapdump").exchange().expectStatus().isOk() - .expectHeader().contentType(MediaType.APPLICATION_OCTET_STREAM) - .expectBody(String.class).isEqualTo("HEAPDUMP"); + client.get().uri("/actuator/heapdump").exchange().expectStatus().isOk().expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM).expectBody(String.class).isEqualTo("HEAPDUMP"); assertHeapDumpFileIsDeleted(); } @@ -117,8 +115,7 @@ public class HeapDumpWebEndpointWebIntegrationTests { if (file.exists()) { throw new IOException("File exists"); } - FileCopyUtils.copy(TestHeapDumpWebEndpoint.this.heapDump.getBytes(), - file); + FileCopyUtils.copy(TestHeapDumpWebEndpoint.this.heapDump.getBytes(), file); }; } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java index 0af982a5642..16fcdfdad46 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java @@ -30,8 +30,7 @@ public class ThreadDumpEndpointTests { @Test public void dumpThreads() { - assertThat(new ThreadDumpEndpoint().threadDump().getThreads().size()) - .isGreaterThan(0); + assertThat(new ThreadDumpEndpoint().threadDump().getThreads().size()).isGreaterThan(0); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java index 946f4fd2b28..5430adcd8ca 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java @@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ public class MetricsEndpointTests { - private final MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, - new MockClock()); + private final MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); private final MetricsEndpoint endpoint = new MetricsEndpoint(this.registry); @@ -59,8 +58,7 @@ public class MetricsEndpointTests { this.registry.counter("com.example.bar"); this.registry.counter("com.example.foo"); MetricsEndpoint.ListNamesResponse result = this.endpoint.listNames(); - assertThat(result.getNames()).containsOnlyOnce("com.example.foo", - "com.example.bar"); + assertThat(result.getNames()).containsOnlyOnce("com.example.foo", "com.example.bar"); } @Test @@ -81,8 +79,7 @@ public class MetricsEndpointTests { this.registry.counter("cache", "result", "hit", "host", "1").increment(2); this.registry.counter("cache", "result", "miss", "host", "1").increment(2); this.registry.counter("cache", "result", "hit", "host", "2").increment(2); - MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", - Collections.emptyList()); + MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", Collections.emptyList()); assertThat(response.getName()).isEqualTo("cache"); assertThat(availableTagKeys(response)).containsExactly("result", "host"); assertThat(getCount(response)).hasValue(6.0); @@ -104,8 +101,7 @@ public class MetricsEndpointTests { secondLevel.counter("cache", "result", "miss", "host", "1").increment(2); secondLevel.counter("cache", "result", "hit", "host", "2").increment(2); MetricsEndpoint endpoint = new MetricsEndpoint(composite); - MetricsEndpoint.MetricResponse response = endpoint.metric("cache", - Collections.emptyList()); + MetricsEndpoint.MetricResponse response = endpoint.metric("cache", Collections.emptyList()); assertThat(response.getName()).isEqualTo("cache"); assertThat(availableTagKeys(response)).containsExactly("result", "host"); assertThat(getCount(response)).hasValue(6.0); @@ -122,8 +118,7 @@ public class MetricsEndpointTests { composite.add(firstLevel); firstLevel.add(secondLevel); MetricsEndpoint endpoint = new MetricsEndpoint(composite); - MetricsEndpoint.MetricResponse response = endpoint.metric("invalid.metric.name", - Collections.emptyList()); + MetricsEndpoint.MetricResponse response = endpoint.metric("invalid.metric.name", Collections.emptyList()); assertThat(response).isNull(); } @@ -131,10 +126,8 @@ public class MetricsEndpointTests { public void metricTagValuesAreDeduplicated() { this.registry.counter("cache", "host", "1", "region", "east", "result", "hit"); this.registry.counter("cache", "host", "1", "region", "east", "result", "miss"); - MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", - Collections.singletonList("host:1")); - assertThat(response.getAvailableTags().stream() - .filter((t) -> t.getTag().equals("region")) + MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", Collections.singletonList("host:1")); + assertThat(response.getAvailableTags().stream().filter((t) -> t.getTag().equals("region")) .flatMap((t) -> t.getValues().stream())).containsExactly("east"); } @@ -150,8 +143,8 @@ public class MetricsEndpointTests { @Test public void metricWithInvalidTag() { - assertThatExceptionOfType(InvalidEndpointRequestException.class).isThrownBy( - () -> this.endpoint.metric("counter", Collections.singletonList("key"))); + assertThatExceptionOfType(InvalidEndpointRequestException.class) + .isThrownBy(() -> this.endpoint.metric("counter", Collections.singletonList("key"))); } @Test @@ -170,8 +163,7 @@ public class MetricsEndpointTests { @Test public void nonExistentMetric() { - MetricsEndpoint.MetricResponse response = this.endpoint.metric("does.not.exist", - Collections.emptyList()); + MetricsEndpoint.MetricResponse response = this.endpoint.metric("does.not.exist", Collections.emptyList()); assertThat(response).isNull(); } @@ -191,24 +183,21 @@ public class MetricsEndpointTests { assertMetricHasStatisticEqualTo(reg, "counter", Statistic.COUNT, 2.0); } - private void assertMetricHasStatisticEqualTo(MeterRegistry registry, - String metricName, Statistic stat, Double value) { + private void assertMetricHasStatisticEqualTo(MeterRegistry registry, String metricName, Statistic stat, + Double value) { MetricsEndpoint endpoint = new MetricsEndpoint(registry); - assertThat(endpoint.metric(metricName, Collections.emptyList()).getMeasurements() - .stream().filter((sample) -> sample.getStatistic().equals(stat)) - .findAny()).hasValueSatisfying( - (sample) -> assertThat(sample.getValue()).isEqualTo(value)); + assertThat(endpoint.metric(metricName, Collections.emptyList()).getMeasurements().stream() + .filter((sample) -> sample.getStatistic().equals(stat)).findAny()) + .hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value)); } private Optional getCount(MetricsEndpoint.MetricResponse response) { - return response.getMeasurements().stream() - .filter((sample) -> sample.getStatistic().equals(Statistic.COUNT)) + return response.getMeasurements().stream().filter((sample) -> sample.getStatistic().equals(Statistic.COUNT)) .findAny().map(MetricsEndpoint.Sample::getValue); } private Stream availableTagKeys(MetricsEndpoint.MetricResponse response) { - return response.getAvailableTags().stream() - .map(MetricsEndpoint.AvailableTag::getTag); + return response.getAvailableTags().stream().map(MetricsEndpoint.AvailableTag::getTag); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java index 13768afb9f3..8d83a17f3ed 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java @@ -45,8 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(WebEndpointRunners.class) public class MetricsEndpointWebIntegrationTests { - private static MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, - new MockClock()); + private static MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); private static WebTestClient client; @@ -55,25 +54,22 @@ public class MetricsEndpointWebIntegrationTests { @Test @SuppressWarnings("unchecked") public void listNames() throws IOException { - String responseBody = client.get().uri("/actuator/metrics").exchange() - .expectStatus().isOk().expectBody(String.class).returnResult() - .getResponseBody(); + String responseBody = client.get().uri("/actuator/metrics").exchange().expectStatus().isOk() + .expectBody(String.class).returnResult().getResponseBody(); Map> names = this.mapper.readValue(responseBody, Map.class); assertThat(names.get("names")).containsOnlyOnce("jvm.memory.used"); } @Test public void selectByName() { - client.get().uri("/actuator/metrics/jvm.memory.used").exchange().expectStatus() - .isOk().expectBody().jsonPath("$.name").isEqualTo("jvm.memory.used"); + client.get().uri("/actuator/metrics/jvm.memory.used").exchange().expectStatus().isOk().expectBody() + .jsonPath("$.name").isEqualTo("jvm.memory.used"); } @Test public void selectByTag() { - client.get().uri( - "/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space") - .exchange().expectStatus().isOk().expectBody().jsonPath("$.name") - .isEqualTo("jvm.memory.used"); + client.get().uri("/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space").exchange() + .expectStatus().isOk().expectBody().jsonPath("$.name").isEqualTo("jvm.memory.used"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java index ec58127eb7e..4e371618f60 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java @@ -44,10 +44,8 @@ public class RabbitMetricsTests { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); SimpleMeterRegistry registry = new SimpleMeterRegistry(); new RabbitMetrics(connectionFactory, Tags.of("env", "prod")).bindTo(registry); - assertThat(registry.get("rabbitmq.connections").tags("env", "prod").meter()) - .isNotNull(); - assertThat(registry.find("rabbitmq.connections").tags("env", "dev").meter()) - .isNull(); + assertThat(registry.get("rabbitmq.connections").tags("env", "prod").meter()).isNotNull(); + assertThat(registry.find("rabbitmq.connections").tags("env", "dev").meter()).isNull(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java index 33fc87e54ac..80b55be9348 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java @@ -41,30 +41,24 @@ public class CacheMetricsRegistrarTests { public void bindToSupportedCache() { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.singleton(new CaffeineCacheMeterBinderProvider())); - assertThat(registrar.bindCacheToRegistry( - new CaffeineCache("test", Caffeine.newBuilder().build()))).isTrue(); - assertThat(this.meterRegistry.get("cache.gets").tags("name", "test").meter()) - .isNotNull(); + assertThat(registrar.bindCacheToRegistry(new CaffeineCache("test", Caffeine.newBuilder().build()))).isTrue(); + assertThat(this.meterRegistry.get("cache.gets").tags("name", "test").meter()).isNotNull(); } @Test public void bindToSupportedCacheWrappedInTransactionProxy() { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.singleton(new CaffeineCacheMeterBinderProvider())); - assertThat(registrar.bindCacheToRegistry(new TransactionAwareCacheDecorator( - new CaffeineCache("test", Caffeine.newBuilder().build())))).isTrue(); - assertThat(this.meterRegistry.get("cache.gets").tags("name", "test").meter()) - .isNotNull(); + assertThat(registrar.bindCacheToRegistry( + new TransactionAwareCacheDecorator(new CaffeineCache("test", Caffeine.newBuilder().build())))).isTrue(); + assertThat(this.meterRegistry.get("cache.gets").tags("name", "test").meter()).isNotNull(); } @Test public void bindToUnsupportedCache() { - CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, - Collections.emptyList()); - assertThat(registrar.bindCacheToRegistry( - new CaffeineCache("test", Caffeine.newBuilder().build()))).isFalse(); - assertThat(this.meterRegistry.find("cache.gets").tags("name", "test").meter()) - .isNull(); + CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.emptyList()); + assertThat(registrar.bindCacheToRegistry(new CaffeineCache("test", Caffeine.newBuilder().build()))).isFalse(); + assertThat(this.meterRegistry.find("cache.gets").tags("name", "test").meter()).isNull(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java index 3e8282616fb..7727ea7238c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java @@ -37,8 +37,7 @@ public class CaffeineCacheMeterBinderProviderTests { @Test public void caffeineCacheProvider() { CaffeineCache cache = new CaffeineCache("test", Caffeine.newBuilder().build()); - MeterBinder meterBinder = new CaffeineCacheMeterBinderProvider() - .getMeterBinder(cache, Collections.emptyList()); + MeterBinder meterBinder = new CaffeineCacheMeterBinderProvider().getMeterBinder(cache, Collections.emptyList()); assertThat(meterBinder).isInstanceOf(CaffeineCacheMetrics.class); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java index fb0b65514c2..61913206f6b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java @@ -40,14 +40,13 @@ public class EhCache2CacheMeterBinderProviderTests { @Test public void ehCache2CacheProvider() { CacheManager cacheManager = new CacheManager( - new Configuration().name("EhCacheCacheTests") - .defaultCache(new CacheConfiguration("default", 100))); + new Configuration().name("EhCacheCacheTests").defaultCache(new CacheConfiguration("default", 100))); try { Cache nativeCache = new Cache(new CacheConfiguration("test", 100)); cacheManager.addCache(nativeCache); EhCacheCache cache = new EhCacheCache(nativeCache); - MeterBinder meterBinder = new EhCache2CacheMeterBinderProvider() - .getMeterBinder(cache, Collections.emptyList()); + MeterBinder meterBinder = new EhCache2CacheMeterBinderProvider().getMeterBinder(cache, + Collections.emptyList()); assertThat(meterBinder).isInstanceOf(EhCache2Metrics.class); } finally { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java index 8807feb8f74..77e8af5f2f8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java @@ -41,8 +41,8 @@ public class HazelcastCacheMeterBinderProviderTests { IMap nativeCache = mock(IMap.class); given(nativeCache.getName()).willReturn("test"); HazelcastCache cache = new HazelcastCache(nativeCache); - MeterBinder meterBinder = new HazelcastCacheMeterBinderProvider() - .getMeterBinder(cache, Collections.emptyList()); + MeterBinder meterBinder = new HazelcastCacheMeterBinderProvider().getMeterBinder(cache, + Collections.emptyList()); assertThat(meterBinder).isInstanceOf(HazelcastCacheMetrics.class); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java index 6ec26dbd48f..8a794374fdb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java @@ -51,8 +51,7 @@ public class JCacheCacheMeterBinderProviderTests { given(this.nativeCache.getCacheManager()).willReturn(cacheManager); given(this.nativeCache.getName()).willReturn("test"); JCacheCache cache = new JCacheCache(this.nativeCache); - MeterBinder meterBinder = new JCacheCacheMeterBinderProvider() - .getMeterBinder(cache, Collections.emptyList()); + MeterBinder meterBinder = new JCacheCacheMeterBinderProvider().getMeterBinder(cache, Collections.emptyList()); assertThat(meterBinder).isInstanceOf(JCacheMetrics.class); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java index 1ff35d6f536..8c62e6b5ce4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java @@ -79,93 +79,78 @@ public class PrometheusPushGatewayManagerTests { @Test public void createWhenPushGatewayIsNullThrowsException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, - this.scheduler, this.pushRate, "job", this.groupingKey, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, + this.scheduler, this.pushRate, "job", this.groupingKey, null)) .withMessage("PushGateway must not be null"); } @Test public void createWhenCollectorRegistryIsNullThrowsException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, - this.scheduler, this.pushRate, "job", this.groupingKey, null)) - .withMessage("Registry must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, + this.scheduler, this.pushRate, "job", this.groupingKey, null)).withMessage("Registry must not be null"); } @Test public void createWhenSchedulerIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, - null, this.pushRate, "job", this.groupingKey, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, + this.registry, null, this.pushRate, "job", this.groupingKey, null)) .withMessage("Scheduler must not be null"); } @Test public void createWhenPushRateIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, - this.scheduler, null, "job", this.groupingKey, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, + this.registry, this.scheduler, null, "job", this.groupingKey, null)) .withMessage("PushRate must not be null"); } @Test public void createWhenJobIsEmptyThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, - this.scheduler, this.pushRate, "", this.groupingKey, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, + this.registry, this.scheduler, this.pushRate, "", this.groupingKey, null)) .withMessage("Job must not be empty"); } @Test public void createShouldSchedulePushAsFixedRate() throws Exception { - new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, - this.pushRate, "job", this.groupingKey, null); - verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), - eq(this.pushRate)); + new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", + this.groupingKey, null); + verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); this.task.getValue().run(); verify(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey); } @Test public void shutdownWhenOwnsSchedulerDoesShutdownScheduler() { - PushGatewayTaskScheduler ownedScheduler = mockScheduler( - PushGatewayTaskScheduler.class); - PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager( - this.pushGateway, this.registry, ownedScheduler, this.pushRate, "job", - this.groupingKey, null); + PushGatewayTaskScheduler ownedScheduler = mockScheduler(PushGatewayTaskScheduler.class); + PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, + ownedScheduler, this.pushRate, "job", this.groupingKey, null); manager.shutdown(); verify(ownedScheduler).shutdown(); } @Test public void shutdownWhenDoesNotOwnSchedulerDoesNotShutdownScheduler() { - ThreadPoolTaskScheduler otherScheduler = mockScheduler( - ThreadPoolTaskScheduler.class); - PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager( - this.pushGateway, this.registry, otherScheduler, this.pushRate, "job", - this.groupingKey, null); + ThreadPoolTaskScheduler otherScheduler = mockScheduler(ThreadPoolTaskScheduler.class); + PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, + otherScheduler, this.pushRate, "job", this.groupingKey, null); manager.shutdown(); verify(otherScheduler, never()).shutdown(); } @Test - public void shutdownWhenShutdownOperationIsPushPerformsPushOnShutdown() - throws Exception { - PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager( - this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", - this.groupingKey, ShutdownOperation.PUSH); + public void shutdownWhenShutdownOperationIsPushPerformsPushOnShutdown() throws Exception { + PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, + this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.PUSH); manager.shutdown(); verify(this.future).cancel(false); verify(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey); } @Test - public void shutdownWhenShutdownOperationIsDeletePerformsDeleteOnShutdown() - throws Exception { - PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager( - this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", - this.groupingKey, ShutdownOperation.DELETE); + public void shutdownWhenShutdownOperationIsDeletePerformsDeleteOnShutdown() throws Exception { + PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, + this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.DELETE); manager.shutdown(); verify(this.future).cancel(false); verify(this.pushGateway).delete("job", this.groupingKey); @@ -173,9 +158,8 @@ public class PrometheusPushGatewayManagerTests { @Test public void shutdownWhenShutdownOperationIsNoneDoesNothing() { - PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager( - this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", - this.groupingKey, ShutdownOperation.NONE); + PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, + this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.NONE); manager.shutdown(); verify(this.future).cancel(false); verifyZeroInteractions(this.pushGateway); @@ -183,24 +167,21 @@ public class PrometheusPushGatewayManagerTests { @Test public void pushWhenUnknownHostExceptionIsThrownDoesShutdown() throws Exception { - new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, - this.pushRate, "job", this.groupingKey, null); - verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), - eq(this.pushRate)); - willThrow(new UnknownHostException("foo")).given(this.pushGateway) - .pushAdd(this.registry, "job", this.groupingKey); + new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", + this.groupingKey, null); + verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); + willThrow(new UnknownHostException("foo")).given(this.pushGateway).pushAdd(this.registry, "job", + this.groupingKey); this.task.getValue().run(); verify(this.future).cancel(false); } @Test public void pushDoesNotThrowException() throws Exception { - new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, - this.pushRate, "job", this.groupingKey, null); - verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), - eq(this.pushRate)); - willThrow(RuntimeException.class).given(this.pushGateway).pushAdd(this.registry, - "job", this.groupingKey); + new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", + this.groupingKey, null); + verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); + willThrow(RuntimeException.class).given(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey); this.task.getValue().run(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java index 79558f113e5..6ff8cfd946c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java @@ -42,8 +42,7 @@ public class PrometheusScrapeEndpointIntegrationTests { @Test public void scrapeHasContentTypeText004() { - client.get().uri("/actuator/prometheus").exchange().expectStatus().isOk() - .expectHeader() + client.get().uri("/actuator/prometheus").exchange().expectStatus().isOk().expectHeader() .contentType(MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004)); } @@ -51,8 +50,7 @@ public class PrometheusScrapeEndpointIntegrationTests { static class TestConfiguration { @Bean - public PrometheusScrapeEndpoint prometheusScrapeEndpoint( - CollectorRegistry collectorRegistry) { + public PrometheusScrapeEndpoint prometheusScrapeEndpoint(CollectorRegistry collectorRegistry) { return new PrometheusScrapeEndpoint(collectorRegistry); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java index e45ae8d9c71..97e5a729d5c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java @@ -42,16 +42,12 @@ public class DataSourcePoolMetricsTests { @Test public void dataSourceIsInstrumented() { - new ApplicationContextRunner() - .withUserConfiguration(DataSourceConfig.class, MetricsApp.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "metrics.use-global-registry=false") + new ApplicationContextRunner().withUserConfiguration(DataSourceConfig.class, MetricsApp.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", "metrics.use-global-registry=false") .run((context) -> { context.getBean(DataSource.class).getConnection().getMetaData(); - context.getBean(MeterRegistry.class).get("jdbc.connections.max") - .meter(); + context.getBean(MeterRegistry.class).get("jdbc.connections.max").meter(); }); } @@ -68,11 +64,10 @@ public class DataSourcePoolMetricsTests { @Configuration(proxyBeanMethods = false) static class DataSourceConfig { - DataSourceConfig(DataSource dataSource, - Collection metadataProviders, + DataSourceConfig(DataSource dataSource, Collection metadataProviders, MeterRegistry registry) { - new DataSourcePoolMetrics(dataSource, metadataProviders, "data.source", - Collections.emptyList()).bindTo(registry); + new DataSourcePoolMetrics(dataSource, metadataProviders, "data.source", Collections.emptyList()) + .bindTo(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java index 2c9ed173105..cc8567d86f4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java @@ -59,8 +59,7 @@ public class MetricsRestTemplateCustomizerTests { this.restTemplate = new RestTemplate(); this.mockServer = MockRestServiceServer.createServer(this.restTemplate); this.customizer = new MetricsRestTemplateCustomizer(this.registry, - new DefaultRestTemplateExchangeTagsProvider(), "http.client.requests", - AutoTimer.ENABLED); + new DefaultRestTemplateExchangeTagsProvider(), "http.client.requests", AutoTimer.ENABLED); this.customizer.customize(this.restTemplate); } @@ -68,15 +67,12 @@ public class MetricsRestTemplateCustomizerTests { public void interceptRestTemplate() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", - MediaType.APPLICATION_JSON)); + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); String result = this.restTemplate.getForObject("/test/{id}", String.class, 123); - assertThat(this.registry.find("http.client.requests").meters()).anySatisfy( - (m) -> assertThat(m.getId().getTags().stream().map(Tag::getKey)) - .doesNotContain("bucket")); - assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/test/{id}", "status", "200").timer() - .count()).isEqualTo(1); + assertThat(this.registry.find("http.client.requests").meters()) + .anySatisfy((m) -> assertThat(m.getId().getTags().stream().map(Tag::getKey)).doesNotContain("bucket")); + assertThat(this.registry.get("http.client.requests").tags("method", "GET", "uri", "/test/{id}", "status", "200") + .timer().count()).isEqualTo(1); assertThat(result).isEqualTo("OK"); this.mockServer.verify(); } @@ -93,8 +89,7 @@ public class MetricsRestTemplateCustomizerTests { public void normalizeUriToContainLeadingSlash() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", - MediaType.APPLICATION_JSON)); + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); String result = this.restTemplate.getForObject("test/{id}", String.class, 123); this.registry.get("http.client.requests").tags("uri", "/test/{id}").timer(); assertThat(result).isEqualTo("OK"); @@ -103,13 +98,10 @@ public class MetricsRestTemplateCustomizerTests { @Test public void interceptRestTemplateWithUri() throws URISyntaxException { - this.mockServer - .expect(MockRestRequestMatchers.requestTo("http://localhost/test/123")) + this.mockServer.expect(MockRestRequestMatchers.requestTo("http://localhost/test/123")) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", - MediaType.APPLICATION_JSON)); - String result = this.restTemplate - .getForObject(new URI("http://localhost/test/123"), String.class); + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + String result = this.restTemplate.getForObject(new URI("http://localhost/test/123"), String.class); assertThat(result).isEqualTo("OK"); this.registry.get("http.client.requests").tags("uri", "/test/123").timer(); this.mockServer.verify(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java index 84025b5f987..5d9348a26af 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java @@ -45,40 +45,35 @@ public class RestTemplateExchangeTagsTests { @Test public void outcomeTagIsInformationalWhenResponseIs1xx() { - ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), - HttpStatus.CONTINUE); + ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.CONTINUE); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("INFORMATIONAL"); } @Test public void outcomeTagIsSuccessWhenResponseIs2xx() { - ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), - HttpStatus.OK); + ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.OK); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("SUCCESS"); } @Test public void outcomeTagIsRedirectionWhenResponseIs3xx() { - ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), - HttpStatus.MOVED_PERMANENTLY); + ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.MOVED_PERMANENTLY); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test public void outcomeTagIsClientErrorWhenResponseIs4xx() { - ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), - HttpStatus.BAD_REQUEST); + ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.BAD_REQUEST); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("CLIENT_ERROR"); } @Test public void outcomeTagIsServerErrorWhenResponseIs5xx() { - ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), - HttpStatus.BAD_GATEWAY); + ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.BAD_GATEWAY); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("SERVER_ERROR"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java index f28dce74d14..21c8de5262d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java @@ -41,8 +41,7 @@ import static org.mockito.Mockito.mock; */ public class DefaultWebClientExchangeTagsProviderTests { - private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() - + ".uriTemplate"; + private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; private WebClientExchangeTagsProvider tagsProvider = new DefaultWebClientExchangeTagsProvider(); @@ -52,12 +51,8 @@ public class DefaultWebClientExchangeTagsProviderTests { @BeforeEach public void setup() { - this.request = ClientRequest - .create(HttpMethod.GET, - URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, - "https://example.org/projects/{project}") - .build(); + this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) + .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}").build(); this.response = mock(ClientResponse.class); given(this.response.statusCode()).willReturn(HttpStatus.OK); } @@ -65,38 +60,31 @@ public class DefaultWebClientExchangeTagsProviderTests { @Test public void tagsShouldBePopulated() { Iterable tags = this.tagsProvider.tags(this.request, this.response, null); - assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), - Tag.of("uri", "/projects/{project}"), Tag.of("clientName", "example.org"), - Tag.of("status", "200"), Tag.of("outcome", "SUCCESS")); + assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/{project}"), + Tag.of("clientName", "example.org"), Tag.of("status", "200"), Tag.of("outcome", "SUCCESS")); } @Test public void tagsWhenNoUriTemplateShouldProvideUriPath() { - ClientRequest request = ClientRequest.create(HttpMethod.GET, - URI.create("https://example.org/projects/spring-boot")).build(); + ClientRequest request = ClientRequest + .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")).build(); Iterable tags = this.tagsProvider.tags(request, this.response, null); - assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), - Tag.of("uri", "/projects/spring-boot"), - Tag.of("clientName", "example.org"), Tag.of("status", "200"), - Tag.of("outcome", "SUCCESS")); + assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/spring-boot"), + Tag.of("clientName", "example.org"), Tag.of("status", "200"), Tag.of("outcome", "SUCCESS")); } @Test public void tagsWhenIoExceptionShouldReturnIoErrorStatus() { - Iterable tags = this.tagsProvider.tags(this.request, null, - new IOException()); - assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), - Tag.of("uri", "/projects/{project}"), Tag.of("clientName", "example.org"), - Tag.of("status", "IO_ERROR")); + Iterable tags = this.tagsProvider.tags(this.request, null, new IOException()); + assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/{project}"), + Tag.of("clientName", "example.org"), Tag.of("status", "IO_ERROR")); } @Test public void tagsWhenExceptionShouldReturnClientErrorStatus() { - Iterable tags = this.tagsProvider.tags(this.request, null, - new IllegalArgumentException()); - assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), - Tag.of("uri", "/projects/{project}"), Tag.of("clientName", "example.org"), - Tag.of("status", "CLIENT_ERROR")); + Iterable tags = this.tagsProvider.tags(this.request, null, new IllegalArgumentException()); + assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/{project}"), + Tag.of("clientName", "example.org"), Tag.of("status", "CLIENT_ERROR")); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java index 16925f33909..1899ddc1546 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java @@ -48,8 +48,8 @@ public class MetricsWebClientCustomizerTests { public void customizeShouldAddFilterFunction() { this.clientBuilder.filter(mock(ExchangeFilterFunction.class)); this.customizer.customize(this.clientBuilder); - this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(2).first() - .isInstanceOf(MetricsWebClientFilterFunction.class)); + this.clientBuilder.filters( + (filters) -> assertThat(filters).hasSize(2).first().isInstanceOf(MetricsWebClientFilterFunction.class)); } @Test @@ -57,8 +57,8 @@ public class MetricsWebClientCustomizerTests { this.customizer.customize(this.clientBuilder); this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(1)); this.customizer.customize(this.clientBuilder); - this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(1).first() - .isInstanceOf(MetricsWebClientFilterFunction.class)); + this.clientBuilder.filters( + (filters) -> assertThat(filters).hasSize(1).first().isInstanceOf(MetricsWebClientFilterFunction.class)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java index 2f8a165955e..145f30892b2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java @@ -49,8 +49,7 @@ import static org.mockito.Mockito.mock; */ public class MetricsWebClientFilterFunctionTests { - private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() - + ".uriTemplate"; + private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; private MeterRegistry registry; @@ -64,76 +63,66 @@ public class MetricsWebClientFilterFunctionTests { public void setup() { this.registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); this.filterFunction = new MetricsWebClientFilterFunction(this.registry, - new DefaultWebClientExchangeTagsProvider(), "http.client.requests", - AutoTimer.ENABLED); + new DefaultWebClientExchangeTagsProvider(), "http.client.requests", AutoTimer.ENABLED); this.response = mock(ClientResponse.class); this.exchange = (r) -> Mono.just(this.response); } @Test public void filterShouldRecordTimer() { - ClientRequest request = ClientRequest.create(HttpMethod.GET, - URI.create("https://example.com/projects/spring-boot")).build(); + ClientRequest request = ClientRequest + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); given(this.response.statusCode()).willReturn(HttpStatus.OK); this.filterFunction.filter(request, this.exchange).block(Duration.ofSeconds(30)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200") - .timer().count()).isEqualTo(1); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200").timer().count()).isEqualTo(1); } @Test public void filterWhenUriTemplatePresentShouldRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, - URI.create("https://example.com/projects/spring-boot")) + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); given(this.response.statusCode()).willReturn(HttpStatus.OK); this.filterFunction.filter(request, this.exchange).block(Duration.ofSeconds(30)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/{project}", "status", "200") - .timer().count()).isEqualTo(1); + .tags("method", "GET", "uri", "/projects/{project}", "status", "200").timer().count()).isEqualTo(1); } @Test public void filterWhenIoExceptionThrownShouldRecordTimer() { - ClientRequest request = ClientRequest.create(HttpMethod.GET, - URI.create("https://example.com/projects/spring-boot")).build(); + ClientRequest request = ClientRequest + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); ExchangeFunction errorExchange = (r) -> Mono.error(new IOException()); - this.filterFunction.filter(request, errorExchange) - .onErrorResume(IOException.class, (t) -> Mono.empty()) + this.filterFunction.filter(request, errorExchange).onErrorResume(IOException.class, (t) -> Mono.empty()) .block(Duration.ofSeconds(30)); - assertThat( - this.registry - .get("http.client.requests").tags("method", "GET", "uri", - "/projects/spring-boot", "status", "IO_ERROR") - .timer().count()).isEqualTo(1); + assertThat(this.registry.get("http.client.requests") + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "IO_ERROR").timer().count()) + .isEqualTo(1); } @Test public void filterWhenExceptionThrownShouldRecordTimer() { - ClientRequest request = ClientRequest.create(HttpMethod.GET, - URI.create("https://example.com/projects/spring-boot")).build(); + ClientRequest request = ClientRequest + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException()); - this.filterFunction.filter(request, exchange) - .onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()) + this.filterFunction.filter(request, exchange).onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()) .block(Duration.ofSeconds(30)); - assertThat(this.registry - .get("http.client.requests").tags("method", "GET", "uri", - "/projects/spring-boot", "status", "CLIENT_ERROR") - .timer().count()).isEqualTo(1); + assertThat(this.registry.get("http.client.requests") + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer().count()) + .isEqualTo(1); } @Test public void filterWhenExceptionAndRetryShouldNotCumulateRecordTime() { - ClientRequest request = ClientRequest.create(HttpMethod.GET, - URI.create("https://example.com/projects/spring-boot")).build(); + ClientRequest request = ClientRequest + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException()) .delaySubscription(Duration.ofMillis(300)).cast(ClientResponse.class); this.filterFunction.filter(request, exchange).retry(1) - .onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()) - .block(Duration.ofSeconds(30)); - Timer timer = this.registry.get("http.client.requests").tags("method", "GET", - "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer(); + .onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()).block(Duration.ofSeconds(30)); + Timer timer = this.registry.get("http.client.requests") + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer(); assertThat(timer.count()).isEqualTo(2); assertThat(timer.max(TimeUnit.MILLISECONDS)).isLessThan(600); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java index 1bd2fede570..c438e19ae6a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java @@ -41,8 +41,7 @@ import static org.mockito.Mockito.mock; */ public class WebClientExchangeTagsTests { - private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() - + ".uriTemplate"; + private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; private ClientRequest request; @@ -50,62 +49,49 @@ public class WebClientExchangeTagsTests { @BeforeEach public void setup() { - this.request = ClientRequest - .create(HttpMethod.GET, - URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, - "https://example.org/projects/{project}") - .build(); + this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) + .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}").build(); this.response = mock(ClientResponse.class); given(this.response.statusCode()).willReturn(HttpStatus.OK); } @Test public void method() { - assertThat(WebClientExchangeTags.method(this.request)) - .isEqualTo(Tag.of("method", "GET")); + assertThat(WebClientExchangeTags.method(this.request)).isEqualTo(Tag.of("method", "GET")); } @Test public void uriWhenAbsoluteTemplateIsAvailableShouldReturnTemplate() { - assertThat(WebClientExchangeTags.uri(this.request)) - .isEqualTo(Tag.of("uri", "/projects/{project}")); + assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/{project}")); } @Test public void uriWhenRelativeTemplateIsAvailableShouldReturnTemplate() { - this.request = ClientRequest - .create(HttpMethod.GET, - URI.create("https://example.org/projects/spring-boot")) + this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); - assertThat(WebClientExchangeTags.uri(this.request)) - .isEqualTo(Tag.of("uri", "/projects/{project}")); + assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/{project}")); } @Test public void uriWhenTemplateIsMissingShouldReturnPath() { - this.request = ClientRequest.create(HttpMethod.GET, - URI.create("https://example.org/projects/spring-boot")).build(); - assertThat(WebClientExchangeTags.uri(this.request)) - .isEqualTo(Tag.of("uri", "/projects/spring-boot")); + this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) + .build(); + assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/spring-boot")); } @Test public void clientName() { - assertThat(WebClientExchangeTags.clientName(this.request)) - .isEqualTo(Tag.of("clientName", "example.org")); + assertThat(WebClientExchangeTags.clientName(this.request)).isEqualTo(Tag.of("clientName", "example.org")); } @Test public void status() { - assertThat(WebClientExchangeTags.status(this.response)) - .isEqualTo(Tag.of("status", "200")); + assertThat(WebClientExchangeTags.status(this.response)).isEqualTo(Tag.of("status", "200")); } @Test public void statusWhenIOException() { - assertThat(WebClientExchangeTags.status(new IOException())) - .isEqualTo(Tag.of("status", "IO_ERROR")); + assertThat(WebClientExchangeTags.status(new IOException())).isEqualTo(Tag.of("status", "IO_ERROR")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java index 3a902b7d4ed..112b5e17903 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java @@ -50,18 +50,14 @@ public class MetricsWebFilterTests { public void setup() { MockClock clock = new MockClock(); this.registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, clock); - this.webFilter = new MetricsWebFilter(this.registry, - new DefaultWebFluxTagsProvider(), REQUEST_METRICS_NAME, + this.webFilter = new MetricsWebFilter(this.registry, new DefaultWebFluxTagsProvider(), REQUEST_METRICS_NAME, AutoTimer.ENABLED); } @Test public void filterAddsTagsToRegistry() { - MockServerWebExchange exchange = createExchange("/projects/spring-boot", - "/projects/{project}"); - this.webFilter - .filter(exchange, - (serverWebExchange) -> exchange.getResponse().setComplete()) + MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); + this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "200"); @@ -69,12 +65,8 @@ public class MetricsWebFilterTests { @Test public void filterAddsTagsToRegistryForExceptions() { - MockServerWebExchange exchange = createExchange("/projects/spring-boot", - "/projects/{project}"); - this.webFilter - .filter(exchange, - (serverWebExchange) -> Mono - .error(new IllegalStateException("test error"))) + MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); + this.webFilter.filter(exchange, (serverWebExchange) -> Mono.error(new IllegalStateException("test error"))) .onErrorResume((t) -> { exchange.getResponse().setStatusCodeValue(500); return exchange.getResponse().setComplete(); @@ -89,13 +81,11 @@ public class MetricsWebFilterTests { final Exception anonymous = new Exception("test error") { }; - MockServerWebExchange exchange = createExchange("/projects/spring-boot", - "/projects/{project}"); - this.webFilter.filter(exchange, (serverWebExchange) -> Mono.error(anonymous)) - .onErrorResume((t) -> { - exchange.getResponse().setStatusCodeValue(500); - return exchange.getResponse().setComplete(); - }).block(Duration.ofSeconds(30)); + MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); + this.webFilter.filter(exchange, (serverWebExchange) -> Mono.error(anonymous)).onErrorResume((t) -> { + exchange.getResponse().setStatusCodeValue(500); + return exchange.getResponse().setComplete(); + }).block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "500"); assertMetricsContainsTag("exception", anonymous.getClass().getName()); @@ -103,12 +93,10 @@ public class MetricsWebFilterTests { @Test public void filterAddsTagsToRegistryForExceptionsAndCommittedResponse() { - MockServerWebExchange exchange = createExchange("/projects/spring-boot", - "/projects/{project}"); + MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.webFilter.filter(exchange, (serverWebExchange) -> { exchange.getResponse().setStatusCodeValue(500); - return exchange.getResponse().setComplete() - .then(Mono.error(new IllegalStateException("test error"))); + return exchange.getResponse().setComplete().then(Mono.error(new IllegalStateException("test error"))); }).onErrorResume((t) -> Mono.empty()).block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "500"); @@ -116,16 +104,13 @@ public class MetricsWebFilterTests { private MockServerWebExchange createExchange(String path, String pathPattern) { PathPatternParser parser = new PathPatternParser(); - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get(path).build()); - exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - parser.parse(pathPattern)); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path).build()); + exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, parser.parse(pathPattern)); return exchange; } private void assertMetricsContainsTag(String tagKey, String tagValue) { - assertThat(this.registry.get(REQUEST_METRICS_NAME).tag(tagKey, tagValue).timer() - .count()).isEqualTo(1); + assertThat(this.registry.get(REQUEST_METRICS_NAME).tag(tagKey, tagValue).timer().count()).isEqualTo(1); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java index 3d41f593233..26db50cdfe1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java @@ -51,8 +51,7 @@ public class WebFluxTagsTests { @Test public void uriTagValueIsBestMatchingPatternWhenAvailable() { - this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - this.parser.parse("/spring")); + this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring")); this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("/spring"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java index 160b78c728d..c185ef716d8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java @@ -87,13 +87,11 @@ public class LongTaskTimingHandlerInterceptorTests { public void asyncRequestThatThrowsUncheckedException() throws Exception { MvcResult result = this.mvc.perform(get("/api/c1/completableFutureException")) .andExpect(request().asyncStarted()).andReturn(); - assertThat(this.registry.get("my.long.request.exception").longTaskTimer() - .activeTasks()).isEqualTo(1); + assertThat(this.registry.get("my.long.request.exception").longTaskTimer().activeTasks()).isEqualTo(1); assertThatExceptionOfType(NestedServletException.class) .isThrownBy(() -> this.mvc.perform(asyncDispatch(result))) .withRootCauseInstanceOf(RuntimeException.class); - assertThat(this.registry.get("my.long.request.exception").longTaskTimer() - .activeTasks()).isEqualTo(0); + assertThat(this.registry.get("my.long.request.exception").longTaskTimer().activeTasks()).isEqualTo(0); } @Test @@ -101,8 +99,8 @@ public class LongTaskTimingHandlerInterceptorTests { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { - result.set(this.mvc.perform(get("/api/c1/callable/10")) - .andExpect(request().asyncStarted()).andReturn()); + result.set( + this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); } catch (Exception ex) { fail("Failed to execute async request", ex); @@ -110,13 +108,13 @@ public class LongTaskTimingHandlerInterceptorTests { }); backgroundRequest.start(); this.callableBarrier.await(); - assertThat(this.registry.get("my.long.request").tags("region", "test") - .longTaskTimer().activeTasks()).isEqualTo(1); + assertThat(this.registry.get("my.long.request").tags("region", "test").longTaskTimer().activeTasks()) + .isEqualTo(1); this.callableBarrier.await(); backgroundRequest.join(); this.mvc.perform(asyncDispatch(result.get())).andExpect(status().isOk()); - assertThat(this.registry.get("my.long.request").tags("region", "test") - .longTaskTimer().activeTasks()).isEqualTo(0); + assertThat(this.registry.get("my.long.request").tags("region", "test").longTaskTimer().activeTasks()) + .isEqualTo(0); } @Configuration(proxyBeanMethods = false) @@ -145,8 +143,8 @@ public class LongTaskTimingHandlerInterceptorTests { @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new LongTaskTimingHandlerInterceptor( - meterRegistry, new DefaultWebMvcTagsProvider())); + registry.addInterceptor( + new LongTaskTimingHandlerInterceptor(meterRegistry, new DefaultWebMvcTagsProvider())); } }; @@ -162,8 +160,7 @@ public class LongTaskTimingHandlerInterceptorTests { private CyclicBarrier callableBarrier; @Timed - @Timed(value = "my.long.request", extraTags = { "region", "test" }, - longTask = true) + @Timed(value = "my.long.request", extraTags = { "region", "test" }, longTask = true) @GetMapping("/callable/{id}") public Callable asyncCallable(@PathVariable Long id) throws Exception { this.callableBarrier.await(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java index 31d57ea08d9..c74649e8463 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java @@ -69,15 +69,13 @@ public class WebMvcMetricsFilterAutoTimedTests { @BeforeEach public void setupMockMvc() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filter).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filter).build(); } @Test public void metricsCanBeAutoTimed() throws Exception { this.mvc.perform(get("/api/10")).andExpect(status().isOk()); - Timer timer = this.registry.get("http.server.requests").tags("status", "200") - .timer(); + Timer timer = this.registry.get("http.server.requests").tags("status", "200").timer(); assertThat(timer.count()).isEqualTo(1L); HistogramSnapshot snapshot = timer.takeSnapshot(); assertThat(snapshot.percentileValues()).hasSize(2); @@ -101,12 +99,9 @@ public class WebMvcMetricsFilterAutoTimedTests { } @Bean - public WebMvcMetricsFilter webMetricsFilter(WebApplicationContext context, - MeterRegistry registry) { - return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), - "http.server.requests", - (builder) -> builder.publishPercentiles(0.5, 0.95) - .publishPercentileHistogram(true)); + public WebMvcMetricsFilter webMetricsFilter(WebApplicationContext context, MeterRegistry registry) { + return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), "http.server.requests", + (builder) -> builder.publishPercentiles(0.5, 0.95).publishPercentileHistogram(true)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java index d029de1d11f..1724f25060d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java @@ -130,74 +130,65 @@ public class WebMvcMetricsFilterTests { public void timedMethod() throws Exception { this.mvc.perform(get("/api/c1/10")).andExpect(status().isOk()); assertThat(this.registry.get("http.server.requests") - .tags("status", "200", "uri", "/api/c1/{id}", "public", "true").timer() - .count()).isEqualTo(1); + .tags("status", "200", "uri", "/api/c1/{id}", "public", "true").timer().count()).isEqualTo(1); } @Test public void subclassedTimedMethod() throws Exception { this.mvc.perform(get("/api/c1/metaTimed/10")).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests") - .tags("status", "200", "uri", "/api/c1/metaTimed/{id}").timer().count()) - .isEqualTo(1L); + assertThat(this.registry.get("http.server.requests").tags("status", "200", "uri", "/api/c1/metaTimed/{id}") + .timer().count()).isEqualTo(1L); } @Test public void untimedMethod() throws Exception { this.mvc.perform(get("/api/c1/untimed/10")).andExpect(status().isOk()); - assertThat(this.registry.find("http.server.requests") - .tags("uri", "/api/c1/untimed/10").timer()).isNull(); + assertThat(this.registry.find("http.server.requests").tags("uri", "/api/c1/untimed/10").timer()).isNull(); } @Test public void timedControllerClass() throws Exception { this.mvc.perform(get("/api/c2/10")).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests").tags("status", "200").timer() - .count()).isEqualTo(1L); + assertThat(this.registry.get("http.server.requests").tags("status", "200").timer().count()).isEqualTo(1L); } @Test public void badClientRequest() throws Exception { this.mvc.perform(get("/api/c1/oops")).andExpect(status().is4xxClientError()); - assertThat(this.registry.get("http.server.requests").tags("status", "400").timer() - .count()).isEqualTo(1L); + assertThat(this.registry.get("http.server.requests").tags("status", "400").timer().count()).isEqualTo(1L); } @Test public void redirectRequest() throws Exception { - this.mvc.perform(get("/api/redirect") - .header(RedirectAndNotFoundFilter.TEST_MISBEHAVE_HEADER, "302")) + this.mvc.perform(get("/api/redirect").header(RedirectAndNotFoundFilter.TEST_MISBEHAVE_HEADER, "302")) .andExpect(status().is3xxRedirection()); - assertThat(this.registry.get("http.server.requests").tags("uri", "REDIRECTION") - .tags("status", "302").timer()).isNotNull(); + assertThat(this.registry.get("http.server.requests").tags("uri", "REDIRECTION").tags("status", "302").timer()) + .isNotNull(); } @Test public void notFoundRequest() throws Exception { - this.mvc.perform(get("/api/not/found") - .header(RedirectAndNotFoundFilter.TEST_MISBEHAVE_HEADER, "404")) + this.mvc.perform(get("/api/not/found").header(RedirectAndNotFoundFilter.TEST_MISBEHAVE_HEADER, "404")) .andExpect(status().is4xxClientError()); - assertThat(this.registry.get("http.server.requests").tags("uri", "NOT_FOUND") - .tags("status", "404").timer()).isNotNull(); + assertThat(this.registry.get("http.server.requests").tags("uri", "NOT_FOUND").tags("status", "404").timer()) + .isNotNull(); } @Test public void unhandledError() { - assertThatCode(() -> this.mvc.perform(get("/api/c1/unhandledError/10")) - .andExpect(status().isOk())) - .hasRootCauseInstanceOf(RuntimeException.class); - assertThat(this.registry.get("http.server.requests") - .tags("exception", "RuntimeException").timer().count()).isEqualTo(1L); + assertThatCode(() -> this.mvc.perform(get("/api/c1/unhandledError/10")).andExpect(status().isOk())) + .hasRootCauseInstanceOf(RuntimeException.class); + assertThat(this.registry.get("http.server.requests").tags("exception", "RuntimeException").timer().count()) + .isEqualTo(1L); } @Test public void streamingError() throws Exception { - MvcResult result = this.mvc.perform(get("/api/c1/streamingError")) - .andExpect(request().asyncStarted()).andReturn(); - assertThatCode( - () -> this.mvc.perform(asyncDispatch(result)).andExpect(status().isOk())); - assertThat(this.registry.get("http.server.requests") - .tags("exception", "IOException").timer().count()).isEqualTo(1L); + MvcResult result = this.mvc.perform(get("/api/c1/streamingError")).andExpect(request().asyncStarted()) + .andReturn(); + assertThatCode(() -> this.mvc.perform(asyncDispatch(result)).andExpect(status().isOk())); + assertThat(this.registry.get("http.server.requests").tags("exception", "IOException").timer().count()) + .isEqualTo(1L); } @Test @@ -207,8 +198,7 @@ public class WebMvcMetricsFilterTests { } catch (Throwable ignore) { } - assertThat(this.registry.get("http.server.requests") - .tag("uri", "/api/c1/anonymousError/{id}").timer().getId() + assertThat(this.registry.get("http.server.requests").tag("uri", "/api/c1/anonymousError/{id}").timer().getId() .getTag("exception")).endsWith("$1"); } @@ -217,26 +207,24 @@ public class WebMvcMetricsFilterTests { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { - result.set(this.mvc.perform(get("/api/c1/callable/10")) - .andExpect(request().asyncStarted()).andReturn()); + result.set( + this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); } catch (Exception ex) { fail("Failed to execute async request", ex); } }); backgroundRequest.start(); - assertThat(this.registry.find("http.server.requests").tags("uri", "/api/c1/async") - .timer()).describedAs("Request isn't prematurely recorded as complete") - .isNull(); + assertThat(this.registry.find("http.server.requests").tags("uri", "/api/c1/async").timer()) + .describedAs("Request isn't prematurely recorded as complete").isNull(); // once the mapping completes, we can gather information about status, etc. this.callableBarrier.await(); MockClock.clock(this.registry).add(Duration.ofSeconds(2)); this.callableBarrier.await(); backgroundRequest.join(); this.mvc.perform(asyncDispatch(result.get())).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests").tags("status", "200") - .tags("uri", "/api/c1/callable/{id}").timer().totalTime(TimeUnit.SECONDS)) - .isEqualTo(2L); + assertThat(this.registry.get("http.server.requests").tags("status", "200").tags("uri", "/api/c1/callable/{id}") + .timer().totalTime(TimeUnit.SECONDS)).isEqualTo(2L); } @Test @@ -246,9 +234,8 @@ public class WebMvcMetricsFilterTests { assertThatExceptionOfType(NestedServletException.class) .isThrownBy(() -> this.mvc.perform(asyncDispatch(result))) .withRootCauseInstanceOf(RuntimeException.class); - assertThat(this.registry.get("http.server.requests") - .tags("uri", "/api/c1/completableFutureException").timer().count()) - .isEqualTo(1); + assertThat(this.registry.get("http.server.requests").tags("uri", "/api/c1/completableFutureException").timer() + .count()).isEqualTo(1); } @Test @@ -269,23 +256,21 @@ public class WebMvcMetricsFilterTests { this.completableFutureBarrier.await(); backgroundRequest.join(); this.mvc.perform(asyncDispatch(result.get())).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests") - .tags("uri", "/api/c1/completableFuture/{id}").timer() + assertThat(this.registry.get("http.server.requests").tags("uri", "/api/c1/completableFuture/{id}").timer() .totalTime(TimeUnit.SECONDS)).isEqualTo(2); } @Test public void endpointThrowsError() throws Exception { this.mvc.perform(get("/api/c1/error/10")).andExpect(status().is4xxClientError()); - assertThat(this.registry.get("http.server.requests").tags("status", "422").timer() - .count()).isEqualTo(1L); + assertThat(this.registry.get("http.server.requests").tags("status", "422").timer().count()).isEqualTo(1L); } @Test public void regexBasedRequestMapping() throws Exception { this.mvc.perform(get("/api/c1/regex/.abc")).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests") - .tags("uri", "/api/c1/regex/{id:\\.[a-z]+}").timer().count()) + assertThat( + this.registry.get("http.server.requests").tags("uri", "/api/c1/regex/{id:\\.[a-z]+}").timer().count()) .isEqualTo(1L); } @@ -335,16 +320,15 @@ public class WebMvcMetricsFilterTests { @Bean PrometheusMeterRegistry prometheus(Clock clock) { - PrometheusMeterRegistry r = new PrometheusMeterRegistry( - PrometheusConfig.DEFAULT, new CollectorRegistry(), clock); + PrometheusMeterRegistry r = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT, new CollectorRegistry(), + clock); r.config().meterFilter(new MeterFilter() { @Override @NonNull public MeterFilterReply accept(@NonNull Meter.Id id) { for (Tag tag : id.getTags()) { if (tag.getKey().equals("uri") - && (tag.getValue().contains("histogram") - || tag.getValue().contains("percentiles"))) { + && (tag.getValue().contains("histogram") || tag.getValue().contains("percentiles"))) { return MeterFilterReply.ACCEPT; } } @@ -370,10 +354,9 @@ public class WebMvcMetricsFilterTests { } @Bean - WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, - WebApplicationContext ctx) { - return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), - "http.server.requests", AutoTimer.ENABLED); + WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, WebApplicationContext ctx) { + return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), "http.server.requests", + AutoTimer.ENABLED); } } @@ -397,8 +380,7 @@ public class WebMvcMetricsFilterTests { } @Timed - @Timed(value = "my.long.request", extraTags = { "region", "test" }, - longTask = true) + @Timed(value = "my.long.request", extraTags = { "region", "test" }, longTask = true) @GetMapping("/callable/{id}") public Callable asyncCallable(@PathVariable Long id) throws Exception { this.callableBarrier.await(); @@ -415,8 +397,7 @@ public class WebMvcMetricsFilterTests { @Timed @GetMapping("/completableFuture/{id}") - CompletableFuture asyncCompletableFuture(@PathVariable Long id) - throws Exception { + CompletableFuture asyncCompletableFuture(@PathVariable Long id) throws Exception { this.completableFutureBarrier.await(); return CompletableFuture.supplyAsync(() -> { try { @@ -451,8 +432,7 @@ public class WebMvcMetricsFilterTests { @Timed @GetMapping("/anonymousError/{id}") - public String alwaysThrowsAnonymousException(@PathVariable Long id) - throws Exception { + public String alwaysThrowsAnonymousException(@PathVariable Long id) throws Exception { throw new Exception("this exception won't have a simple class name") { }; } @@ -466,8 +446,7 @@ public class WebMvcMetricsFilterTests { @GetMapping("/streamingError") public ResponseBodyEmitter streamingError() { ResponseBodyEmitter emitter = new ResponseBodyEmitter(); - emitter.completeWithError( - new IOException("error while writing to the response")); + emitter.completeWithError(new IOException("error while writing to the response")); return emitter; } @@ -520,9 +499,8 @@ public class WebMvcMetricsFilterTests { static final String TEST_MISBEHAVE_HEADER = "x-test-misbehave-status"; @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { String misbehave = request.getHeader(TEST_MISBEHAVE_HEADER); if (misbehave != null) { response.setStatus(Integer.parseInt(misbehave)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java index c7469e517b0..7353fce9bb0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java @@ -73,25 +73,21 @@ public class WebMvcMetricsIntegrationTests { @BeforeEach public void setupMockMvc() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filter).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filter).build(); } @Test public void handledExceptionIsRecordedInMetricTag() throws Exception { this.mvc.perform(get("/api/handledError")).andExpect(status().is5xxServerError()); - assertThat(this.registry.get("http.server.requests") - .tags("exception", "Exception1", "status", "500").timer().count()) - .isEqualTo(1L); + assertThat(this.registry.get("http.server.requests").tags("exception", "Exception1", "status", "500").timer() + .count()).isEqualTo(1L); } @Test public void rethrownExceptionIsRecordedInMetricTag() { - assertThatCode(() -> this.mvc.perform(get("/api/rethrownError")) - .andExpect(status().is5xxServerError())); - assertThat(this.registry.get("http.server.requests") - .tags("exception", "Exception2", "status", "500").timer().count()) - .isEqualTo(1L); + assertThatCode(() -> this.mvc.perform(get("/api/rethrownError")).andExpect(status().is5xxServerError())); + assertThat(this.registry.get("http.server.requests").tags("exception", "Exception2", "status", "500").timer() + .count()).isEqualTo(1L); } @Configuration(proxyBeanMethods = false) @@ -109,10 +105,9 @@ public class WebMvcMetricsIntegrationTests { } @Bean - public WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, - WebApplicationContext ctx) { - return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), - "http.server.requests", AutoTimer.ENABLED); + public WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, WebApplicationContext ctx) { + return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), "http.server.requests", + AutoTimer.ENABLED); } @Configuration(proxyBeanMethods = false) @@ -153,8 +148,7 @@ public class WebMvcMetricsIntegrationTests { @ExceptionHandler ResponseEntity handleError(Exception1 ex) { - return new ResponseEntity<>("this is a custom exception body", - HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>("this is a custom exception body", HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java index b1f68e8dcde..669d53e3982 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java @@ -64,13 +64,11 @@ public class MongoHealthIndicatorTests { @Test public void mongoIsDown() { MongoTemplate mongoTemplate = mock(MongoTemplate.class); - given(mongoTemplate.executeCommand("{ buildInfo: 1 }")) - .willThrow(new MongoException("Connection failed")); + given(mongoTemplate.executeCommand("{ buildInfo: 1 }")).willThrow(new MongoException("Connection failed")); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); verify(mongoTemplate).executeCommand("{ buildInfo: 1 }"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java index fe7e0a76755..761ff40fba0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java @@ -42,8 +42,7 @@ public class MongoReactiveHealthIndicatorTests { Document buildInfo = mock(Document.class); given(buildInfo.getString("version")).willReturn("2.6.4"); ReactiveMongoTemplate reactiveMongoTemplate = mock(ReactiveMongoTemplate.class); - given(reactiveMongoTemplate.executeCommand("{ buildInfo: 1 }")) - .willReturn(Mono.just(buildInfo)); + given(reactiveMongoTemplate.executeCommand("{ buildInfo: 1 }")).willReturn(Mono.just(buildInfo)); MongoReactiveHealthIndicator mongoReactiveHealthIndicator = new MongoReactiveHealthIndicator( reactiveMongoTemplate); Mono health = mongoReactiveHealthIndicator.health(); @@ -65,8 +64,7 @@ public class MongoReactiveHealthIndicatorTests { StepVerifier.create(health).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.DOWN); assertThat(h.getDetails()).containsOnlyKeys("error"); - assertThat(h.getDetails().get("error")) - .isEqualTo(MongoException.class.getName() + ": Connection failed"); + assertThat(h.getDetails().get("error")).isEqualTo(MongoException.class.getName() + ": Connection failed"); }).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java index 0381288376c..46c9c74dd20 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java @@ -61,8 +61,7 @@ public class Neo4jHealthIndicatorTests { @Test public void neo4jUp() { Result result = mock(Result.class); - given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())) - .willReturn(result); + given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())).willReturn(result); int nodeCount = 500; Map expectedCypherDetails = new HashMap<>(); expectedCypherDetails.put("nodes", nodeCount); @@ -78,10 +77,9 @@ public class Neo4jHealthIndicatorTests { @Test public void neo4jDown() { - CypherException cypherException = new CypherException( - "Neo.ClientError.Statement.SyntaxError", "Error executing Cypher"); - given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())) - .willThrow(cypherException); + CypherException cypherException = new CypherException("Neo.ClientError.Statement.SyntaxError", + "Error executing Cypher"); + given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())).willThrow(cypherException); Health health = this.neo4jHealthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java index d5db2b02094..bd887a27a69 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java @@ -61,18 +61,15 @@ public class RedisHealthIndicatorTests { @Test public void redisIsDown() { RedisConnection redisConnection = mock(RedisConnection.class); - given(redisConnection.info()) - .willThrow(new RedisConnectionFailureException("Connection failed")); + given(redisConnection.info()).willThrow(new RedisConnectionFailureException("Connection failed")); RedisHealthIndicator healthIndicator = createHealthIndicator(redisConnection); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); } private RedisHealthIndicator createHealthIndicator(RedisConnection redisConnection) { - RedisConnectionFactory redisConnectionFactory = mock( - RedisConnectionFactory.class); + RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); given(redisConnectionFactory.getConnection()).willReturn(redisConnection); return new RedisHealthIndicator(redisConnectionFactory); } @@ -83,18 +80,14 @@ public class RedisHealthIndicatorTests { clusterProperties.setProperty("cluster_size", "4"); clusterProperties.setProperty("cluster_slots_ok", "4"); clusterProperties.setProperty("cluster_slots_fail", "0"); - List redisMasterNodes = Arrays.asList( - new RedisClusterNode("127.0.0.1", 7001), + List redisMasterNodes = Arrays.asList(new RedisClusterNode("127.0.0.1", 7001), new RedisClusterNode("127.0.0.2", 7001)); RedisClusterConnection redisConnection = mock(RedisClusterConnection.class); given(redisConnection.clusterGetNodes()).willReturn(redisMasterNodes); - given(redisConnection.clusterGetClusterInfo()) - .willReturn(new ClusterInfo(clusterProperties)); - RedisConnectionFactory redisConnectionFactory = mock( - RedisConnectionFactory.class); + given(redisConnection.clusterGetClusterInfo()).willReturn(new ClusterInfo(clusterProperties)); + RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); given(redisConnectionFactory.getConnection()).willReturn(redisConnection); - RedisHealthIndicator healthIndicator = new RedisHealthIndicator( - redisConnectionFactory); + RedisHealthIndicator healthIndicator = new RedisHealthIndicator(redisConnectionFactory); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java index cb88aa54982..305c9a092e8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java @@ -53,8 +53,7 @@ public class RedisReactiveHealthIndicatorTests { given(redisConnection.closeLater()).willReturn(Mono.empty()); ReactiveServerCommands commands = mock(ReactiveServerCommands.class); given(commands.info()).willReturn(Mono.just(info)); - RedisReactiveHealthIndicator healthIndicator = createHealthIndicator( - redisConnection, commands); + RedisReactiveHealthIndicator healthIndicator = createHealthIndicator(redisConnection, commands); Mono health = healthIndicator.health(); StepVerifier.create(health).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); @@ -67,39 +66,31 @@ public class RedisReactiveHealthIndicatorTests { @Test public void redisCommandIsDown() { ReactiveServerCommands commands = mock(ReactiveServerCommands.class); - given(commands.info()).willReturn( - Mono.error(new RedisConnectionFailureException("Connection failed"))); + given(commands.info()).willReturn(Mono.error(new RedisConnectionFailureException("Connection failed"))); ReactiveRedisConnection redisConnection = mock(ReactiveRedisConnection.class); given(redisConnection.closeLater()).willReturn(Mono.empty()); - RedisReactiveHealthIndicator healthIndicator = createHealthIndicator( - redisConnection, commands); + RedisReactiveHealthIndicator healthIndicator = createHealthIndicator(redisConnection, commands); Mono health = healthIndicator.health(); - StepVerifier.create(health) - .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) .verifyComplete(); verify(redisConnection).closeLater(); } @Test public void redisConnectionIsDown() { - ReactiveRedisConnectionFactory redisConnectionFactory = mock( - ReactiveRedisConnectionFactory.class); - given(redisConnectionFactory.getReactiveConnection()).willThrow( - new RedisConnectionException("Unable to connect to localhost:6379")); - RedisReactiveHealthIndicator healthIndicator = new RedisReactiveHealthIndicator( - redisConnectionFactory); + ReactiveRedisConnectionFactory redisConnectionFactory = mock(ReactiveRedisConnectionFactory.class); + given(redisConnectionFactory.getReactiveConnection()) + .willThrow(new RedisConnectionException("Unable to connect to localhost:6379")); + RedisReactiveHealthIndicator healthIndicator = new RedisReactiveHealthIndicator(redisConnectionFactory); Mono health = healthIndicator.health(); - StepVerifier.create(health) - .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) .verifyComplete(); } - private RedisReactiveHealthIndicator createHealthIndicator( - ReactiveRedisConnection redisConnection, + private RedisReactiveHealthIndicator createHealthIndicator(ReactiveRedisConnection redisConnection, ReactiveServerCommands serverCommands) { - ReactiveRedisConnectionFactory redisConnectionFactory = mock( - ReactiveRedisConnectionFactory.class); + ReactiveRedisConnectionFactory redisConnectionFactory = mock(ReactiveRedisConnectionFactory.class); given(redisConnectionFactory.getReactiveConnection()).willReturn(redisConnection); given(redisConnection.serverCommands()).willReturn(serverCommands); return new RedisReactiveHealthIndicator(redisConnectionFactory); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java index f3c5214ceeb..d08ce24675d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java @@ -59,11 +59,9 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedRate()).isEmpty(); assertThat(tasks.getCustom()).isEmpty(); assertThat(tasks.getCron()).hasSize(1); - CronTaskDescription description = (CronTaskDescription) tasks.getCron() - .get(0); + CronTaskDescription description = (CronTaskDescription) tasks.getCron().get(0); assertThat(description.getExpression()).isEqualTo("0 0 0/3 1/1 * ?"); - assertThat(description.getRunnable().getTarget()) - .isEqualTo(CronScheduledMethod.class.getName() + ".cron"); + assertThat(description.getRunnable().getTarget()).isEqualTo(CronScheduledMethod.class.getName() + ".cron"); }); } @@ -74,11 +72,9 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedDelay()).isEmpty(); assertThat(tasks.getCustom()).isEmpty(); assertThat(tasks.getCron()).hasSize(1); - CronTaskDescription description = (CronTaskDescription) tasks.getCron() - .get(0); + CronTaskDescription description = (CronTaskDescription) tasks.getCron().get(0); assertThat(description.getExpression()).isEqualTo("0 0 0/6 1/1 * ?"); - assertThat(description.getRunnable().getTarget()) - .isEqualTo(CronTriggerRunnable.class.getName()); + assertThat(description.getRunnable().getTarget()).isEqualTo(CronTriggerRunnable.class.getName()); }); } @@ -89,8 +85,7 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedRate()).isEmpty(); assertThat(tasks.getCustom()).isEmpty(); assertThat(tasks.getFixedDelay()).hasSize(1); - FixedDelayTaskDescription description = (FixedDelayTaskDescription) tasks - .getFixedDelay().get(0); + FixedDelayTaskDescription description = (FixedDelayTaskDescription) tasks.getFixedDelay().get(0); assertThat(description.getInitialDelay()).isEqualTo(2); assertThat(description.getInterval()).isEqualTo(1); assertThat(description.getRunnable().getTarget()) @@ -105,12 +100,10 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedRate()).isEmpty(); assertThat(tasks.getCustom()).isEmpty(); assertThat(tasks.getFixedDelay()).hasSize(1); - FixedDelayTaskDescription description = (FixedDelayTaskDescription) tasks - .getFixedDelay().get(0); + FixedDelayTaskDescription description = (FixedDelayTaskDescription) tasks.getFixedDelay().get(0); assertThat(description.getInitialDelay()).isEqualTo(2000); assertThat(description.getInterval()).isEqualTo(1000); - assertThat(description.getRunnable().getTarget()) - .isEqualTo(FixedDelayTriggerRunnable.class.getName()); + assertThat(description.getRunnable().getTarget()).isEqualTo(FixedDelayTriggerRunnable.class.getName()); }); } @@ -121,8 +114,7 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedDelay()).isEmpty(); assertThat(tasks.getCustom()).isEmpty(); assertThat(tasks.getFixedRate()).hasSize(1); - FixedRateTaskDescription description = (FixedRateTaskDescription) tasks - .getFixedRate().get(0); + FixedRateTaskDescription description = (FixedRateTaskDescription) tasks.getFixedRate().get(0); assertThat(description.getInitialDelay()).isEqualTo(4); assertThat(description.getInterval()).isEqualTo(3); assertThat(description.getRunnable().getTarget()) @@ -137,12 +129,10 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedDelay()).isEmpty(); assertThat(tasks.getCustom()).isEmpty(); assertThat(tasks.getFixedRate()).hasSize(1); - FixedRateTaskDescription description = (FixedRateTaskDescription) tasks - .getFixedRate().get(0); + FixedRateTaskDescription description = (FixedRateTaskDescription) tasks.getFixedRate().get(0); assertThat(description.getInitialDelay()).isEqualTo(3000); assertThat(description.getInterval()).isEqualTo(2000); - assertThat(description.getRunnable().getTarget()) - .isEqualTo(FixedRateTriggerRunnable.class.getName()); + assertThat(description.getRunnable().getTarget()).isEqualTo(FixedRateTriggerRunnable.class.getName()); }); } @@ -153,18 +143,15 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedDelay()).isEmpty(); assertThat(tasks.getFixedRate()).isEmpty(); assertThat(tasks.getCustom()).hasSize(1); - CustomTriggerTaskDescription description = (CustomTriggerTaskDescription) tasks - .getCustom().get(0); - assertThat(description.getRunnable().getTarget()) - .isEqualTo(CustomTriggerRunnable.class.getName()); - assertThat(description.getTrigger()) - .isEqualTo(CustomTriggerTask.trigger.toString()); + CustomTriggerTaskDescription description = (CustomTriggerTaskDescription) tasks.getCustom().get(0); + assertThat(description.getRunnable().getTarget()).isEqualTo(CustomTriggerRunnable.class.getName()); + assertThat(description.getTrigger()).isEqualTo(CustomTriggerTask.trigger.toString()); }); } private void run(Class configuration, Consumer consumer) { - this.contextRunner.withUserConfiguration(configuration).run((context) -> consumer - .accept(context.getBean(ScheduledTasksEndpoint.class).scheduledTasks())); + this.contextRunner.withUserConfiguration(configuration) + .run((context) -> consumer.accept(context.getBean(ScheduledTasksEndpoint.class).scheduledTasks())); } @Configuration(proxyBeanMethods = false) @@ -172,8 +159,7 @@ public class ScheduledTasksEndpointTests { static class BaseConfiguration { @Bean - public ScheduledTasksEndpoint endpoint( - Collection scheduledTaskHolders) { + public ScheduledTasksEndpoint endpoint(Collection scheduledTaskHolders) { return new ScheduledTasksEndpoint(scheduledTaskHolders); } @@ -233,8 +219,7 @@ public class ScheduledTasksEndpointTests { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { - taskRegistrar.addTriggerTask(new CronTriggerRunnable(), - new CronTrigger("0 0 0/6 1/1 * ?")); + taskRegistrar.addTriggerTask(new CronTriggerRunnable(), new CronTrigger("0 0 0/6 1/1 * ?")); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java index 1485fc01ac7..f1d2ebede30 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java @@ -46,8 +46,7 @@ public class AuthenticationAuditListenerTests { private final AuthenticationAuditListener listener = new AuthenticationAuditListener(); - private final ApplicationEventPublisher publisher = mock( - ApplicationEventPublisher.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @BeforeEach public void init() { @@ -57,10 +56,8 @@ public class AuthenticationAuditListenerTests { @Test public void testAuthenticationSuccess() { AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationSuccessEvent( - new UsernamePasswordAuthenticationToken("user", "password"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SUCCESS); + new AuthenticationSuccessEvent(new UsernamePasswordAuthenticationToken("user", "password"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SUCCESS); } @Test @@ -73,53 +70,40 @@ public class AuthenticationAuditListenerTests { @Test public void testAuthenticationFailed() { - AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationFailureExpiredEvent( - new UsernamePasswordAuthenticationToken("user", "password"), - new BadCredentialsException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); + AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationFailureExpiredEvent( + new UsernamePasswordAuthenticationToken("user", "password"), new BadCredentialsException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); } @Test public void testAuthenticationSwitch() { AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationSwitchUserEvent( - new UsernamePasswordAuthenticationToken("user", "password"), - new User("user", "password", AuthorityUtils - .commaSeparatedStringToAuthorityList("USER")))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); + new AuthenticationSwitchUserEvent(new UsernamePasswordAuthenticationToken("user", "password"), + new User("user", "password", AuthorityUtils.commaSeparatedStringToAuthorityList("USER")))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); } @Test public void testAuthenticationSwitchBackToAnonymous() { AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationSwitchUserEvent( - new UsernamePasswordAuthenticationToken("user", "password"), - null)); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); + new AuthenticationSwitchUserEvent(new UsernamePasswordAuthenticationToken("user", "password"), null)); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); } @Test public void testDetailsAreIncludedInAuditEvent() { Object details = new Object(); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "user", "password"); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", + "password"); authentication.setDetails(details); AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationFailureExpiredEvent(authentication, - new BadCredentialsException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); + new AuthenticationFailureExpiredEvent(authentication, new BadCredentialsException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); assertThat(event.getAuditEvent().getData()).containsEntry("details", details); } - private AuditApplicationEvent handleAuthenticationEvent( - AbstractAuthenticationEvent event) { - ArgumentCaptor eventCaptor = ArgumentCaptor - .forClass(AuditApplicationEvent.class); + private AuditApplicationEvent handleAuthenticationEvent(AbstractAuthenticationEvent event) { + ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class); this.listener.onApplicationEvent(event); verify(this.publisher).publishEvent(eventCaptor.capture()); return eventCaptor.getValue(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java index 4fda44ac1d2..2aee13e0072 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java @@ -43,8 +43,7 @@ public class AuthorizationAuditListenerTests { private final AuthorizationAuditListener listener = new AuthorizationAuditListener(); - private final ApplicationEventPublisher publisher = mock( - ApplicationEventPublisher.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @BeforeEach public void init() { @@ -54,43 +53,34 @@ public class AuthorizationAuditListenerTests { @Test public void testAuthenticationCredentialsNotFound() { AuditApplicationEvent event = handleAuthorizationEvent( - new AuthenticationCredentialsNotFoundEvent(this, - Collections.singletonList(new SecurityConfig("USER")), + new AuthenticationCredentialsNotFoundEvent(this, Collections.singletonList(new SecurityConfig("USER")), new AuthenticationCredentialsNotFoundException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); } @Test public void testAuthorizationFailure() { - AuditApplicationEvent event = handleAuthorizationEvent( - new AuthorizationFailureEvent(this, - Collections.singletonList(new SecurityConfig("USER")), - new UsernamePasswordAuthenticationToken("user", "password"), - new AccessDeniedException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); + AuditApplicationEvent event = handleAuthorizationEvent(new AuthorizationFailureEvent(this, + Collections.singletonList(new SecurityConfig("USER")), + new UsernamePasswordAuthenticationToken("user", "password"), new AccessDeniedException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); } @Test public void testDetailsAreIncludedInAuditEvent() { Object details = new Object(); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "user", "password"); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", + "password"); authentication.setDetails(details); AuditApplicationEvent event = handleAuthorizationEvent( - new AuthorizationFailureEvent(this, - Collections.singletonList(new SecurityConfig("USER")), + new AuthorizationFailureEvent(this, Collections.singletonList(new SecurityConfig("USER")), authentication, new AccessDeniedException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); assertThat(event.getAuditEvent().getData()).containsEntry("details", details); } - private AuditApplicationEvent handleAuthorizationEvent( - AbstractAuthorizationEvent event) { - ArgumentCaptor eventCaptor = ArgumentCaptor - .forClass(AuditApplicationEvent.class); + private AuditApplicationEvent handleAuthorizationEvent(AbstractAuthorizationEvent event) { + ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class); this.listener.onApplicationEvent(event); verify(this.publisher).publishEvent(eventCaptor.capture()); return eventCaptor.getValue(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java index bd91a73e6ce..bbf12c3996e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class SessionsEndpointTests { private static final Session session = new MapSession(); @SuppressWarnings("unchecked") - private final FindByIndexNameSessionRepository repository = mock( - FindByIndexNameSessionRepository.class); + private final FindByIndexNameSessionRepository repository = mock(FindByIndexNameSessionRepository.class); private final SessionsEndpoint endpoint = new SessionsEndpoint(this.repository); @@ -50,17 +49,13 @@ public class SessionsEndpointTests { public void sessionsForUsername() { given(this.repository.findByPrincipalName("user")) .willReturn(Collections.singletonMap(session.getId(), session)); - List result = this.endpoint.sessionsForUsername("user") - .getSessions(); + List result = this.endpoint.sessionsForUsername("user").getSessions(); assertThat(result).hasSize(1); assertThat(result.get(0).getId()).isEqualTo(session.getId()); - assertThat(result.get(0).getAttributeNames()) - .isEqualTo(session.getAttributeNames()); + assertThat(result.get(0).getAttributeNames()).isEqualTo(session.getAttributeNames()); assertThat(result.get(0).getCreationTime()).isEqualTo(session.getCreationTime()); - assertThat(result.get(0).getLastAccessedTime()) - .isEqualTo(session.getLastAccessedTime()); - assertThat(result.get(0).getMaxInactiveInterval()) - .isEqualTo(session.getMaxInactiveInterval().getSeconds()); + assertThat(result.get(0).getLastAccessedTime()).isEqualTo(session.getLastAccessedTime()); + assertThat(result.get(0).getMaxInactiveInterval()).isEqualTo(session.getMaxInactiveInterval().getSeconds()); assertThat(result.get(0).isExpired()).isEqualTo(session.isExpired()); } @@ -72,8 +67,7 @@ public class SessionsEndpointTests { assertThat(result.getAttributeNames()).isEqualTo(session.getAttributeNames()); assertThat(result.getCreationTime()).isEqualTo(session.getCreationTime()); assertThat(result.getLastAccessedTime()).isEqualTo(session.getLastAccessedTime()); - assertThat(result.getMaxInactiveInterval()) - .isEqualTo(session.getMaxInactiveInterval().getSeconds()); + assertThat(result.getMaxInactiveInterval()).isEqualTo(session.getMaxInactiveInterval().getSeconds()); assertThat(result.isExpired()).isEqualTo(session.isExpired()); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java index b2e5177be34..0324e3dfca5 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java @@ -52,35 +52,28 @@ public class SessionsEndpointWebIntegrationTests { @Test public void sessionsForUsernameWithoutUsernameParam() { - client.get().uri((builder) -> builder.path("/actuator/sessions").build()) - .exchange().expectStatus().isBadRequest(); + client.get().uri((builder) -> builder.path("/actuator/sessions").build()).exchange().expectStatus() + .isBadRequest(); } @Test public void sessionsForUsernameNoResults() { given(repository.findByPrincipalName("user")).willReturn(Collections.emptyMap()); - client.get() - .uri((builder) -> builder.path("/actuator/sessions") - .queryParam("username", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("sessions") - .isEmpty(); + client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) + .exchange().expectStatus().isOk().expectBody().jsonPath("sessions").isEmpty(); } @Test public void sessionsForUsernameFound() { - given(repository.findByPrincipalName("user")) - .willReturn(Collections.singletonMap(session.getId(), session)); - client.get() - .uri((builder) -> builder.path("/actuator/sessions") - .queryParam("username", "user").build()) + given(repository.findByPrincipalName("user")).willReturn(Collections.singletonMap(session.getId(), session)); + client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) .exchange().expectStatus().isOk().expectBody().jsonPath("sessions.[*].id") .isEqualTo(new JSONArray().appendElement(session.getId())); } @Test public void sessionForIdNotFound() { - client.get().uri((builder) -> builder - .path("/actuator/sessions/session-id-not-found").build()).exchange() + client.get().uri((builder) -> builder.path("/actuator/sessions/session-id-not-found").build()).exchange() .expectStatus().isNotFound(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java index 2005e41b697..c9dfac1236f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java @@ -53,8 +53,7 @@ public class SolrHealthIndicatorTests { @Test public void solrIsUp() throws Exception { SolrClient solrClient = mock(SolrClient.class); - given(solrClient.request(any(CoreAdminRequest.class), isNull())) - .willReturn(mockResponse(0)); + given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(0)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -64,8 +63,7 @@ public class SolrHealthIndicatorTests { @Test public void solrIsUpAndRequestFailed() throws Exception { SolrClient solrClient = mock(SolrClient.class); - given(solrClient.request(any(CoreAdminRequest.class), isNull())) - .willReturn(mockResponse(400)); + given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(400)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -80,8 +78,7 @@ public class SolrHealthIndicatorTests { SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); } private NamedList mockResponse(int status) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java index 386aea5c097..6418fd385a2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java @@ -45,48 +45,42 @@ public class HttpExchangeTracerTests { @Test public void methodIsIncluded() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)) - .receivedRequest(createRequest()); + HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getMethod()).isEqualTo("GET"); } @Test public void uriIsIncluded() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)) - .receivedRequest(createRequest()); + HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getUri()).isEqualTo(URI.create("https://api.example.com")); } @Test public void remoteAddressIsNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)) - .receivedRequest(createRequest()); + HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getRemoteAddress()).isNull(); } @Test public void remoteAddressCanBeIncluded() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REMOTE_ADDRESS)) - .receivedRequest(createRequest()); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REMOTE_ADDRESS)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test public void requestHeadersAreNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)) - .receivedRequest(createRequest()); + HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @Test public void requestHeadersCanBeIncluded() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)) - .receivedRequest(createRequest()); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(HttpHeaders.ACCEPT); } @@ -96,8 +90,7 @@ public class HttpExchangeTracerTests { MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("to-remove", "test"); headers.add("test", "value"); - HttpTrace trace = new RequestHeadersFilterHttpExchangeTracer() - .receivedRequest(createRequest(headers)); + HttpTrace trace = new RequestHeadersFilterHttpExchangeTracer().receivedRequest(createRequest(headers)); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys("test", "to-add"); assertThat(request.getHeaders().get("test")).containsExactly("value"); @@ -106,78 +99,67 @@ public class HttpExchangeTracerTests { @Test public void authorizationHeaderIsNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)) - .receivedRequest(createRequest(Collections.singletonMap( - HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( + createRequest(Collections.singletonMap(HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @Test public void mixedCaseAuthorizationHeaderIsNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)) - .receivedRequest(createRequest(Collections.singletonMap( - mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( + createRequest(Collections.singletonMap(mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @Test public void authorizationHeaderCanBeIncluded() { - HttpTrace trace = new HttpExchangeTracer( - EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) - .receivedRequest(createRequest(Collections.singletonMap( - HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) + .receivedRequest( + createRequest(Collections.singletonMap(HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(HttpHeaders.AUTHORIZATION); } @Test public void mixedCaseAuthorizationHeaderCanBeIncluded() { - HttpTrace trace = new HttpExchangeTracer( - EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) - .receivedRequest(createRequest(Collections.singletonMap( - mixedCase(HttpHeaders.AUTHORIZATION), - Arrays.asList("secret")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) + .receivedRequest(createRequest( + Collections.singletonMap(mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); Request request = trace.getRequest(); - assertThat(request.getHeaders()) - .containsOnlyKeys(mixedCase(HttpHeaders.AUTHORIZATION)); + assertThat(request.getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.AUTHORIZATION)); } @Test public void cookieHeaderIsNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)) - .receivedRequest(createRequest(Collections - .singletonMap(HttpHeaders.COOKIE, Arrays.asList("test=test")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( + createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("test=test")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @Test public void mixedCaseCookieHeaderIsNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)) - .receivedRequest(createRequest(Collections.singletonMap( - mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( + createRequest(Collections.singletonMap(mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @Test public void cookieHeaderCanBeIncluded() { - HttpTrace trace = new HttpExchangeTracer( - EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) - .receivedRequest(createRequest(Collections.singletonMap( - HttpHeaders.COOKIE, Arrays.asList("value")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) + .receivedRequest(createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("value")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(HttpHeaders.COOKIE); } @Test public void mixedCaseCookieHeaderCanBeIncluded() { - HttpTrace trace = new HttpExchangeTracer( - EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) - .receivedRequest(createRequest(Collections.singletonMap( - mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) + .receivedRequest( + createRequest(Collections.singletonMap(mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.COOKIE)); } @@ -185,45 +167,39 @@ public class HttpExchangeTracerTests { @Test public void statusIsIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, - createResponse(), null, null); + new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getResponse().getStatus()).isEqualTo(204); } @Test public void responseHeadersAreNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, - createResponse(), null, null); + new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getResponse().getHeaders()).isEmpty(); } @Test public void responseHeadersCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)) - .sendingResponse(trace, createResponse(), null, null); - assertThat(trace.getResponse().getHeaders()) - .containsOnlyKeys(HttpHeaders.CONTENT_TYPE); + new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse(trace, createResponse(), null, + null); + assertThat(trace.getResponse().getHeaders()).containsOnlyKeys(HttpHeaders.CONTENT_TYPE); } @Test public void setCookieHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse( - trace, createResponse(Collections.singletonMap(HttpHeaders.SET_COOKIE, - Arrays.asList("test=test"))), - null, null); + new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse(trace, + createResponse(Collections.singletonMap(HttpHeaders.SET_COOKIE, Arrays.asList("test=test"))), null, + null); assertThat(trace.getResponse().getHeaders()).isEmpty(); } @Test public void mixedCaseSetCookieHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse( - trace, - createResponse(Collections.singletonMap(mixedCase(HttpHeaders.SET_COOKIE), - Arrays.asList("test=test"))), + new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse(trace, + createResponse(Collections.singletonMap(mixedCase(HttpHeaders.SET_COOKIE), Arrays.asList("test=test"))), null, null); assertThat(trace.getResponse().getHeaders()).isEmpty(); } @@ -231,44 +207,34 @@ public class HttpExchangeTracerTests { @Test public void setCookieHeaderCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer( - EnumSet.of(Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS)) - .sendingResponse(trace, - createResponse( - Collections.singletonMap(HttpHeaders.SET_COOKIE, - Arrays.asList("test=test"))), - null, null); - assertThat(trace.getResponse().getHeaders()) - .containsOnlyKeys(HttpHeaders.SET_COOKIE); + new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS)).sendingResponse(trace, + createResponse(Collections.singletonMap(HttpHeaders.SET_COOKIE, Arrays.asList("test=test"))), null, + null); + assertThat(trace.getResponse().getHeaders()).containsOnlyKeys(HttpHeaders.SET_COOKIE); } @Test public void mixedCaseSetCookieHeaderCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer( - EnumSet.of(Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS)) - .sendingResponse(trace, - createResponse(Collections.singletonMap( - mixedCase(HttpHeaders.SET_COOKIE), - Arrays.asList("test=test"))), - null, null); - assertThat(trace.getResponse().getHeaders()) - .containsOnlyKeys(mixedCase(HttpHeaders.SET_COOKIE)); + new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS)).sendingResponse(trace, + createResponse(Collections.singletonMap(mixedCase(HttpHeaders.SET_COOKIE), Arrays.asList("test=test"))), + null, null); + assertThat(trace.getResponse().getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.SET_COOKIE)); } @Test public void principalIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, - createResponse(), this::createPrincipal, null); + new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), + this::createPrincipal, null); assertThat(trace.getPrincipal()).isNull(); } @Test public void principalCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.PRINCIPAL)).sendingResponse(trace, - createResponse(), this::createPrincipal, null); + new HttpExchangeTracer(EnumSet.of(Include.PRINCIPAL)).sendingResponse(trace, createResponse(), + this::createPrincipal, null); assertThat(trace.getPrincipal()).isNotNull(); assertThat(trace.getPrincipal().getName()).isEqualTo("alice"); } @@ -276,16 +242,16 @@ public class HttpExchangeTracerTests { @Test public void sessionIdIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, - createResponse(), null, () -> "sessionId"); + new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, + () -> "sessionId"); assertThat(trace.getSession()).isNull(); } @Test public void sessionIdCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.SESSION_ID)).sendingResponse(trace, - createResponse(), null, () -> "sessionId"); + new HttpExchangeTracer(EnumSet.of(Include.SESSION_ID)).sendingResponse(trace, createResponse(), null, + () -> "sessionId"); assertThat(trace.getSession()).isNotNull(); assertThat(trace.getSession().getId()).isEqualTo("sessionId"); } @@ -293,22 +259,19 @@ public class HttpExchangeTracerTests { @Test public void timeTakenIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, - createResponse(), null, null); + new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getTimeTaken()).isNull(); } @Test public void timeTakenCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.TIME_TAKEN)).sendingResponse(trace, - createResponse(), null, null); + new HttpExchangeTracer(EnumSet.of(Include.TIME_TAKEN)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getTimeTaken()).isNotNull(); } private TraceableRequest createRequest() { - return createRequest(Collections.singletonMap(HttpHeaders.ACCEPT, - Arrays.asList("application/json"))); + return createRequest(Collections.singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); } private TraceableRequest createRequest(Map> headers) { @@ -321,8 +284,7 @@ public class HttpExchangeTracerTests { } private TraceableResponse createResponse() { - return createResponse(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, - Arrays.asList("application/json"))); + return createResponse(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); } private TraceableResponse createResponse(Map> headers) { @@ -341,14 +303,13 @@ public class HttpExchangeTracerTests { private String mixedCase(String input) { StringBuilder output = new StringBuilder(); for (int i = 0; i < input.length(); i++) { - output.append((i % 2 != 0) ? Character.toUpperCase(input.charAt(i)) - : Character.toLowerCase(input.charAt(i))); + output.append( + (i % 2 != 0) ? Character.toUpperCase(input.charAt(i)) : Character.toLowerCase(input.charAt(i))); } return output.toString(); } - private static class RequestHeadersFilterHttpExchangeTracer - extends HttpExchangeTracer { + private static class RequestHeadersFilterHttpExchangeTracer extends HttpExchangeTracer { RequestHeadersFilterHttpExchangeTracer() { super(EnumSet.of(Include.REQUEST_HEADERS)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java index f52b831854d..34372d67330 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java @@ -57,38 +57,33 @@ public class HttpTraceWebFilterIntegrationTests { @Test public void traceForNotFoundResponseHas404Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/") - .exchange().expectStatus().isNotFound(); + WebTestClient.bindToApplicationContext(context).build().get().uri("/").exchange().expectStatus() + .isNotFound(); HttpTraceRepository repository = context.getBean(HttpTraceRepository.class); assertThat(repository.findAll()).hasSize(1); - assertThat(repository.findAll().get(0).getResponse().getStatus()) - .isEqualTo(404); + assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(404); }); } @Test public void traceForMonoErrorWithRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get() - .uri("/mono-error").exchange().expectStatus() + WebTestClient.bindToApplicationContext(context).build().get().uri("/mono-error").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); HttpTraceRepository repository = context.getBean(HttpTraceRepository.class); assertThat(repository.findAll()).hasSize(1); - assertThat(repository.findAll().get(0).getResponse().getStatus()) - .isEqualTo(500); + assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); }); } @Test public void traceForThrownRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/thrown") - .exchange().expectStatus() + WebTestClient.bindToApplicationContext(context).build().get().uri("/thrown").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); HttpTraceRepository repository = context.getBean(HttpTraceRepository.class); assertThat(repository.findAll()).hasSize(1); - assertThat(repository.findAll().get(0).getResponse().getStatus()) - .isEqualTo(500); + assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); }); } @@ -99,8 +94,7 @@ public class HttpTraceWebFilterIntegrationTests { @Bean public HttpTraceWebFilter httpTraceWebFilter(HttpTraceRepository repository) { Set includes = EnumSet.allOf(Include.class); - return new HttpTraceWebFilter(repository, new HttpExchangeTracer(includes), - includes); + return new HttpTraceWebFilter(repository, new HttpExchangeTracer(includes), includes); } @Bean @@ -115,12 +109,10 @@ public class HttpTraceWebFilterIntegrationTests { @Bean public RouterFunction router() { - return route(GET("/mono-error"), - (request) -> Mono.error(new RuntimeException())).andRoute( - GET("/thrown"), - (HandlerFunction) (request) -> { - throw new RuntimeException(); - }); + return route(GET("/mono-error"), (request) -> Mono.error(new RuntimeException())).andRoute(GET("/thrown"), + (HandlerFunction) (request) -> { + throw new RuntimeException(); + }); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java index b082489f4ec..e9ac5628d91 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java @@ -47,31 +47,24 @@ public class HttpTraceWebFilterTests { private final InMemoryHttpTraceRepository repository = new InMemoryHttpTraceRepository(); - private final HttpExchangeTracer tracer = new HttpExchangeTracer( - EnumSet.allOf(Include.class)); + private final HttpExchangeTracer tracer = new HttpExchangeTracer(EnumSet.allOf(Include.class)); - private final HttpTraceWebFilter filter = new HttpTraceWebFilter(this.repository, - this.tracer, EnumSet.allOf(Include.class)); + private final HttpTraceWebFilter filter = new HttpTraceWebFilter(this.repository, this.tracer, + EnumSet.allOf(Include.class)); @Test public void filterTracesExchange() { - executeFilter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), + executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> Mono.empty()).block(Duration.ofSeconds(30)); assertThat(this.repository.findAll()).hasSize(1); } @Test public void filterCapturesSessionIdWhenSessionIsUsed() { - executeFilter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), - (exchange) -> { - exchange.getSession().block(Duration.ofSeconds(30)).getAttributes() - .put("a", "alpha"); - return Mono.empty(); - }).block(Duration.ofSeconds(30)); + executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> { + exchange.getSession().block(Duration.ofSeconds(30)).getAttributes().put("a", "alpha"); + return Mono.empty(); + }).block(Duration.ofSeconds(30)); assertThat(this.repository.findAll()).hasSize(1); Session session = this.repository.findAll().get(0).getSession(); assertThat(session).isNotNull(); @@ -80,13 +73,10 @@ public class HttpTraceWebFilterTests { @Test public void filterDoesNotCaptureIdOfUnusedSession() { - executeFilter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), - (exchange) -> { - exchange.getSession().block(Duration.ofSeconds(30)); - return Mono.empty(); - }).block(Duration.ofSeconds(30)); + executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> { + exchange.getSession().block(Duration.ofSeconds(30)); + return Mono.empty(); + }).block(Duration.ofSeconds(30)); assertThat(this.repository.findAll()).hasSize(1); Session session = this.repository.findAll().get(0).getSession(); assertThat(session).isNull(); @@ -96,8 +86,8 @@ public class HttpTraceWebFilterTests { public void filterCapturesPrincipal() { Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); - executeFilter(new ServerWebExchangeDecorator(MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com"))) { + executeFilter(new ServerWebExchangeDecorator( + MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com"))) { @Override public Mono getPrincipal() { @@ -105,20 +95,18 @@ public class HttpTraceWebFilterTests { } }, (exchange) -> { - exchange.getSession().block(Duration.ofSeconds(30)).getAttributes().put("a", - "alpha"); + exchange.getSession().block(Duration.ofSeconds(30)).getAttributes().put("a", "alpha"); return Mono.empty(); }).block(Duration.ofSeconds(30)); assertThat(this.repository.findAll()).hasSize(1); - org.springframework.boot.actuate.trace.http.HttpTrace.Principal tracedPrincipal = this.repository - .findAll().get(0).getPrincipal(); + org.springframework.boot.actuate.trace.http.HttpTrace.Principal tracedPrincipal = this.repository.findAll() + .get(0).getPrincipal(); assertThat(tracedPrincipal).isNotNull(); assertThat(tracedPrincipal.getName()).isEqualTo("alice"); } private Mono executeFilter(ServerWebExchange exchange, WebFilterChain chain) { - return this.filter.filter(exchange, chain) - .then(Mono.defer(() -> exchange.getResponse().setComplete())); + return this.filter.filter(exchange, chain).then(Mono.defer(() -> exchange.getResponse().setComplete())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java index 9bbd8a2bfe7..7cb35829195 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java @@ -56,16 +56,13 @@ public class HttpTraceFilterTests { private final InMemoryHttpTraceRepository repository = new InMemoryHttpTraceRepository(); - private final HttpExchangeTracer tracer = new HttpExchangeTracer( - EnumSet.allOf(Include.class)); + private final HttpExchangeTracer tracer = new HttpExchangeTracer(EnumSet.allOf(Include.class)); - private final HttpTraceFilter filter = new HttpTraceFilter(this.repository, - this.tracer); + private final HttpTraceFilter filter = new HttpTraceFilter(this.repository, this.tracer); @Test public void filterTracesExchange() throws ServletException, IOException { - this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), - new MockFilterChain()); + this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); assertThat(this.repository.findAll()).hasSize(1); } @@ -75,8 +72,7 @@ public class HttpTraceFilterTests { new MockFilterChain(new HttpServlet() { @Override - protected void service(HttpServletRequest req, - HttpServletResponse resp) + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession(true); } @@ -94,35 +90,28 @@ public class HttpTraceFilterTests { Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); request.setUserPrincipal(principal); - this.filter.doFilter(request, new MockHttpServletResponse(), - new MockFilterChain()); + this.filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertThat(this.repository.findAll()).hasSize(1); - org.springframework.boot.actuate.trace.http.HttpTrace.Principal tracedPrincipal = this.repository - .findAll().get(0).getPrincipal(); + org.springframework.boot.actuate.trace.http.HttpTrace.Principal tracedPrincipal = this.repository.findAll() + .get(0).getPrincipal(); assertThat(tracedPrincipal).isNotNull(); assertThat(tracedPrincipal.getName()).isEqualTo("alice"); } @Test - public void statusIsAssumedToBe500WhenChainFails() - throws ServletException, IOException { - assertThatIOException() - .isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(), - new MockHttpServletResponse(), - new MockFilterChain(new HttpServlet() { + public void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { + assertThatIOException().isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(), + new MockHttpServletResponse(), new MockFilterChain(new HttpServlet() { - @Override - protected void service(HttpServletRequest req, - HttpServletResponse resp) - throws ServletException, IOException { - throw new IOException(); - } + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + throw new IOException(); + } - }))) - .satisfies((ex) -> { + }))).satisfies((ex) -> { assertThat(this.repository.findAll()).hasSize(1); - assertThat(this.repository.findAll().get(0).getResponse().getStatus()) - .isEqualTo(500); + assertThat(this.repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); }); } @@ -130,8 +119,7 @@ public class HttpTraceFilterTests { public void filterRejectsInvalidRequests() throws ServletException, IOException { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName(""); - this.filter.doFilter(request, new MockHttpServletResponse(), - new MockFilterChain()); + this.filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertThat(this.repository.findAll()).hasSize(0); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java index 9a3dfe08387..0012247499c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java @@ -76,24 +76,20 @@ public class MappingsEndpointTests { public void servletWebMappings() { Supplier contextSupplier = prepareContextSupplier(); new WebApplicationContextRunner(contextSupplier) - .withUserConfiguration(EndpointConfiguration.class, - ServletWebConfiguration.class) - .run((context) -> { + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class).run((context) -> { ContextMappings contextMappings = contextMappings(context); assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys( - "dispatcherServlets", "servletFilters", "servlets"); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", + "servlets"); Map> dispatcherServlets = mappings( contextMappings, "dispatcherServlets"); assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); List handlerMappings = dispatcherServlets .get("dispatcherServlet"); assertThat(handlerMappings).hasSize(1); - List servlets = mappings( - contextMappings, "servlets"); + List servlets = mappings(contextMappings, "servlets"); assertThat(servlets).hasSize(1); - List filters = mappings( - contextMappings, "servletFilters"); + List filters = mappings(contextMappings, "servletFilters"); assertThat(filters).hasSize(1); }); } @@ -101,31 +97,24 @@ public class MappingsEndpointTests { @Test public void servletWebMappingsWithAdditionalDispatcherServlets() { Supplier contextSupplier = prepareContextSupplier(); - new WebApplicationContextRunner(contextSupplier).withUserConfiguration( - EndpointConfiguration.class, ServletWebConfiguration.class, - CustomDispatcherServletConfiguration.class).run((context) -> { + new WebApplicationContextRunner(contextSupplier).withUserConfiguration(EndpointConfiguration.class, + ServletWebConfiguration.class, CustomDispatcherServletConfiguration.class).run((context) -> { ContextMappings contextMappings = contextMappings(context); Map> dispatcherServlets = mappings( contextMappings, "dispatcherServlets"); assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet", - "customDispatcherServletRegistration", - "anotherDispatcherServletRegistration"); + "customDispatcherServletRegistration", "anotherDispatcherServletRegistration"); assertThat(dispatcherServlets.get("dispatcherServlet")).hasSize(1); - assertThat( - dispatcherServlets.get("customDispatcherServletRegistration")) - .hasSize(1); - assertThat(dispatcherServlets - .get("anotherDispatcherServletRegistration")).hasSize(1); + assertThat(dispatcherServlets.get("customDispatcherServletRegistration")).hasSize(1); + assertThat(dispatcherServlets.get("anotherDispatcherServletRegistration")).hasSize(1); }); } @SuppressWarnings("unchecked") private Supplier prepareContextSupplier() { ServletContext servletContext = mock(ServletContext.class); - given(servletContext.getInitParameterNames()) - .willReturn(Collections.emptyEnumeration()); - given(servletContext.getAttributeNames()) - .willReturn(Collections.emptyEnumeration()); + given(servletContext.getInitParameterNames()).willReturn(Collections.emptyEnumeration()); + given(servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); FilterRegistration filterRegistration = mock(FilterRegistration.class); given((Map) servletContext.getFilterRegistrations()) .willReturn(Collections.singletonMap("testFilter", filterRegistration)); @@ -142,25 +131,20 @@ public class MappingsEndpointTests { @Test public void reactiveWebMappings() { new ReactiveWebApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class, - ReactiveWebConfiguration.class) - .run((context) -> { + .withUserConfiguration(EndpointConfiguration.class, ReactiveWebConfiguration.class).run((context) -> { ContextMappings contextMappings = contextMappings(context); assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()) - .containsOnlyKeys("dispatcherHandlers"); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherHandlers"); Map> dispatcherHandlers = mappings( contextMappings, "dispatcherHandlers"); assertThat(dispatcherHandlers).containsOnlyKeys("webHandler"); - List handlerMappings = dispatcherHandlers - .get("webHandler"); + List handlerMappings = dispatcherHandlers.get("webHandler"); assertThat(handlerMappings).hasSize(3); }); } private ContextMappings contextMappings(ApplicationContext context) { - ApplicationMappings applicationMappings = context.getBean(MappingsEndpoint.class) - .mappings(); + ApplicationMappings applicationMappings = context.getBean(MappingsEndpoint.class).mappings(); assertThat(applicationMappings.getContexts()).containsOnlyKeys(context.getId()); return applicationMappings.getContexts().get(context.getId()); } @@ -174,8 +158,7 @@ public class MappingsEndpointTests { static class EndpointConfiguration { @Bean - public MappingsEndpoint mappingsEndpoint( - Collection descriptionProviders, + public MappingsEndpoint mappingsEndpoint(Collection descriptionProviders, ApplicationContext context) { return new MappingsEndpoint(descriptionProviders, context); } @@ -194,8 +177,8 @@ public class MappingsEndpointTests { @Bean public RouterFunction routerFunction() { - return route(GET("/one"), (request) -> ServerResponse.ok().build()) - .andRoute(POST("/two"), (request) -> ServerResponse.ok().build()); + return route(GET("/one"), (request) -> ServerResponse.ok().build()).andRoute(POST("/two"), + (request) -> ServerResponse.ok().build()); } @RequestMapping("/three") @@ -226,8 +209,7 @@ public class MappingsEndpointTests { } @Bean - public DispatcherServlet dispatcherServlet(WebApplicationContext context) - throws ServletException { + public DispatcherServlet dispatcherServlet(WebApplicationContext context) throws ServletException { DispatcherServlet dispatcherServlet = new DispatcherServlet(context); dispatcherServlet.init(new MockServletConfig()); return dispatcherServlet; @@ -266,8 +248,7 @@ public class MappingsEndpointTests { return registrationBean; } - private DispatcherServlet createTestDispatcherServlet( - WebApplicationContext context) { + private DispatcherServlet createTestDispatcherServlet(WebApplicationContext context) { try { DispatcherServlet dispatcherServlet = new DispatcherServlet(context); dispatcherServlet.init(new MockServletConfig()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java index c63caa67564..d38841cd9e1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java @@ -53,8 +53,7 @@ public class ServerWebExchangeTraceableRequestTests { public void getMethod() { String method = "POST"; given(this.request.getMethodValue()).willReturn(method); - ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest( - this.exchange); + ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); assertThat(traceableRequest.getMethod()).isSameAs(method); } @@ -62,8 +61,7 @@ public class ServerWebExchangeTraceableRequestTests { public void getUri() { URI uri = URI.create("http://localhost:8080/"); given(this.request.getURI()).willReturn(uri); - ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest( - this.exchange); + ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); assertThat(traceableRequest.getUri()).isSameAs(uri); } @@ -72,19 +70,15 @@ public class ServerWebExchangeTraceableRequestTests { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("name", "value"); given(this.request.getHeaders()).willReturn(httpHeaders); - ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest( - this.exchange); - assertThat(traceableRequest.getHeaders()) - .containsOnly(entry("name", Collections.singletonList("value"))); + ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); + assertThat(traceableRequest.getHeaders()).containsOnly(entry("name", Collections.singletonList("value"))); } @Test public void getUnresolvedRemoteAddress() { - InetSocketAddress socketAddress = InetSocketAddress - .createUnresolved("unresolved.example.com", 8080); + InetSocketAddress socketAddress = InetSocketAddress.createUnresolved("unresolved.example.com", 8080); given(this.request.getRemoteAddress()).willReturn(socketAddress); - ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest( - this.exchange); + ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); assertThat(traceableRequest.getRemoteAddress()).isNull(); } @@ -92,10 +86,8 @@ public class ServerWebExchangeTraceableRequestTests { public void getRemoteAddress() { InetSocketAddress socketAddress = new InetSocketAddress(0); given(this.request.getRemoteAddress()).willReturn(socketAddress); - ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest( - this.exchange); - assertThat(traceableRequest.getRemoteAddress()) - .isEqualTo(socketAddress.getAddress().toString()); + ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); + assertThat(traceableRequest.getRemoteAddress()).isEqualTo(socketAddress.getAddress().toString()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java index 0411b3a1891..60a77897012 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ import org.springframework.util.StringUtils; * @since 1.3.0 * @see BeanDefinition#setDependsOn(String[]) */ -public abstract class AbstractDependsOnBeanFactoryPostProcessor - implements BeanFactoryPostProcessor { +public abstract class AbstractDependsOnBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private final Class beanClass; @@ -64,8 +63,7 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor * @param dependsOn dependencies * @since 2.0.4 */ - protected AbstractDependsOnBeanFactoryPostProcessor(Class beanClass, - String... dependsOn) { + protected AbstractDependsOnBeanFactoryPostProcessor(Class beanClass, String... dependsOn) { this(beanClass, null, dependsOn); } @@ -83,28 +81,25 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor private Iterable getBeanNames(ListableBeanFactory beanFactory) { Set names = new HashSet<>(); - names.addAll(Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - beanFactory, this.beanClass, true, false))); + names.addAll(Arrays + .asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, this.beanClass, true, false))); if (this.factoryBeanClass != null) { - for (String factoryBeanName : BeanFactoryUtils - .beanNamesForTypeIncludingAncestors(beanFactory, - this.factoryBeanClass, true, false)) { + for (String factoryBeanName : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, + this.factoryBeanClass, true, false)) { names.add(BeanFactoryUtils.transformedBeanName(factoryBeanName)); } } return names; } - private static BeanDefinition getBeanDefinition(String beanName, - ConfigurableListableBeanFactory beanFactory) { + private static BeanDefinition getBeanDefinition(String beanName, ConfigurableListableBeanFactory beanFactory) { try { return beanFactory.getBeanDefinition(beanName); } catch (NoSuchBeanDefinitionException ex) { BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory(); if (parentBeanFactory instanceof ConfigurableListableBeanFactory) { - return getBeanDefinition(beanName, - (ConfigurableListableBeanFactory) parentBeanFactory); + return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory); } throw ex; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java index 1a9d702e683..dc83e8b28e4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,25 +44,23 @@ public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoad } @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader); } private boolean isConfiguration(MetadataReader metadataReader) { - return metadataReader.getAnnotationMetadata() - .isAnnotated(Configuration.class.getName()); + return metadataReader.getAnnotationMetadata().isAnnotated(Configuration.class.getName()); } private boolean isAutoConfiguration(MetadataReader metadataReader) { - return getAutoConfigurations() - .contains(metadataReader.getClassMetadata().getClassName()); + return getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName()); } protected List getAutoConfigurations() { if (this.autoConfigurations == null) { - this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames( - EnableAutoConfiguration.class, this.beanClassLoader); + this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, + this.beanClassLoader); } return this.autoConfigurations; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java index b361412498d..fbab1c9c642 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,11 +33,9 @@ public class AutoConfigurationImportEvent extends EventObject { private final Set exclusions; - public AutoConfigurationImportEvent(Object source, - List candidateConfigurations, Set exclusions) { + public AutoConfigurationImportEvent(Object source, List candidateConfigurations, Set exclusions) { super(source); - this.candidateConfigurations = Collections - .unmodifiableList(candidateConfigurations); + this.candidateConfigurations = Collections.unmodifiableList(candidateConfigurations); this.exclusions = Collections.unmodifiableSet(exclusions); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java index 84db3a8c987..526d5e50963 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,6 @@ public interface AutoConfigurationImportFilter { * {@code autoConfigurationClasses} parameter. Entries containing {@code false} will * not be imported. */ - boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata); + boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java index ce0735cd95c..725124f42a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,16 +69,14 @@ import org.springframework.util.StringUtils; * @since 1.3.0 * @see EnableAutoConfiguration */ -public class AutoConfigurationImportSelector - implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, - BeanFactoryAware, EnvironmentAware, Ordered { +public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, + ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered { private static final AutoConfigurationEntry EMPTY_ENTRY = new AutoConfigurationEntry(); private static final String[] NO_IMPORTS = {}; - private static final Log logger = LogFactory - .getLog(AutoConfigurationImportSelector.class); + private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.class); private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude"; @@ -97,8 +95,8 @@ public class AutoConfigurationImportSelector } AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); - AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry( - autoConfigurationMetadata, annotationMetadata); + AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata, + annotationMetadata); return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations()); } @@ -109,15 +107,13 @@ public class AutoConfigurationImportSelector * @param annotationMetadata the annotation metadata of the configuration class * @return the auto-configurations that should be imported */ - protected AutoConfigurationEntry getAutoConfigurationEntry( - AutoConfigurationMetadata autoConfigurationMetadata, + protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } AnnotationAttributes attributes = getAttributes(annotationMetadata); - List configurations = getCandidateConfigurations(annotationMetadata, - attributes); + List configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); Set exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); @@ -134,9 +130,7 @@ public class AutoConfigurationImportSelector protected boolean isEnabled(AnnotationMetadata metadata) { if (getClass() == AutoConfigurationImportSelector.class) { - return getEnvironment().getProperty( - EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, - true); + return getEnvironment().getProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, true); } return true; } @@ -150,12 +144,9 @@ public class AutoConfigurationImportSelector */ protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) { String name = getAnnotationClass().getName(); - AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(name, true)); - Assert.notNull(attributes, - () -> "No auto-configuration attributes found. Is " - + metadata.getClassName() + " annotated with " - + ClassUtils.getShortName(name) + "?"); + AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true)); + Assert.notNull(attributes, () -> "No auto-configuration attributes found. Is " + metadata.getClassName() + + " annotated with " + ClassUtils.getShortName(name) + "?"); return attributes; } @@ -176,13 +167,11 @@ public class AutoConfigurationImportSelector * attributes} * @return a list of candidate configurations */ - protected List getCandidateConfigurations(AnnotationMetadata metadata, - AnnotationAttributes attributes) { - List configurations = SpringFactoriesLoader.loadFactoryNames( - getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); - Assert.notEmpty(configurations, - "No auto configuration classes found in META-INF/spring.factories. If you " - + "are using a custom packaging, make sure that file is correct."); + protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { + List configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), + getBeanClassLoader()); + Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + + "are using a custom packaging, make sure that file is correct."); return configurations; } @@ -195,12 +184,10 @@ public class AutoConfigurationImportSelector return EnableAutoConfiguration.class; } - private void checkExcludedClasses(List configurations, - Set exclusions) { + private void checkExcludedClasses(List configurations, Set exclusions) { List invalidExcludes = new ArrayList<>(exclusions.size()); for (String exclusion : exclusions) { - if (ClassUtils.isPresent(exclusion, getClass().getClassLoader()) - && !configurations.contains(exclusion)) { + if (ClassUtils.isPresent(exclusion, getClass().getClassLoader()) && !configurations.contains(exclusion)) { invalidExcludes.add(exclusion); } } @@ -219,9 +206,9 @@ public class AutoConfigurationImportSelector for (String exclude : invalidExcludes) { message.append("\t- ").append(exclude).append(String.format("%n")); } - throw new IllegalStateException(String - .format("The following classes could not be excluded because they are" - + " not auto-configuration classes:%n%s", message)); + throw new IllegalStateException(String.format( + "The following classes could not be excluded because they are" + " not auto-configuration classes:%n%s", + message)); } /** @@ -231,8 +218,7 @@ public class AutoConfigurationImportSelector * attributes} * @return exclusions or an empty set */ - protected Set getExclusions(AnnotationMetadata metadata, - AnnotationAttributes attributes) { + protected Set getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) { Set excluded = new LinkedHashSet<>(); excluded.addAll(asList(attributes, "exclude")); excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName"))); @@ -243,16 +229,14 @@ public class AutoConfigurationImportSelector private List getExcludeAutoConfigurationsProperty() { if (getEnvironment() instanceof ConfigurableEnvironment) { Binder binder = Binder.get(getEnvironment()); - return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class) - .map(Arrays::asList).orElse(Collections.emptyList()); + return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(Arrays::asList) + .orElse(Collections.emptyList()); } - String[] excludes = getEnvironment() - .getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class); + String[] excludes = getEnvironment().getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class); return (excludes != null) ? Arrays.asList(excludes) : Collections.emptyList(); } - private List filter(List configurations, - AutoConfigurationMetadata autoConfigurationMetadata) { + private List filter(List configurations, AutoConfigurationMetadata autoConfigurationMetadata) { long startTime = System.nanoTime(); String[] candidates = StringUtils.toStringArray(configurations); boolean[] skip = new boolean[candidates.length]; @@ -280,15 +264,13 @@ public class AutoConfigurationImportSelector if (logger.isTraceEnabled()) { int numberFiltered = configurations.size() - result.size(); logger.trace("Filtered " + numberFiltered + " auto configuration class in " - + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) - + " ms"); + + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + " ms"); } return new ArrayList<>(result); } protected List getAutoConfigurationImportFilters() { - return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, - this.beanClassLoader); + return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader); } protected final List removeDuplicates(List list) { @@ -300,12 +282,10 @@ public class AutoConfigurationImportSelector return Arrays.asList((value != null) ? value : new String[0]); } - private void fireAutoConfigurationImportEvents(List configurations, - Set exclusions) { + private void fireAutoConfigurationImportEvents(List configurations, Set exclusions) { List listeners = getAutoConfigurationImportListeners(); if (!listeners.isEmpty()) { - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - configurations, exclusions); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions); for (AutoConfigurationImportListener listener : listeners) { invokeAwareMethods(listener); listener.onAutoConfigurationImportEvent(event); @@ -314,15 +294,13 @@ public class AutoConfigurationImportSelector } protected List getAutoConfigurationImportListeners() { - return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, - this.beanClassLoader); + return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, this.beanClassLoader); } private void invokeAwareMethods(Object instance) { if (instance instanceof Aware) { if (instance instanceof BeanClassLoaderAware) { - ((BeanClassLoaderAware) instance) - .setBeanClassLoader(this.beanClassLoader); + ((BeanClassLoaderAware) instance).setBeanClassLoader(this.beanClassLoader); } if (instance instanceof BeanFactoryAware) { ((BeanFactoryAware) instance).setBeanFactory(this.beanFactory); @@ -378,8 +356,8 @@ public class AutoConfigurationImportSelector return Ordered.LOWEST_PRECEDENCE - 1; } - private static class AutoConfigurationGroup implements DeferredImportSelector.Group, - BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware { + private static class AutoConfigurationGroup + implements DeferredImportSelector.Group, BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware { private final Map entries = new LinkedHashMap<>(); @@ -409,16 +387,13 @@ public class AutoConfigurationImportSelector } @Override - public void process(AnnotationMetadata annotationMetadata, - DeferredImportSelector deferredImportSelector) { - Assert.state( - deferredImportSelector instanceof AutoConfigurationImportSelector, + public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) { + Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) - .getAutoConfigurationEntry(getAutoConfigurationMetadata(), - annotationMetadata); + .getAutoConfigurationEntry(getAutoConfigurationMetadata(), annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); for (String importClassName : autoConfigurationEntry.getConfigurations()) { this.entries.putIfAbsent(importClassName, annotationMetadata); @@ -431,40 +406,33 @@ public class AutoConfigurationImportSelector return Collections.emptyList(); } Set allExclusions = this.autoConfigurationEntries.stream() - .map(AutoConfigurationEntry::getExclusions) - .flatMap(Collection::stream).collect(Collectors.toSet()); + .map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet()); Set processedConfigurations = this.autoConfigurationEntries.stream() - .map(AutoConfigurationEntry::getConfigurations) - .flatMap(Collection::stream) + .map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream) .collect(Collectors.toCollection(LinkedHashSet::new)); processedConfigurations.removeAll(allExclusions); - return sortAutoConfigurations(processedConfigurations, - getAutoConfigurationMetadata()) - .stream() - .map((importClassName) -> new Entry( - this.entries.get(importClassName), importClassName)) - .collect(Collectors.toList()); + return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream() + .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)) + .collect(Collectors.toList()); } private AutoConfigurationMetadata getAutoConfigurationMetadata() { if (this.autoConfigurationMetadata == null) { - this.autoConfigurationMetadata = AutoConfigurationMetadataLoader - .loadMetadata(this.beanClassLoader); + this.autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader); } return this.autoConfigurationMetadata; } private List sortAutoConfigurations(Set configurations, AutoConfigurationMetadata autoConfigurationMetadata) { - return new AutoConfigurationSorter(getMetadataReaderFactory(), - autoConfigurationMetadata).getInPriorityOrder(configurations); + return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata) + .getInPriorityOrder(configurations); } private MetadataReaderFactory getMetadataReaderFactory() { try { - return this.beanFactory.getBean( - SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, + return this.beanFactory.getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, MetadataReaderFactory.class); } catch (NoSuchBeanDefinitionException ex) { @@ -491,8 +459,7 @@ public class AutoConfigurationImportSelector * @param configurations the configurations that should be imported * @param exclusions the exclusions that were applied to the original list */ - AutoConfigurationEntry(Collection configurations, - Collection exclusions) { + AutoConfigurationEntry(Collection configurations, Collection exclusions) { this.configurations = new ArrayList<>(configurations); this.exclusions = new HashSet<>(exclusions); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java index cc7b23196f3..6a17c83662a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.util.StringUtils; */ final class AutoConfigurationMetadataLoader { - protected static final String PATH = "META-INF/" - + "spring-autoconfigure-metadata.properties"; + protected static final String PATH = "META-INF/" + "spring-autoconfigure-metadata.properties"; private AutoConfigurationMetadataLoader() { } @@ -49,14 +48,12 @@ final class AutoConfigurationMetadataLoader { : ClassLoader.getSystemResources(path); Properties properties = new Properties(); while (urls.hasMoreElements()) { - properties.putAll(PropertiesLoaderUtils - .loadProperties(new UrlResource(urls.nextElement()))); + properties.putAll(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } return loadMetadata(properties); } catch (IOException ex) { - throw new IllegalArgumentException( - "Unable to load @ConditionalOnClass location [" + path + "]", ex); + throw new IllegalArgumentException("Unable to load @ConditionalOnClass location [" + path + "]", ex); } } @@ -67,8 +64,7 @@ final class AutoConfigurationMetadataLoader { /** * {@link AutoConfigurationMetadata} implementation backed by a properties file. */ - private static class PropertiesAutoConfigurationMetadata - implements AutoConfigurationMetadata { + private static class PropertiesAutoConfigurationMetadata implements AutoConfigurationMetadata { private final Properties properties; @@ -98,11 +94,9 @@ final class AutoConfigurationMetadataLoader { } @Override - public Set getSet(String className, String key, - Set defaultValue) { + public Set getSet(String className, String key, Set defaultValue) { String value = get(className, key); - return (value != null) ? StringUtils.commaDelimitedListToSet(value) - : defaultValue; + return (value != null) ? StringUtils.commaDelimitedListToSet(value) : defaultValue; } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java index eac6047d12a..38fa20dc19e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,7 @@ public abstract class AutoConfigurationPackages { return beanFactory.getBean(BEAN, BasePackages.class).get(); } catch (NoSuchBeanDefinitionException ex) { - throw new IllegalStateException( - "Unable to retrieve @EnableAutoConfiguration base packages"); + throw new IllegalStateException("Unable to retrieve @EnableAutoConfiguration base packages"); } } @@ -92,25 +91,20 @@ public abstract class AutoConfigurationPackages { public static void register(BeanDefinitionRegistry registry, String... packageNames) { if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); - ConstructorArgumentValues constructorArguments = beanDefinition - .getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - addBasePackages(constructorArguments, packageNames)); + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(BasePackages.class); - beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, - packageNames); + beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN, beanDefinition); } } - private static String[] addBasePackages( - ConstructorArgumentValues constructorArguments, String[] packageNames) { - String[] existing = (String[]) constructorArguments - .getIndexedArgumentValue(0, String[].class).getValue(); + private static String[] addBasePackages(ConstructorArgumentValues constructorArguments, String[] packageNames) { + String[] existing = (String[]) constructorArguments.getIndexedArgumentValue(0, String[].class).getValue(); Set merged = new LinkedHashSet<>(); merged.addAll(Arrays.asList(existing)); merged.addAll(Arrays.asList(packageNames)); @@ -124,8 +118,7 @@ public abstract class AutoConfigurationPackages { static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, new PackageImport(metadata).getPackageName()); } @@ -201,12 +194,9 @@ public abstract class AutoConfigurationPackages { } else { if (logger.isDebugEnabled()) { - String packageNames = StringUtils - .collectionToCommaDelimitedString(this.packages); - logger.debug("@EnableAutoConfiguration was declared on a class " - + "in the package '" + packageNames - + "'. Automatic @Repository and @Entity scanning is " - + "enabled."); + String packageNames = StringUtils.collectionToCommaDelimitedString(this.packages); + logger.debug("@EnableAutoConfiguration was declared on a class " + "in the package '" + + packageNames + "'. Automatic @Repository and @Entity scanning is " + "enabled."); } } this.loggedBasePackageInfo = true; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java index 2c716e09984..0605b7acf6b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java @@ -53,8 +53,8 @@ class AutoConfigurationSorter { } public List getInPriorityOrder(Collection classNames) { - AutoConfigurationClasses classes = new AutoConfigurationClasses( - this.metadataReaderFactory, this.autoConfigurationMetadata, classNames); + AutoConfigurationClasses classes = new AutoConfigurationClasses(this.metadataReaderFactory, + this.autoConfigurationMetadata, classNames); List orderedClassNames = new ArrayList<>(classNames); // Initially sort alphabetically Collections.sort(orderedClassNames); @@ -69,8 +69,7 @@ class AutoConfigurationSorter { return orderedClassNames; } - private List sortByAnnotation(AutoConfigurationClasses classes, - List classNames) { + private List sortByAnnotation(AutoConfigurationClasses classes, List classNames) { List toSort = new ArrayList<>(classNames); toSort.addAll(classes.getAllNames()); Set sorted = new LinkedHashSet<>(); @@ -82,9 +81,8 @@ class AutoConfigurationSorter { return new ArrayList<>(sorted); } - private void doSortByAfterAnnotation(AutoConfigurationClasses classes, - List toSort, Set sorted, Set processing, - String current) { + private void doSortByAfterAnnotation(AutoConfigurationClasses classes, List toSort, Set sorted, + Set processing, String current) { if (current == null) { current = toSort.remove(0); } @@ -105,10 +103,8 @@ class AutoConfigurationSorter { private final Map classes = new HashMap<>(); AutoConfigurationClasses(MetadataReaderFactory metadataReaderFactory, - AutoConfigurationMetadata autoConfigurationMetadata, - Collection classNames) { - addToClasses(metadataReaderFactory, autoConfigurationMetadata, classNames, - true); + AutoConfigurationMetadata autoConfigurationMetadata, Collection classNames) { + addToClasses(metadataReaderFactory, autoConfigurationMetadata, classNames, true); } public Set getAllNames() { @@ -116,12 +112,11 @@ class AutoConfigurationSorter { } private void addToClasses(MetadataReaderFactory metadataReaderFactory, - AutoConfigurationMetadata autoConfigurationMetadata, - Collection classNames, boolean required) { + AutoConfigurationMetadata autoConfigurationMetadata, Collection classNames, boolean required) { for (String className : classNames) { if (!this.classes.containsKey(className)) { - AutoConfigurationClass autoConfigurationClass = new AutoConfigurationClass( - className, metadataReaderFactory, autoConfigurationMetadata); + AutoConfigurationClass autoConfigurationClass = new AutoConfigurationClass(className, + metadataReaderFactory, autoConfigurationMetadata); boolean available = autoConfigurationClass.isAvailable(); if (required || available) { this.classes.put(className, autoConfigurationClass); @@ -167,8 +162,7 @@ class AutoConfigurationSorter { private volatile Set after; - AutoConfigurationClass(String className, - MetadataReaderFactory metadataReaderFactory, + AutoConfigurationClass(String className, MetadataReaderFactory metadataReaderFactory, AutoConfigurationMetadata autoConfigurationMetadata) { this.className = className; this.metadataReaderFactory = metadataReaderFactory; @@ -189,33 +183,28 @@ class AutoConfigurationSorter { public Set getBefore() { if (this.before == null) { - this.before = (wasProcessed() - ? this.autoConfigurationMetadata.getSet(this.className, - "AutoConfigureBefore", Collections.emptySet()) - : getAnnotationValue(AutoConfigureBefore.class)); + this.before = (wasProcessed() ? this.autoConfigurationMetadata.getSet(this.className, + "AutoConfigureBefore", Collections.emptySet()) : getAnnotationValue(AutoConfigureBefore.class)); } return this.before; } public Set getAfter() { if (this.after == null) { - this.after = (wasProcessed() - ? this.autoConfigurationMetadata.getSet(this.className, - "AutoConfigureAfter", Collections.emptySet()) - : getAnnotationValue(AutoConfigureAfter.class)); + this.after = (wasProcessed() ? this.autoConfigurationMetadata.getSet(this.className, + "AutoConfigureAfter", Collections.emptySet()) : getAnnotationValue(AutoConfigureAfter.class)); } return this.after; } private int getOrder() { if (wasProcessed()) { - return this.autoConfigurationMetadata.getInteger(this.className, - "AutoConfigureOrder", AutoConfigureOrder.DEFAULT_ORDER); + return this.autoConfigurationMetadata.getInteger(this.className, "AutoConfigureOrder", + AutoConfigureOrder.DEFAULT_ORDER); } Map attributes = getAnnotationMetadata() .getAnnotationAttributes(AutoConfigureOrder.class.getName()); - return (attributes != null) ? (Integer) attributes.get("value") - : AutoConfigureOrder.DEFAULT_ORDER; + return (attributes != null) ? (Integer) attributes.get("value") : AutoConfigureOrder.DEFAULT_ORDER; } private boolean wasProcessed() { @@ -224,8 +213,8 @@ class AutoConfigurationSorter { } private Set getAnnotationValue(Class annotation) { - Map attributes = getAnnotationMetadata() - .getAnnotationAttributes(annotation.getName(), true); + Map attributes = getAnnotationMetadata().getAnnotationAttributes(annotation.getName(), + true); if (attributes == null) { return Collections.emptySet(); } @@ -238,13 +227,11 @@ class AutoConfigurationSorter { private AnnotationMetadata getAnnotationMetadata() { if (this.annotationMetadata == null) { try { - MetadataReader metadataReader = this.metadataReaderFactory - .getMetadataReader(this.className); + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(this.className); this.annotationMetadata = metadataReader.getAnnotationMetadata(); } catch (IOException ex) { - throw new IllegalStateException( - "Unable to read meta-data for class " + this.className, ex); + throw new IllegalStateException("Unable to read meta-data for class " + this.className, ex); } } return this.annotationMetadata; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java index 8a1d37e7874..904d1eb1ee9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ import org.springframework.util.ClassUtils; */ public class AutoConfigurations extends Configurations implements Ordered { - private static final AutoConfigurationSorter SORTER = new AutoConfigurationSorter( - new SimpleMetadataReaderFactory(), null); + private static final AutoConfigurationSorter SORTER = new AutoConfigurationSorter(new SimpleMetadataReaderFactory(), + null); private static final Ordered ORDER = new AutoConfigurationImportSelector(); @@ -47,11 +47,9 @@ public class AutoConfigurations extends Configurations implements Ordered { @Override protected Collection> sort(Collection> classes) { - List names = classes.stream().map(Class::getName) - .collect(Collectors.toList()); + List names = classes.stream().map(Class::getName).collect(Collectors.toList()); List sorted = SORTER.getInPriorityOrder(names); - return sorted.stream() - .map((className) -> ClassUtils.resolveClassName(className, null)) + return sorted.stream().map((className) -> ClassUtils.resolveClassName(className, null)) .collect(Collectors.toCollection(ArrayList::new)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java index 715d2a778d7..b224582db42 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java @@ -48,8 +48,7 @@ import org.springframework.http.converter.support.AllEncompassingFormHttpMessage * @since 1.3.0 */ @Order(LoggingApplicationListener.DEFAULT_ORDER + 1) -public class BackgroundPreinitializer - implements ApplicationListener { +public class BackgroundPreinitializer implements ApplicationListener { /** * System property that instructs Spring Boot how to run pre initialization. When the @@ -60,8 +59,7 @@ public class BackgroundPreinitializer */ public static final String IGNORE_BACKGROUNDPREINITIALIZER_PROPERTY_NAME = "spring.backgroundpreinitializer.ignore"; - private static final AtomicBoolean preinitializationStarted = new AtomicBoolean( - false); + private static final AtomicBoolean preinitializationStarted = new AtomicBoolean(false); private static final CountDownLatch preinitializationComplete = new CountDownLatch(1); @@ -72,8 +70,7 @@ public class BackgroundPreinitializer && preinitializationStarted.compareAndSet(false, true)) { performPreinitialization(); } - if ((event instanceof ApplicationReadyEvent - || event instanceof ApplicationFailedEvent) + if ((event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent) && preinitializationStarted.get()) { try { preinitializationComplete.await(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java index 984d92658ea..6b5f546d93c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java @@ -45,8 +45,7 @@ import org.springframework.util.ObjectUtils; * @author Phillip Webb * @author Andy Wilkinson */ -class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelector - implements DeterminableImports { +class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelector implements DeterminableImports { private static final Set ANNOTATION_NAMES; @@ -71,26 +70,23 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec } @Override - protected List getCandidateConfigurations(AnnotationMetadata metadata, - AnnotationAttributes attributes) { + protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List candidates = new ArrayList<>(); Map, List> annotations = getAnnotations(metadata); - annotations.forEach((source, sourceAnnotations) -> collectCandidateConfigurations( - source, sourceAnnotations, candidates)); + annotations.forEach( + (source, sourceAnnotations) -> collectCandidateConfigurations(source, sourceAnnotations, candidates)); return candidates; } - private void collectCandidateConfigurations(Class source, - List annotations, List candidates) { + private void collectCandidateConfigurations(Class source, List annotations, + List candidates) { for (Annotation annotation : annotations) { candidates.addAll(getConfigurationsForAnnotation(source, annotation)); } } - private Collection getConfigurationsForAnnotation(Class source, - Annotation annotation) { - String[] classes = (String[]) AnnotationUtils - .getAnnotationAttributes(annotation, true).get("classes"); + private Collection getConfigurationsForAnnotation(Class source, Annotation annotation) { + String[] classes = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("classes"); if (classes.length > 0) { return Arrays.asList(classes); } @@ -98,20 +94,16 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec } protected Collection loadFactoryNames(Class source) { - return SpringFactoriesLoader.loadFactoryNames(source, - getClass().getClassLoader()); + return SpringFactoriesLoader.loadFactoryNames(source, getClass().getClassLoader()); } @Override - protected Set getExclusions(AnnotationMetadata metadata, - AnnotationAttributes attributes) { + protected Set getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) { Set exclusions = new LinkedHashSet<>(); Class source = ClassUtils.resolveClassName(metadata.getClassName(), null); for (String annotationName : ANNOTATION_NAMES) { - AnnotationAttributes merged = AnnotatedElementUtils - .getMergedAnnotationAttributes(source, annotationName); - Class[] exclude = (merged != null) ? merged.getClassArray("exclude") - : null; + AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName); + Class[] exclude = (merged != null) ? merged.getClassArray("exclude") : null; if (exclude != null) { for (Class excludeClass : exclude) { exclusions.add(excludeClass.getName()); @@ -120,8 +112,7 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec } for (List annotations : getAnnotations(metadata).values()) { for (Annotation annotation : annotations) { - String[] exclude = (String[]) AnnotationUtils - .getAnnotationAttributes(annotation, true).get("exclude"); + String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude"); if (!ObjectUtils.isEmpty(exclude)) { exclusions.addAll(Arrays.asList(exclude)); } @@ -130,21 +121,19 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec return exclusions; } - protected final Map, List> getAnnotations( - AnnotationMetadata metadata) { + protected final Map, List> getAnnotations(AnnotationMetadata metadata) { MultiValueMap, Annotation> annotations = new LinkedMultiValueMap<>(); Class source = ClassUtils.resolveClassName(metadata.getClassName(), null); collectAnnotations(source, annotations, new HashSet<>()); return Collections.unmodifiableMap(annotations); } - private void collectAnnotations(Class source, - MultiValueMap, Annotation> annotations, HashSet> seen) { + private void collectAnnotations(Class source, MultiValueMap, Annotation> annotations, + HashSet> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : source.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { - if (ANNOTATION_NAMES - .contains(annotation.annotationType().getName())) { + if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { annotations.add(source, annotation); } collectAnnotations(annotation.annotationType(), annotations, seen); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java index a9faba3bde4..71e00fa8412 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,16 +46,15 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; * @author Phillip Webb * @since 1.4.0 */ -class SharedMetadataReaderFactoryContextInitializer implements - ApplicationContextInitializer, Ordered { +class SharedMetadataReaderFactoryContextInitializer + implements ApplicationContextInitializer, Ordered { public static final String BEAN_NAME = "org.springframework.boot.autoconfigure." + "internalCachingMetadataReaderFactory"; @Override public void initialize(ConfigurableApplicationContext applicationContext) { - applicationContext.addBeanFactoryPostProcessor( - new CachingMetadataReaderFactoryPostProcessor()); + applicationContext.addBeanFactoryPostProcessor(new CachingMetadataReaderFactoryPostProcessor()); } @Override @@ -78,32 +77,27 @@ class SharedMetadataReaderFactoryContextInitializer implements } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { register(registry); configureConfigurationClassPostProcessor(registry); } private void register(BeanDefinitionRegistry registry) { BeanDefinition definition = BeanDefinitionBuilder - .genericBeanDefinition(SharedMetadataReaderFactoryBean.class, - SharedMetadataReaderFactoryBean::new) + .genericBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new) .getBeanDefinition(); registry.registerBeanDefinition(BEAN_NAME, definition); } - private void configureConfigurationClassPostProcessor( - BeanDefinitionRegistry registry) { + private void configureConfigurationClassPostProcessor(BeanDefinitionRegistry registry) { try { - BeanDefinition definition = registry.getBeanDefinition( - AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME); - definition.getPropertyValues().add("metadataReaderFactory", - new RuntimeBeanReference(BEAN_NAME)); + BeanDefinition definition = registry + .getBeanDefinition(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME); + definition.getPropertyValues().add("metadataReaderFactory", new RuntimeBeanReference(BEAN_NAME)); } catch (NoSuchBeanDefinitionException ex) { } @@ -115,20 +109,18 @@ class SharedMetadataReaderFactoryContextInitializer implements * {@link FactoryBean} to create the shared {@link MetadataReaderFactory}. */ static class SharedMetadataReaderFactoryBean - implements FactoryBean, - BeanClassLoaderAware, ApplicationListener { + implements FactoryBean, BeanClassLoaderAware, + ApplicationListener { private ConcurrentReferenceCachingMetadataReaderFactory metadataReaderFactory; @Override public void setBeanClassLoader(ClassLoader classLoader) { - this.metadataReaderFactory = new ConcurrentReferenceCachingMetadataReaderFactory( - classLoader); + this.metadataReaderFactory = new ConcurrentReferenceCachingMetadataReaderFactory(classLoader); } @Override - public ConcurrentReferenceCachingMetadataReaderFactory getObject() - throws Exception { + public ConcurrentReferenceCachingMetadataReaderFactory getObject() throws Exception { return this.metadataReaderFactory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java index b52c4341330..347c37bd0bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java @@ -53,10 +53,8 @@ import org.springframework.core.annotation.AliasFor; @Inherited @SpringBootConfiguration @EnableAutoConfiguration -@ComponentScan(excludeFilters = { - @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), - @Filter(type = FilterType.CUSTOM, - classes = AutoConfigurationExcludeFilter.class) }) +@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), + @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) @ConfigurationPropertiesScan public @interface SpringBootApplication { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java index cf4efa34530..1ed6ca48994 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java @@ -41,8 +41,8 @@ import org.springframework.jmx.export.MBeanExporter; */ @Configuration(proxyBeanMethods = false) @AutoConfigureAfter(JmxAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled", - havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled", havingValue = "true", + matchIfMissing = false) public class SpringApplicationAdminJmxAutoConfiguration { /** @@ -59,8 +59,7 @@ public class SpringApplicationAdminJmxAutoConfiguration { @Bean @ConditionalOnMissingBean public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar( - ObjectProvider mbeanExporters, Environment environment) - throws MalformedObjectNameException { + ObjectProvider mbeanExporters, Environment environment) throws MalformedObjectNameException { String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice for (MBeanExporter mbeanExporter : mbeanExporters) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractRabbitListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractRabbitListenerContainerFactoryConfigurer.java index 7932cae2482..3b7f668dbe6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractRabbitListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractRabbitListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,7 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer retryTemplateCustomizers) { + protected void setRetryTemplateCustomizers(List retryTemplateCustomizers) { this.retryTemplateCustomizers = retryTemplateCustomizers; } @@ -119,15 +118,13 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer builder = (retryConfig.isStateless()) - ? RetryInterceptorBuilder.stateless() + RetryInterceptorBuilder builder = (retryConfig.isStateless()) ? RetryInterceptorBuilder.stateless() : RetryInterceptorBuilder.stateful(); - RetryTemplate retryTemplate = new RetryTemplateFactory( - this.retryTemplateCustomizers).createRetryTemplate(retryConfig, - RabbitRetryTemplateCustomizer.Target.LISTENER); + RetryTemplate retryTemplate = new RetryTemplateFactory(this.retryTemplateCustomizers) + .createRetryTemplate(retryConfig, RabbitRetryTemplateCustomizer.Target.LISTENER); builder.retryOperations(retryTemplate); - MessageRecoverer recoverer = (this.messageRecoverer != null) - ? this.messageRecoverer : new RejectAndDontRequeueRecoverer(); + MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer + : new RejectAndDontRequeueRecoverer(); builder.recoverer(recoverer); factory.setAdviceChain(builder.build()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/DirectRabbitListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/DirectRabbitListenerContainerFactoryConfigurer.java index a0cd6b8e49d..29f086e9fe0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/DirectRabbitListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/DirectRabbitListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,18 +28,15 @@ import org.springframework.boot.context.properties.PropertyMapper; * @author Stephane Nicoll * @since 2.0 */ -public final class DirectRabbitListenerContainerFactoryConfigurer extends - AbstractRabbitListenerContainerFactoryConfigurer { +public final class DirectRabbitListenerContainerFactoryConfigurer + extends AbstractRabbitListenerContainerFactoryConfigurer { @Override - public void configure(DirectRabbitListenerContainerFactory factory, - ConnectionFactory connectionFactory) { + public void configure(DirectRabbitListenerContainerFactory factory, ConnectionFactory connectionFactory) { PropertyMapper map = PropertyMapper.get(); - RabbitProperties.DirectContainer config = getRabbitProperties().getListener() - .getDirect(); + RabbitProperties.DirectContainer config = getRabbitProperties().getListener().getDirect(); configure(factory, connectionFactory, config); - map.from(config::getConsumersPerQueue).whenNonNull() - .to(factory::setConsumersPerQueue); + map.from(config::getConsumersPerQueue).whenNonNull().to(factory::setConsumersPerQueue); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java index a49f962e266..8e6fe469530 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java @@ -53,8 +53,7 @@ class RabbitAnnotationDrivenConfiguration { RabbitAnnotationDrivenConfiguration(ObjectProvider messageConverter, ObjectProvider messageRecoverer, - ObjectProvider retryTemplateCustomizers, - RabbitProperties properties) { + ObjectProvider retryTemplateCustomizers, RabbitProperties properties) { this.messageConverter = messageConverter; this.messageRecoverer = messageRecoverer; this.retryTemplateCustomizers = retryTemplateCustomizers; @@ -67,19 +66,18 @@ class RabbitAnnotationDrivenConfiguration { SimpleRabbitListenerContainerFactoryConfigurer configurer = new SimpleRabbitListenerContainerFactoryConfigurer(); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique()); - configurer.setRetryTemplateCustomizers(this.retryTemplateCustomizers - .orderedStream().collect(Collectors.toList())); + configurer.setRetryTemplateCustomizers( + this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); configurer.setRabbitProperties(this.properties); return configurer; } @Bean(name = "rabbitListenerContainerFactory") @ConditionalOnMissingBean(name = "rabbitListenerContainerFactory") - @ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", - havingValue = "simple", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", havingValue = "simple", + matchIfMissing = true) public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory( - SimpleRabbitListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; @@ -91,19 +89,17 @@ class RabbitAnnotationDrivenConfiguration { DirectRabbitListenerContainerFactoryConfigurer configurer = new DirectRabbitListenerContainerFactoryConfigurer(); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique()); - configurer.setRetryTemplateCustomizers(this.retryTemplateCustomizers - .orderedStream().collect(Collectors.toList())); + configurer.setRetryTemplateCustomizers( + this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); configurer.setRabbitProperties(this.properties); return configurer; } @Bean(name = "rabbitListenerContainerFactory") @ConditionalOnMissingBean(name = "rabbitListenerContainerFactory") - @ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", - havingValue = "direct") + @ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", havingValue = "direct") public DirectRabbitListenerContainerFactory directRabbitListenerContainerFactory( - DirectRabbitListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + DirectRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; @@ -111,8 +107,7 @@ class RabbitAnnotationDrivenConfiguration { @Configuration(proxyBeanMethods = false) @EnableRabbit - @ConditionalOnMissingBean( - name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean(name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) protected static class EnableRabbitConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java index 2f04f6929c5..90beff30fd9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java @@ -92,10 +92,8 @@ public class RabbitAutoConfiguration { protected static class RabbitConnectionFactoryCreator { @Bean - public CachingConnectionFactory rabbitConnectionFactory( - RabbitProperties properties, - ObjectProvider connectionNameStrategy) - throws Exception { + public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties properties, + ObjectProvider connectionNameStrategy) throws Exception { PropertyMapper map = PropertyMapper.get(); CachingConnectionFactory factory = new CachingConnectionFactory( getRabbitConnectionFactoryBean(properties).getObject()); @@ -106,30 +104,24 @@ public class RabbitAutoConfiguration { map.from(channel::getSize).whenNonNull().to(factory::setChannelCacheSize); map.from(channel::getCheckoutTimeout).whenNonNull().as(Duration::toMillis) .to(factory::setChannelCheckoutTimeout); - RabbitProperties.Cache.Connection connection = properties.getCache() - .getConnection(); + RabbitProperties.Cache.Connection connection = properties.getCache().getConnection(); map.from(connection::getMode).whenNonNull().to(factory::setCacheMode); - map.from(connection::getSize).whenNonNull() - .to(factory::setConnectionCacheSize); - map.from(connectionNameStrategy::getIfUnique).whenNonNull() - .to(factory::setConnectionNameStrategy); + map.from(connection::getSize).whenNonNull().to(factory::setConnectionCacheSize); + map.from(connectionNameStrategy::getIfUnique).whenNonNull().to(factory::setConnectionNameStrategy); return factory; } - private RabbitConnectionFactoryBean getRabbitConnectionFactoryBean( - RabbitProperties properties) throws Exception { + private RabbitConnectionFactoryBean getRabbitConnectionFactoryBean(RabbitProperties properties) + throws Exception { PropertyMapper map = PropertyMapper.get(); RabbitConnectionFactoryBean factory = new RabbitConnectionFactoryBean(); map.from(properties::determineHost).whenNonNull().to(factory::setHost); map.from(properties::determinePort).to(factory::setPort); - map.from(properties::determineUsername).whenNonNull() - .to(factory::setUsername); - map.from(properties::determinePassword).whenNonNull() - .to(factory::setPassword); - map.from(properties::determineVirtualHost).whenNonNull() - .to(factory::setVirtualHost); - map.from(properties::getRequestedHeartbeat).whenNonNull() - .asInt(Duration::getSeconds).to(factory::setRequestedHeartbeat); + map.from(properties::determineUsername).whenNonNull().to(factory::setUsername); + map.from(properties::determinePassword).whenNonNull().to(factory::setPassword); + map.from(properties::determineVirtualHost).whenNonNull().to(factory::setVirtualHost); + map.from(properties::getRequestedHeartbeat).whenNonNull().asInt(Duration::getSeconds) + .to(factory::setRequestedHeartbeat); RabbitProperties.Ssl ssl = properties.getSsl(); if (ssl.isEnabled()) { factory.setUseSSL(true); @@ -140,13 +132,12 @@ public class RabbitAutoConfiguration { map.from(ssl::getTrustStoreType).to(factory::setTrustStoreType); map.from(ssl::getTrustStore).to(factory::setTrustStore); map.from(ssl::getTrustStorePassword).to(factory::setTrustStorePassphrase); - map.from(ssl::isValidateServerCertificate).to((validate) -> factory - .setSkipServerCertificateValidation(!validate)); - map.from(ssl::getVerifyHostname) - .to(factory::setEnableHostnameVerification); + map.from(ssl::isValidateServerCertificate) + .to((validate) -> factory.setSkipServerCertificateValidation(!validate)); + map.from(ssl::getVerifyHostname).to(factory::setEnableHostnameVerification); } - map.from(properties::getConnectionTimeout).whenNonNull() - .asInt(Duration::toMillis).to(factory::setConnectionTimeout); + map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) + .to(factory::setConnectionTimeout); factory.afterPropertiesSet(); return factory; } @@ -171,19 +162,17 @@ public class RabbitAutoConfiguration { RabbitProperties.Template templateProperties = properties.getTemplate(); if (templateProperties.getRetry().isEnabled()) { template.setRetryTemplate( - new RetryTemplateFactory(retryTemplateCustomizers.orderedStream() - .collect(Collectors.toList())).createRetryTemplate( - templateProperties.getRetry(), + new RetryTemplateFactory(retryTemplateCustomizers.orderedStream().collect(Collectors.toList())) + .createRetryTemplate(templateProperties.getRetry(), RabbitRetryTemplateCustomizer.Target.SENDER)); } - map.from(templateProperties::getReceiveTimeout).whenNonNull() - .as(Duration::toMillis).to(template::setReceiveTimeout); - map.from(templateProperties::getReplyTimeout).whenNonNull() - .as(Duration::toMillis).to(template::setReplyTimeout); + map.from(templateProperties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) + .to(template::setReceiveTimeout); + map.from(templateProperties::getReplyTimeout).whenNonNull().as(Duration::toMillis) + .to(template::setReplyTimeout); map.from(templateProperties::getExchange).to(template::setExchange); map.from(templateProperties::getRoutingKey).to(template::setRoutingKey); - map.from(templateProperties::getDefaultReceiveQueue).whenNonNull() - .to(template::setDefaultReceiveQueue); + map.from(templateProperties::getDefaultReceiveQueue).whenNonNull().to(template::setDefaultReceiveQueue); return template; } @@ -194,8 +183,7 @@ public class RabbitAutoConfiguration { @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) - @ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true) @ConditionalOnMissingBean public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) { return new RabbitAdmin(connectionFactory); @@ -211,8 +199,7 @@ public class RabbitAutoConfiguration { @Bean @ConditionalOnSingleCandidate(RabbitTemplate.class) - public RabbitMessagingTemplate rabbitMessagingTemplate( - RabbitTemplate rabbitTemplate) { + public RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) { return new RabbitMessagingTemplate(rabbitTemplate); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java index a18e33bf74d..9785135160d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ class RetryTemplateFactory { map.from(properties::getInitialInterval).whenNonNull().as(Duration::toMillis) .to(backOffPolicy::setInitialInterval); map.from(properties::getMultiplier).to(backOffPolicy::setMultiplier); - map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis) - .to(backOffPolicy::setMaxInterval); + map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis).to(backOffPolicy::setMaxInterval); template.setBackOffPolicy(backOffPolicy); if (this.customizers != null) { for (RabbitRetryTemplateCustomizer customizer : this.customizers) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java index 52181a4748f..a45c1bb6206 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,20 +28,16 @@ import org.springframework.boot.context.properties.PropertyMapper; * @author Gary Russell * @since 1.3.3 */ -public final class SimpleRabbitListenerContainerFactoryConfigurer extends - AbstractRabbitListenerContainerFactoryConfigurer { +public final class SimpleRabbitListenerContainerFactoryConfigurer + extends AbstractRabbitListenerContainerFactoryConfigurer { @Override - public void configure(SimpleRabbitListenerContainerFactory factory, - ConnectionFactory connectionFactory) { + public void configure(SimpleRabbitListenerContainerFactory factory, ConnectionFactory connectionFactory) { PropertyMapper map = PropertyMapper.get(); - RabbitProperties.SimpleContainer config = getRabbitProperties().getListener() - .getSimple(); + RabbitProperties.SimpleContainer config = getRabbitProperties().getListener().getSimple(); configure(factory, connectionFactory, config); - map.from(config::getConcurrency).whenNonNull() - .to(factory::setConcurrentConsumers); - map.from(config::getMaxConcurrency).whenNonNull() - .to(factory::setMaxConcurrentConsumers); + map.from(config::getConcurrency).whenNonNull().to(factory::setConcurrentConsumers); + map.from(config::getMaxConcurrency).whenNonNull().to(factory::setMaxConcurrentConsumers); map.from(config::getTransactionSize).whenNonNull().to(factory::setTxSize); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java index e23cccf5eae..3655262f7b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java @@ -39,24 +39,22 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; * @see EnableAspectJAutoProxy */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class, - AnnotatedElement.class }) -@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", - matchIfMissing = true) +@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class, AnnotatedElement.class }) +@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true) public class AopAutoConfiguration { @Configuration(proxyBeanMethods = false) @EnableAspectJAutoProxy(proxyTargetClass = false) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "false", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", + matchIfMissing = false) public static class JdkDynamicAutoProxyConfiguration { } @Configuration(proxyBeanMethods = false) @EnableAspectJAutoProxy(proxyTargetClass = true) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", + matchIfMissing = true) public static class CglibAutoProxyConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java index c2d502f8669..a88aeec23c6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,8 +106,7 @@ public class BasicBatchConfigurer implements BatchConfigurer { PropertyMapper map = PropertyMapper.get(); JobExplorerFactoryBean factory = new JobExplorerFactoryBean(); factory.setDataSource(this.dataSource); - map.from(this.properties::getTablePrefix).whenHasText() - .to(factory::setTablePrefix); + map.from(this.properties::getTablePrefix).whenHasText().to(factory::setTablePrefix); factory.afterPropertiesSet(); return factory.getObject(); } @@ -123,10 +122,8 @@ public class BasicBatchConfigurer implements BatchConfigurer { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); PropertyMapper map = PropertyMapper.get(); map.from(this.dataSource).to(factory::setDataSource); - map.from(this::determineIsolationLevel).whenNonNull() - .to(factory::setIsolationLevelForCreate); - map.from(this.properties::getTablePrefix).whenHasText() - .to(factory::setTablePrefix); + map.from(this::determineIsolationLevel).whenNonNull().to(factory::setIsolationLevelForCreate); + map.from(this.properties::getTablePrefix).whenHasText().to(factory::setTablePrefix); map.from(this::getTransactionManager).to(factory::setTransactionManager); factory.afterPropertiesSet(); return factory.getObject(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java index 2c1c46fb082..8fd6fadb526 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java @@ -75,21 +75,16 @@ public class BatchAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(DataSource.class) - public BatchDataSourceInitializer batchDataSourceInitializer(DataSource dataSource, - ResourceLoader resourceLoader) { - return new BatchDataSourceInitializer(dataSource, resourceLoader, - this.properties); + public BatchDataSourceInitializer batchDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) { + return new BatchDataSourceInitializer(dataSource, resourceLoader, this.properties); } @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", - havingValue = "true", matchIfMissing = true) - public JobLauncherCommandLineRunner jobLauncherCommandLineRunner( - JobLauncher jobLauncher, JobExplorer jobExplorer, + @ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true) + public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, JobRepository jobRepository) { - JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner( - jobLauncher, jobExplorer, jobRepository); + JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(jobLauncher, jobExplorer, jobRepository); String jobNames = this.properties.getJob().getNames(); if (StringUtils.hasText(jobNames)) { runner.setJobNames(jobNames); @@ -105,11 +100,9 @@ public class BatchAutoConfiguration { @Bean @ConditionalOnMissingBean(JobOperator.class) - public SimpleJobOperator jobOperator( - ObjectProvider jobParametersConverter, - JobExplorer jobExplorer, JobLauncher jobLauncher, - ListableJobLocator jobRegistry, JobRepository jobRepository) - throws Exception { + public SimpleJobOperator jobOperator(ObjectProvider jobParametersConverter, + JobExplorer jobExplorer, JobLauncher jobLauncher, ListableJobLocator jobRegistry, + JobRepository jobRepository) throws Exception { SimpleJobOperator factory = new SimpleJobOperator(); factory.setJobExplorer(jobExplorer); factory.setJobLauncher(jobLauncher); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchConfigurerConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchConfigurerConfiguration.java index 99d3718f612..17607ca189b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchConfigurerConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchConfigurerConfiguration.java @@ -44,11 +44,9 @@ class BatchConfigurerConfiguration { static class JdbcBatchConfiguration { @Bean - public BasicBatchConfigurer batchConfigurer(BatchProperties properties, - DataSource dataSource, + public BasicBatchConfigurer batchConfigurer(BatchProperties properties, DataSource dataSource, ObjectProvider transactionManagerCustomizers) { - return new BasicBatchConfigurer(properties, dataSource, - transactionManagerCustomizers.getIfAvailable()); + return new BasicBatchConfigurer(properties, dataSource, transactionManagerCustomizers.getIfAvailable()); } } @@ -59,12 +57,11 @@ class BatchConfigurerConfiguration { static class JpaBatchConfiguration { @Bean - public JpaBatchConfigurer batchConfigurer(BatchProperties properties, - DataSource dataSource, + public JpaBatchConfigurer batchConfigurer(BatchProperties properties, DataSource dataSource, ObjectProvider transactionManagerCustomizers, EntityManagerFactory entityManagerFactory) { - return new JpaBatchConfigurer(properties, dataSource, - transactionManagerCustomizers.getIfAvailable(), entityManagerFactory); + return new JpaBatchConfigurer(properties, dataSource, transactionManagerCustomizers.getIfAvailable(), + entityManagerFactory); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceInitializer.java index 10d7bf33e41..a59da6ee0b5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ public class BatchDataSourceInitializer extends AbstractDataSourceInitializer { private final BatchProperties properties; - public BatchDataSourceInitializer(DataSource dataSource, - ResourceLoader resourceLoader, BatchProperties properties) { + public BatchDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader, + BatchProperties properties) { super(dataSource, resourceLoader); Assert.notNull(properties, "BatchProperties must not be null"); this.properties = properties; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java index e31762880b6..b228ee35626 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.context.ApplicationListener; * * @author Dave Syer */ -public class JobExecutionExitCodeGenerator - implements ApplicationListener, ExitCodeGenerator { +public class JobExecutionExitCodeGenerator implements ApplicationListener, ExitCodeGenerator { private final List executions = new ArrayList<>(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java index 85a07352587..60b76b90386 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java @@ -64,16 +64,14 @@ import org.springframework.util.StringUtils; * @author Jean-Pierre Bergamin * @author Mahmoud Ben Hassine */ -public class JobLauncherCommandLineRunner - implements CommandLineRunner, Ordered, ApplicationEventPublisherAware { +public class JobLauncherCommandLineRunner implements CommandLineRunner, Ordered, ApplicationEventPublisherAware { /** * The default order for the command line runner. */ public static final int DEFAULT_ORDER = 0; - private static final Log logger = LogFactory - .getLog(JobLauncherCommandLineRunner.class); + private static final Log logger = LogFactory.getLog(JobLauncherCommandLineRunner.class); private JobParametersConverter converter = new DefaultJobParametersConverter(); @@ -100,8 +98,7 @@ public class JobLauncherCommandLineRunner * @param jobRepository to check if a job instance exists with the given parameters * when running a job */ - public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, - JobRepository jobRepository) { + public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, JobRepository jobRepository) { Assert.notNull(jobLauncher, "JobLauncher must not be null"); Assert.notNull(jobExplorer, "JobExplorer must not be null"); Assert.notNull(jobRepository, "JobRepository must not be null"); @@ -149,15 +146,13 @@ public class JobLauncherCommandLineRunner launchJobFromProperties(StringUtils.splitArrayElementsIntoProperties(args, "=")); } - protected void launchJobFromProperties(Properties properties) - throws JobExecutionException { + protected void launchJobFromProperties(Properties properties) throws JobExecutionException { JobParameters jobParameters = this.converter.getJobParameters(properties); executeLocalJobs(jobParameters); executeRegisteredJobs(jobParameters); } - private void executeLocalJobs(JobParameters jobParameters) - throws JobExecutionException { + private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException { for (Job job : this.jobs) { if (StringUtils.hasText(this.jobNames)) { String[] jobsToRun = this.jobNames.split(","); @@ -170,8 +165,7 @@ public class JobLauncherCommandLineRunner } } - private void executeRegisteredJobs(JobParameters jobParameters) - throws JobExecutionException { + private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException { if (this.jobRegistry != null && StringUtils.hasText(this.jobNames)) { String[] jobsToRun = this.jobNames.split(","); for (String jobName : jobsToRun) { @@ -190,9 +184,8 @@ public class JobLauncherCommandLineRunner } protected void execute(Job job, JobParameters jobParameters) - throws JobExecutionAlreadyRunningException, JobRestartException, - JobInstanceAlreadyCompleteException, JobParametersInvalidException, - JobParametersNotFoundException { + throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, + JobParametersInvalidException, JobParametersNotFoundException { JobParameters parameters = getNextJobParameters(job, jobParameters); JobExecution execution = this.jobLauncher.run(job, parameters); if (this.publisher != null) { @@ -201,25 +194,21 @@ public class JobLauncherCommandLineRunner } private JobParameters getNextJobParameters(Job job, JobParameters jobParameters) { - if (this.jobRepository != null - && this.jobRepository.isJobInstanceExists(job.getName(), jobParameters)) { + if (this.jobRepository != null && this.jobRepository.isJobInstanceExists(job.getName(), jobParameters)) { return getNextJobParametersForExisting(job, jobParameters); } if (job.getJobParametersIncrementer() == null) { return jobParameters; } - JobParameters nextParameters = new JobParametersBuilder(jobParameters, - this.jobExplorer).getNextJobParameters(job).toJobParameters(); + JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer) + .getNextJobParameters(job).toJobParameters(); return merge(nextParameters, jobParameters); } - private JobParameters getNextJobParametersForExisting(Job job, - JobParameters jobParameters) { - JobExecution lastExecution = this.jobRepository.getLastJobExecution(job.getName(), - jobParameters); + private JobParameters getNextJobParametersForExisting(Job job, JobParameters jobParameters) { + JobExecution lastExecution = this.jobRepository.getLastJobExecution(job.getName(), jobParameters); if (isStoppedOrFailed(lastExecution) && job.isRestartable()) { - JobParameters previousIdentifyingParameters = getGetIdentifying( - lastExecution.getJobParameters()); + JobParameters previousIdentifyingParameters = getGetIdentifying(lastExecution.getJobParameters()); return merge(previousIdentifyingParameters, jobParameters); } return jobParameters; @@ -231,8 +220,7 @@ public class JobLauncherCommandLineRunner } private JobParameters getGetIdentifying(JobParameters parameters) { - HashMap nonIdentifying = new LinkedHashMap<>( - parameters.getParameters().size()); + HashMap nonIdentifying = new LinkedHashMap<>(parameters.getParameters().size()); parameters.getParameters().forEach((key, value) -> { if (value.isIdentifying()) { nonIdentifying.put(key, value); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JpaBatchConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JpaBatchConfigurer.java index 3a49d688a1f..f4f994c90bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JpaBatchConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JpaBatchConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,16 +46,14 @@ public class JpaBatchConfigurer extends BasicBatchConfigurer { * @param entityManagerFactory the entity manager factory (or {@code null}) */ protected JpaBatchConfigurer(BatchProperties properties, DataSource dataSource, - TransactionManagerCustomizers transactionManagerCustomizers, - EntityManagerFactory entityManagerFactory) { + TransactionManagerCustomizers transactionManagerCustomizers, EntityManagerFactory entityManagerFactory) { super(properties, dataSource, transactionManagerCustomizers); this.entityManagerFactory = entityManagerFactory; } @Override protected String determineIsolationLevel() { - logger.warn( - "JPA does not support custom isolation levels, so locks may not be taken when launching Jobs"); + logger.warn("JPA does not support custom isolation levels, so locks may not be taken when launching Jobs"); return "ISOLATION_DEFAULT"; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java index c7a72b276e9..9bf7f68e901 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java @@ -67,23 +67,20 @@ public class CacheAutoConfiguration { @Bean @ConditionalOnMissingBean - public CacheManagerCustomizers cacheManagerCustomizers( - ObjectProvider> customizers) { - return new CacheManagerCustomizers( - customizers.orderedStream().collect(Collectors.toList())); + public CacheManagerCustomizers cacheManagerCustomizers(ObjectProvider> customizers) { + return new CacheManagerCustomizers(customizers.orderedStream().collect(Collectors.toList())); } @Bean - public CacheManagerValidator cacheAutoConfigurationValidator( - CacheProperties cacheProperties, ObjectProvider cacheManager) { + public CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties, + ObjectProvider cacheManager) { return new CacheManagerValidator(cacheProperties, cacheManager); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class CacheManagerJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class CacheManagerJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public CacheManagerJpaDependencyConfiguration() { super("cacheManager"); @@ -101,8 +98,7 @@ public class CacheAutoConfiguration { private final ObjectProvider cacheManager; - CacheManagerValidator(CacheProperties cacheProperties, - ObjectProvider cacheManager) { + CacheManagerValidator(CacheProperties cacheProperties, ObjectProvider cacheManager) { this.cacheProperties = cacheProperties; this.cacheManager = cacheManager; } @@ -110,8 +106,7 @@ public class CacheAutoConfiguration { @Override public void afterPropertiesSet() { Assert.notNull(this.cacheManager.getIfAvailable(), - () -> "No cache manager could " - + "be auto-configured, check your configuration (caching " + () -> "No cache manager could " + "be auto-configured, check your configuration (caching " + "type is '" + this.cacheProperties.getType() + "')"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java index eab67eb6451..8939338f7ce 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,26 +39,21 @@ import org.springframework.core.type.ClassMetadata; class CacheCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String sourceClass = ""; if (metadata instanceof ClassMetadata) { sourceClass = ((ClassMetadata) metadata).getClassName(); } - ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", - sourceClass); + ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", sourceClass); Environment environment = context.getEnvironment(); try { - BindResult specified = Binder.get(environment) - .bind("spring.cache.type", CacheType.class); + BindResult specified = Binder.get(environment).bind("spring.cache.type", CacheType.class); if (!specified.isBound()) { return ConditionOutcome.match(message.because("automatic cache type")); } - CacheType required = CacheConfigurations - .getType(((AnnotationMetadata) metadata).getClassName()); + CacheType required = CacheConfigurations.getType(((AnnotationMetadata) metadata).getClassName()); if (specified.get() == required) { - return ConditionOutcome - .match(message.because(specified.get() + " cache type")); + return ConditionOutcome.match(message.because(specified.get() + " cache type")); } } catch (BindException ex) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java index 67b8d0868bd..0fa8e0f0aa2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ final class CacheConfigurations { return entry.getKey(); } } - throw new IllegalStateException( - "Unknown configuration class " + configurationClassName); + throw new IllegalStateException("Unknown configuration class " + configurationClassName); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java index 370bae989ca..c50f4fea132 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,10 +34,8 @@ public class CacheManagerCustomizers { private final List> customizers; - public CacheManagerCustomizers( - List> customizers) { - this.customizers = (customizers != null) ? new ArrayList<>(customizers) - : Collections.emptyList(); + public CacheManagerCustomizers(List> customizers) { + this.customizers = (customizers != null) ? new ArrayList<>(customizers) : Collections.emptyList(); } /** @@ -51,8 +49,7 @@ public class CacheManagerCustomizers { @SuppressWarnings("unchecked") public T customize(T cacheManager) { LambdaSafe.callbacks(CacheManagerCustomizer.class, this.customizers, cacheManager) - .withLogger(CacheManagerCustomizers.class) - .invoke((customizer) -> customizer.customize(cacheManager)); + .withLogger(CacheManagerCustomizers.class).invoke((customizer) -> customizer.customize(cacheManager)); return cacheManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java index 7798c48bfcb..4ef13b702fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,8 +107,8 @@ public class CacheProperties { */ public Resource resolveConfigLocation(Resource config) { if (config != null) { - Assert.isTrue(config.exists(), () -> "Cache configuration does not exist '" - + config.getDescription() + "'"); + Assert.isTrue(config.exists(), + () -> "Cache configuration does not exist '" + config.getDescription() + "'"); return config; } return null; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java index 1eb603391ff..6f5ee9ddad8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java @@ -46,13 +46,10 @@ import org.springframework.util.StringUtils; class CaffeineCacheConfiguration { @Bean - public CaffeineCacheManager cacheManager(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, - ObjectProvider> caffeine, - ObjectProvider caffeineSpec, + public CaffeineCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers customizers, + ObjectProvider> caffeine, ObjectProvider caffeineSpec, ObjectProvider> cacheLoader) { - CaffeineCacheManager cacheManager = createCacheManager(cacheProperties, caffeine, - caffeineSpec, cacheLoader); + CaffeineCacheManager cacheManager = createCacheManager(cacheProperties, caffeine, caffeineSpec, cacheLoader); List cacheNames = cacheProperties.getCacheNames(); if (!CollectionUtils.isEmpty(cacheNames)) { cacheManager.setCacheNames(cacheNames); @@ -61,19 +58,16 @@ class CaffeineCacheConfiguration { } private CaffeineCacheManager createCacheManager(CacheProperties cacheProperties, - ObjectProvider> caffeine, - ObjectProvider caffeineSpec, + ObjectProvider> caffeine, ObjectProvider caffeineSpec, ObjectProvider> cacheLoader) { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); - setCacheBuilder(cacheProperties, caffeineSpec.getIfAvailable(), - caffeine.getIfAvailable(), cacheManager); + setCacheBuilder(cacheProperties, caffeineSpec.getIfAvailable(), caffeine.getIfAvailable(), cacheManager); cacheLoader.ifAvailable(cacheManager::setCacheLoader); return cacheManager; } - private void setCacheBuilder(CacheProperties cacheProperties, - CaffeineSpec caffeineSpec, Caffeine caffeine, - CaffeineCacheManager cacheManager) { + private void setCacheBuilder(CacheProperties cacheProperties, CaffeineSpec caffeineSpec, + Caffeine caffeine, CaffeineCacheManager cacheManager) { String specification = cacheProperties.getCaffeine().getSpec(); if (StringUtils.hasText(specification)) { cacheManager.setCacheSpecification(specification); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java index ea6ec21e0d7..69c1742f13d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java @@ -48,13 +48,13 @@ import org.springframework.util.StringUtils; public class CouchbaseCacheConfiguration { @Bean - public CouchbaseCacheManager cacheManager(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, Bucket bucket) { + public CouchbaseCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers customizers, + Bucket bucket) { List cacheNames = cacheProperties.getCacheNames(); CacheBuilder builder = CacheBuilder.newInstance(bucket); Couchbase couchbase = cacheProperties.getCouchbase(); - PropertyMapper.get().from(couchbase::getExpiration).whenNonNull() - .asInt(Duration::getSeconds).to(builder::withExpiration); + PropertyMapper.get().from(couchbase::getExpiration).whenNonNull().asInt(Duration::getSeconds) + .to(builder::withExpiration); String[] names = StringUtils.toStringArray(cacheNames); CouchbaseCacheManager cacheManager = new CouchbaseCacheManager(builder, names); return customizers.customize(cacheManager); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java index f4445e4aa32..2cf11ee1332 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java @@ -41,21 +41,18 @@ import org.springframework.core.io.Resource; @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Cache.class, EhCacheCacheManager.class }) @ConditionalOnMissingBean(org.springframework.cache.CacheManager.class) -@Conditional({ CacheCondition.class, - EhCacheCacheConfiguration.ConfigAvailableCondition.class }) +@Conditional({ CacheCondition.class, EhCacheCacheConfiguration.ConfigAvailableCondition.class }) class EhCacheCacheConfiguration { @Bean - public EhCacheCacheManager cacheManager(CacheManagerCustomizers customizers, - CacheManager ehCacheCacheManager) { + public EhCacheCacheManager cacheManager(CacheManagerCustomizers customizers, CacheManager ehCacheCacheManager) { return customizers.customize(new EhCacheCacheManager(ehCacheCacheManager)); } @Bean @ConditionalOnMissingBean public CacheManager ehCacheCacheManager(CacheProperties cacheProperties) { - Resource location = cacheProperties - .resolveConfigLocation(cacheProperties.getEhcache().getConfig()); + Resource location = cacheProperties.resolveConfigLocation(cacheProperties.getEhcache().getConfig()); if (location != null) { return EhCacheManagerUtils.buildCacheManager(location); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GenericCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GenericCacheConfiguration.java index 73f53c42866..59d4c44651e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GenericCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GenericCacheConfiguration.java @@ -41,8 +41,7 @@ import org.springframework.context.annotation.Configuration; class GenericCacheConfiguration { @Bean - public SimpleCacheManager cacheManager(CacheManagerCustomizers customizers, - Collection caches) { + public SimpleCacheManager cacheManager(CacheManagerCustomizers customizers, Collection caches) { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCaches(caches); return customizers.customize(cacheManager); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java index bb3032e2787..a4b0fd1024d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java @@ -53,8 +53,7 @@ class HazelcastCacheConfiguration { @Bean public HazelcastCacheManager cacheManager(CacheManagerCustomizers customizers, HazelcastInstance existingHazelcastInstance) throws IOException { - HazelcastCacheManager cacheManager = new HazelcastCacheManager( - existingHazelcastInstance); + HazelcastCacheManager cacheManager = new HazelcastCacheManager(existingHazelcastInstance); return customizers.customize(cacheManager); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java index 928ee835d03..0ed1c4f7f74 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java @@ -53,12 +53,10 @@ class HazelcastJCacheCustomizationConfiguration { @Override public void customize(CacheProperties cacheProperties, Properties properties) { - Resource configLocation = cacheProperties - .resolveConfigLocation(cacheProperties.getJcache().getConfig()); + Resource configLocation = cacheProperties.resolveConfigLocation(cacheProperties.getJcache().getConfig()); if (configLocation != null) { // Hazelcast does not use the URI as a mean to specify a custom config. - properties.setProperty("hazelcast.config.location", - toUri(configLocation).toString()); + properties.setProperty("hazelcast.config.location", toUri(configLocation).toString()); } else if (this.hazelcastInstance != null) { properties.put("hazelcast.instance.itself", this.hazelcastInstance); @@ -70,8 +68,7 @@ class HazelcastJCacheCustomizationConfiguration { return config.getURI(); } catch (IOException ex) { - throw new IllegalArgumentException("Could not get URI from " + config, - ex); + throw new IllegalArgumentException("Could not get URI from " + config, ex); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java index 16bb704b977..3eb68908bfc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java @@ -52,30 +52,25 @@ public class InfinispanCacheConfiguration { @Bean public SpringEmbeddedCacheManager cacheManager(CacheManagerCustomizers customizers, EmbeddedCacheManager embeddedCacheManager) { - SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager( - embeddedCacheManager); + SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager(embeddedCacheManager); return customizers.customize(cacheManager); } @Bean(destroyMethod = "stop") @ConditionalOnMissingBean public EmbeddedCacheManager infinispanCacheManager(CacheProperties cacheProperties, - ObjectProvider defaultConfigurationBuilder) - throws IOException { + ObjectProvider defaultConfigurationBuilder) throws IOException { EmbeddedCacheManager cacheManager = createEmbeddedCacheManager(cacheProperties); List cacheNames = cacheProperties.getCacheNames(); if (!CollectionUtils.isEmpty(cacheNames)) { cacheNames.forEach((cacheName) -> cacheManager.defineConfiguration(cacheName, - getDefaultCacheConfiguration( - defaultConfigurationBuilder.getIfAvailable()))); + getDefaultCacheConfiguration(defaultConfigurationBuilder.getIfAvailable()))); } return cacheManager; } - private EmbeddedCacheManager createEmbeddedCacheManager( - CacheProperties cacheProperties) throws IOException { - Resource location = cacheProperties - .resolveConfigLocation(cacheProperties.getInfinispan().getConfig()); + private EmbeddedCacheManager createEmbeddedCacheManager(CacheProperties cacheProperties) throws IOException { + Resource location = cacheProperties.resolveConfigLocation(cacheProperties.getInfinispan().getConfig()); if (location != null) { try (InputStream in = location.getInputStream()) { return new DefaultCacheManager(in); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java index 1ef08f917d2..7ef4f9e15fc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java @@ -58,8 +58,7 @@ import org.springframework.util.StringUtils; @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) @ConditionalOnMissingBean(org.springframework.cache.CacheManager.class) -@Conditional({ CacheCondition.class, - JCacheCacheConfiguration.JCacheAvailableCondition.class }) +@Conditional({ CacheCondition.class, JCacheCacheConfiguration.JCacheAvailableCondition.class }) @Import(HazelcastJCacheCustomizationConfiguration.class) class JCacheCacheConfiguration implements BeanClassLoaderAware { @@ -71,8 +70,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { } @Bean - public JCacheCacheManager cacheManager(CacheManagerCustomizers customizers, - CacheManager jCacheCacheManager) { + public JCacheCacheManager cacheManager(CacheManagerCustomizers customizers, CacheManager jCacheCacheManager) { JCacheCacheManager cacheManager = new JCacheCacheManager(jCacheCacheManager); return customizers.customize(cacheManager); } @@ -82,34 +80,26 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { public CacheManager jCacheCacheManager(CacheProperties cacheProperties, ObjectProvider> defaultCacheConfiguration, ObjectProvider cacheManagerCustomizers, - ObjectProvider cachePropertiesCustomizers) - throws IOException { - CacheManager jCacheCacheManager = createCacheManager(cacheProperties, - cachePropertiesCustomizers); + ObjectProvider cachePropertiesCustomizers) throws IOException { + CacheManager jCacheCacheManager = createCacheManager(cacheProperties, cachePropertiesCustomizers); List cacheNames = cacheProperties.getCacheNames(); if (!CollectionUtils.isEmpty(cacheNames)) { for (String cacheName : cacheNames) { - jCacheCacheManager.createCache(cacheName, defaultCacheConfiguration - .getIfAvailable(MutableConfiguration::new)); + jCacheCacheManager.createCache(cacheName, + defaultCacheConfiguration.getIfAvailable(MutableConfiguration::new)); } } - cacheManagerCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(jCacheCacheManager)); + cacheManagerCustomizers.orderedStream().forEach((customizer) -> customizer.customize(jCacheCacheManager)); return jCacheCacheManager; } private CacheManager createCacheManager(CacheProperties cacheProperties, - ObjectProvider cachePropertiesCustomizers) - throws IOException { - CachingProvider cachingProvider = getCachingProvider( - cacheProperties.getJcache().getProvider()); - Properties properties = createCacheManagerProperties(cachePropertiesCustomizers, - cacheProperties); - Resource configLocation = cacheProperties - .resolveConfigLocation(cacheProperties.getJcache().getConfig()); + ObjectProvider cachePropertiesCustomizers) throws IOException { + CachingProvider cachingProvider = getCachingProvider(cacheProperties.getJcache().getProvider()); + Properties properties = createCacheManagerProperties(cachePropertiesCustomizers, cacheProperties); + Resource configLocation = cacheProperties.resolveConfigLocation(cacheProperties.getJcache().getConfig()); if (configLocation != null) { - return cachingProvider.getCacheManager(configLocation.getURI(), - this.beanClassLoader, properties); + return cachingProvider.getCacheManager(configLocation.getURI(), this.beanClassLoader, properties); } return cachingProvider.getCacheManager(null, this.beanClassLoader, properties); } @@ -122,11 +112,10 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { } private Properties createCacheManagerProperties( - ObjectProvider cachePropertiesCustomizers, - CacheProperties cacheProperties) { + ObjectProvider cachePropertiesCustomizers, CacheProperties cacheProperties) { Properties properties = new Properties(); - cachePropertiesCustomizers.orderedStream().forEach( - (customizer) -> customizer.customize(cacheProperties, properties)); + cachePropertiesCustomizers.orderedStream() + .forEach((customizer) -> customizer.customize(cacheProperties, properties)); return properties; } @@ -163,28 +152,22 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { static class JCacheProviderAvailableCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("JCache"); String providerProperty = "spring.cache.jcache.provider"; if (context.getEnvironment().containsProperty(providerProperty)) { - return ConditionOutcome - .match(message.because("JCache provider specified")); + return ConditionOutcome.match(message.because("JCache provider specified")); } - Iterator providers = Caching.getCachingProviders() - .iterator(); + Iterator providers = Caching.getCachingProviders().iterator(); if (!providers.hasNext()) { - return ConditionOutcome - .noMatch(message.didNotFind("JSR-107 provider").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("JSR-107 provider").atAll()); } providers.next(); if (providers.hasNext()) { - return ConditionOutcome - .noMatch(message.foundExactly("multiple JSR-107 providers")); + return ConditionOutcome.noMatch(message.foundExactly("multiple JSR-107 providers")); } - return ConditionOutcome - .match(message.foundExactly("single JSR-107 provider")); + return ConditionOutcome.match(message.foundExactly("single JSR-107 provider")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java index f06b0e9d331..545d5133566 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java @@ -57,12 +57,9 @@ class RedisCacheConfiguration { public RedisCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers cacheManagerCustomizers, ObjectProvider redisCacheConfiguration, - RedisConnectionFactory redisConnectionFactory, - ResourceLoader resourceLoader) { - RedisCacheManagerBuilder builder = RedisCacheManager - .builder(redisConnectionFactory) - .cacheDefaults(determineConfiguration(cacheProperties, - redisCacheConfiguration, resourceLoader.getClassLoader())); + RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { + RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults( + determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader())); List cacheNames = cacheProperties.getCacheNames(); if (!cacheNames.isEmpty()) { builder.initialCacheNames(new LinkedHashSet<>(cacheNames)); @@ -74,8 +71,7 @@ class RedisCacheConfiguration { CacheProperties cacheProperties, ObjectProvider redisCacheConfiguration, ClassLoader classLoader) { - return redisCacheConfiguration - .getIfAvailable(() -> createConfiguration(cacheProperties, classLoader)); + return redisCacheConfiguration.getIfAvailable(() -> createConfiguration(cacheProperties, classLoader)); } @@ -84,8 +80,8 @@ class RedisCacheConfiguration { Redis redisProperties = cacheProperties.getRedis(); org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration .defaultCacheConfig(); - config = config.serializeValuesWith(SerializationPair - .fromSerializer(new JdkSerializationRedisSerializer(classLoader))); + config = config.serializeValuesWith( + SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader))); if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java index 4b593cb2504..d5361b55767 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java @@ -54,11 +54,10 @@ public class CassandraAutoConfiguration { ObjectProvider builderCustomizers, ObjectProvider clusterFactory) { PropertyMapper map = PropertyMapper.get(); - Cluster.Builder builder = Cluster.builder() - .withClusterName(properties.getClusterName()) + Cluster.Builder builder = Cluster.builder().withClusterName(properties.getClusterName()) .withPort(properties.getPort()); - map.from(properties::getUsername).whenNonNull().to((username) -> builder - .withCredentials(username, properties.getPassword())); + map.from(properties::getUsername).whenNonNull() + .to((username) -> builder.withCredentials(username, properties.getPassword())); map.from(properties::getCompression).whenNonNull().to(builder::withCompression); QueryOptions queryOptions = getQueryOptions(properties); map.from(queryOptions).to(builder::withQueryOptions); @@ -67,22 +66,17 @@ public class CassandraAutoConfiguration { map.from(properties::isSsl).whenTrue().toCall(builder::withSSL); PoolingOptions poolingOptions = getPoolingOptions(properties); map.from(poolingOptions).to(builder::withPoolingOptions); - map.from(properties::getContactPoints).as(StringUtils::toStringArray) - .to(builder::addContactPoints); - map.from(properties::isJmxEnabled).whenFalse() - .toCall(builder::withoutJMXReporting); - builderCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + map.from(properties::getContactPoints).as(StringUtils::toStringArray).to(builder::addContactPoints); + map.from(properties::isJmxEnabled).whenFalse().toCall(builder::withoutJMXReporting); + builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return clusterFactory.getIfAvailable(() -> Cluster::buildFrom).create(builder); } private QueryOptions getQueryOptions(CassandraProperties properties) { PropertyMapper map = PropertyMapper.get(); QueryOptions options = new QueryOptions(); - map.from(properties::getConsistencyLevel).whenNonNull() - .to(options::setConsistencyLevel); - map.from(properties::getSerialConsistencyLevel).whenNonNull() - .to(options::setSerialConsistencyLevel); + map.from(properties::getConsistencyLevel).whenNonNull().to(options::setConsistencyLevel); + map.from(properties::getSerialConsistencyLevel).whenNonNull().to(options::setSerialConsistencyLevel); map.from(properties::getFetchSize).to(options::setFetchSize); return options; } @@ -92,8 +86,7 @@ public class CassandraAutoConfiguration { SocketOptions options = new SocketOptions(); map.from(properties::getConnectTimeout).whenNonNull().asInt(Duration::toMillis) .to(options::setConnectTimeoutMillis); - map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) - .to(options::setReadTimeoutMillis); + map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis).to(options::setReadTimeoutMillis); return options; } @@ -105,8 +98,8 @@ public class CassandraAutoConfiguration { .to(options::setIdleTimeoutSeconds); map.from(poolProperties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis) .to(options::setPoolTimeoutMillis); - map.from(poolProperties::getHeartbeatInterval).whenNonNull() - .asInt(Duration::getSeconds).to(options::setHeartbeatIntervalSeconds); + map.from(poolProperties::getHeartbeatInterval).whenNonNull().asInt(Duration::getSeconds) + .to(options::setHeartbeatIntervalSeconds); map.from(poolProperties::getMaxQueueSize).to(options::setMaxQueueSize); return options; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java index c91b574cafb..47d5cdef637 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java @@ -55,8 +55,7 @@ public class CassandraProperties { /** * Cluster node addresses. */ - private final List contactPoints = new ArrayList<>( - Collections.singleton("localhost")); + private final List contactPoints = new ArrayList<>(Collections.singleton("localhost")); /** * Port of the Cassandra server. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java index 32f673e0199..76f908c8494 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ import org.springframework.util.MultiValueMap; * @author Phillip Webb * @since 2.0.1 */ -public abstract class AbstractNestedCondition extends SpringBootCondition - implements ConfigurationCondition { +public abstract class AbstractNestedCondition extends SpringBootCondition implements ConfigurationCondition { private final ConfigurationPhase configurationPhase; @@ -58,17 +57,14 @@ public abstract class AbstractNestedCondition extends SpringBootCondition } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String className = getClass().getName(); - MemberConditions memberConditions = new MemberConditions(context, - this.configurationPhase, className); + MemberConditions memberConditions = new MemberConditions(context, this.configurationPhase, className); MemberMatchOutcomes memberOutcomes = new MemberMatchOutcomes(memberConditions); return getFinalMatchOutcome(memberOutcomes); } - protected abstract ConditionOutcome getFinalMatchOutcome( - MemberMatchOutcomes memberOutcomes); + protected abstract ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes); protected static class MemberMatchOutcomes { @@ -111,17 +107,15 @@ public abstract class AbstractNestedCondition extends SpringBootCondition private final Map> memberConditions; - MemberConditions(ConditionContext context, ConfigurationPhase phase, - String className) { + MemberConditions(ConditionContext context, ConfigurationPhase phase, String className) { this.context = context; - this.readerFactory = new SimpleMetadataReaderFactory( - context.getResourceLoader()); + this.readerFactory = new SimpleMetadataReaderFactory(context.getResourceLoader()); String[] members = getMetadata(className).getMemberClassNames(); this.memberConditions = getMemberConditions(members, phase, className); } - private Map> getMemberConditions( - String[] members, ConfigurationPhase phase, String className) { + private Map> getMemberConditions(String[] members, ConfigurationPhase phase, + String className) { MultiValueMap memberConditions = new LinkedMultiValueMap<>(); for (String member : members) { AnnotationMetadata metadata = getMetadata(member); @@ -136,15 +130,12 @@ public abstract class AbstractNestedCondition extends SpringBootCondition return Collections.unmodifiableMap(memberConditions); } - private void validateMemberCondition(Condition condition, - ConfigurationPhase nestedPhase, String nestedClassName) { - if (nestedPhase == ConfigurationPhase.PARSE_CONFIGURATION - && condition instanceof ConfigurationCondition) { - ConfigurationPhase memberPhase = ((ConfigurationCondition) condition) - .getConfigurationPhase(); + private void validateMemberCondition(Condition condition, ConfigurationPhase nestedPhase, + String nestedClassName) { + if (nestedPhase == ConfigurationPhase.PARSE_CONFIGURATION && condition instanceof ConfigurationCondition) { + ConfigurationPhase memberPhase = ((ConfigurationCondition) condition).getConfigurationPhase(); if (memberPhase == ConfigurationPhase.REGISTER_BEAN) { - throw new IllegalStateException("Nested condition " + nestedClassName - + " uses a configuration " + throw new IllegalStateException("Nested condition " + nestedClassName + " uses a configuration " + "phase that is inappropriate for " + condition.getClass()); } } @@ -152,8 +143,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition private AnnotationMetadata getMetadata(String className) { try { - return this.readerFactory.getMetadataReader(className) - .getAnnotationMetadata(); + return this.readerFactory.getMetadataReader(className).getAnnotationMetadata(); } catch (IOException ex) { throw new IllegalStateException(ex); @@ -162,23 +152,21 @@ public abstract class AbstractNestedCondition extends SpringBootCondition @SuppressWarnings("unchecked") private List getConditionClasses(AnnotatedTypeMetadata metadata) { - MultiValueMap attributes = metadata - .getAllAnnotationAttributes(Conditional.class.getName(), true); + MultiValueMap attributes = metadata.getAllAnnotationAttributes(Conditional.class.getName(), + true); Object values = (attributes != null) ? attributes.get("value") : null; return (List) ((values != null) ? values : Collections.emptyList()); } private Condition getCondition(String conditionClassName) { - Class conditionClass = ClassUtils.resolveClassName(conditionClassName, - this.context.getClassLoader()); + Class conditionClass = ClassUtils.resolveClassName(conditionClassName, this.context.getClassLoader()); return (Condition) BeanUtils.instantiateClass(conditionClass); } public List getMatchOutcomes() { List outcomes = new ArrayList<>(); this.memberConditions.forEach((metadata, conditions) -> outcomes - .add(new MemberOutcomes(this.context, metadata, conditions) - .getUltimateOutcome())); + .add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome())); return Collections.unmodifiableList(outcomes); } @@ -192,8 +180,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition private final List outcomes; - MemberOutcomes(ConditionContext context, AnnotationMetadata metadata, - List conditions) { + MemberOutcomes(ConditionContext context, AnnotationMetadata metadata, List conditions) { this.context = context; this.metadata = metadata; this.outcomes = new ArrayList<>(conditions.size()); @@ -202,24 +189,19 @@ public abstract class AbstractNestedCondition extends SpringBootCondition } } - private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata, - Condition condition) { + private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata, Condition condition) { if (condition instanceof SpringBootCondition) { - return ((SpringBootCondition) condition).getMatchOutcome(this.context, - metadata); + return ((SpringBootCondition) condition).getMatchOutcome(this.context, metadata); } - return new ConditionOutcome(condition.matches(this.context, metadata), - ConditionMessage.empty()); + return new ConditionOutcome(condition.matches(this.context, metadata), ConditionMessage.empty()); } public ConditionOutcome getUltimateOutcome() { ConditionMessage.Builder message = ConditionMessage - .forCondition("NestedCondition on " - + ClassUtils.getShortName(this.metadata.getClassName())); + .forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName())); if (this.outcomes.size() == 1) { ConditionOutcome outcome = this.outcomes.get(0); - return new ConditionOutcome(outcome.isMatch(), - message.because(outcome.getMessage())); + return new ConditionOutcome(outcome.isMatch(), message.because(outcome.getMessage())); } List match = new ArrayList<>(); List nonMatch = new ArrayList<>(); @@ -227,11 +209,9 @@ public abstract class AbstractNestedCondition extends SpringBootCondition (outcome.isMatch() ? match : nonMatch).add(outcome); } if (nonMatch.isEmpty()) { - return ConditionOutcome - .match(message.found("matching nested conditions").items(match)); + return ConditionOutcome.match(message.found("matching nested conditions").items(match)); } - return ConditionOutcome.noMatch( - message.found("non-matching nested conditions").items(nonMatch)); + return ConditionOutcome.noMatch(message.found("non-matching nested conditions").items(nonMatch)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java index 98ce303f6eb..58ae16d2766 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,9 +62,8 @@ public abstract class AllNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = hasSameSize(memberOutcomes.getMatches(), memberOutcomes.getAll()); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("AllNestedConditions") - .because(memberOutcomes.getMatches().size() + " matched " - + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AllNestedConditions").because( + memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java index db9c801f5d6..ede56389ad1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,9 +65,8 @@ public abstract class AnyNestedCondition extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = !memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("AnyNestedCondition") - .because(memberOutcomes.getMatches().size() + " matched " - + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AnyNestedCondition").because( + memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java index e86fd927137..0eab9a144da 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java @@ -118,11 +118,9 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { updateTypesIfNecessary(); return this.beanTypes.entrySet().stream() .filter((entry) -> entry.getValue() != null && MergedAnnotations - .from(entry.getValue().resolve(), - MergedAnnotations.SearchStrategy.EXHAUSTIVE) + .from(entry.getValue().resolve(), MergedAnnotations.SearchStrategy.EXHAUSTIVE) .isPresent(annotation)) - .map(Map.Entry::getKey) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new)); } @Override @@ -133,8 +131,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } private void updateTypesIfNecessary() { - this.beanFactory.getBeanNamesIterator() - .forEachRemaining(this::updateTypesIfNecessary); + this.beanFactory.getBeanNamesIterator().forEachRemaining(this::updateTypesIfNecessary); } private void updateTypesIfNecessary(String name) { @@ -186,20 +183,16 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } } - private void addBeanTypeForNonAliasDefinition(String name, - RootBeanDefinition definition) { + private void addBeanTypeForNonAliasDefinition(String name, RootBeanDefinition definition) { try { - if (!definition.isAbstract() - && !requiresEagerInit(definition.getFactoryBeanName())) { - ResolvableType factoryMethodReturnType = getFactoryMethodReturnType( - definition); + if (!definition.isAbstract() && !requiresEagerInit(definition.getFactoryBeanName())) { + ResolvableType factoryMethodReturnType = getFactoryMethodReturnType(definition); String factoryBeanName = BeanFactory.FACTORY_BEAN_PREFIX + name; if (this.beanFactory.isFactoryBean(factoryBeanName)) { - ResolvableType factoryBeanGeneric = getFactoryBeanGeneric( - this.beanFactory, definition, factoryMethodReturnType); + ResolvableType factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, definition, + factoryMethodReturnType); this.beanTypes.put(name, factoryBeanGeneric); - this.beanTypes.put(factoryBeanName, - getType(factoryBeanName, factoryMethodReturnType)); + this.beanTypes.put(factoryBeanName, getType(factoryBeanName, factoryMethodReturnType)); } else { this.beanTypes.put(name, getType(name, factoryMethodReturnType)); @@ -223,8 +216,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { if (StringUtils.hasLength(definition.getFactoryBeanName()) && StringUtils.hasLength(definition.getFactoryMethodName())) { Method method = getFactoryMethod(this.beanFactory, definition); - ResolvableType type = (method != null) - ? ResolvableType.forMethodReturnType(method) : null; + ResolvableType type = (method != null) ? ResolvableType.forMethodReturnType(method) : null; return type; } } @@ -233,18 +225,15 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return null; } - private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, - BeanDefinition definition) throws Exception { + private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) + throws Exception { if (definition instanceof AnnotatedBeanDefinition) { - MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition) - .getFactoryMethodMetadata(); + MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata(); if (factoryMethodMetadata instanceof StandardMethodMetadata) { - return ((StandardMethodMetadata) factoryMethodMetadata) - .getIntrospectedMethod(); + return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod(); } } - BeanDefinition factoryDefinition = beanFactory - .getBeanDefinition(definition.getFactoryBeanName()); + BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName()); Class factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(), beanFactory.getBeanClassLoader()); return getFactoryMethod(definition, factoryClass); @@ -265,10 +254,8 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return uniqueMethod; } - private Method[] getCandidateFactoryMethods(BeanDefinition definition, - Class factoryClass) { - return (shouldConsiderNonPublicMethods(definition) - ? ReflectionUtils.getAllDeclaredMethods(factoryClass) + private Method[] getCandidateFactoryMethods(BeanDefinition definition, Class factoryClass) { + return (shouldConsiderNonPublicMethods(definition) ? ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()); } @@ -295,8 +282,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { * @param factoryMethodReturnType the factory method return type * @return the generic type of the {@link FactoryBean} or {@code null} */ - private ResolvableType getFactoryBeanGeneric( - ConfigurableListableBeanFactory beanFactory, BeanDefinition definition, + private ResolvableType getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition, ResolvableType factoryMethodReturnType) { try { if (factoryMethodReturnType != null) { @@ -311,27 +297,23 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return null; } - private ResolvableType getDirectFactoryBeanGeneric( - ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) - throws ClassNotFoundException, LinkageError { - Class factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), - beanFactory.getBeanClassLoader()); + private ResolvableType getDirectFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, + BeanDefinition definition) throws ClassNotFoundException, LinkageError { + Class factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader()); return getFactoryBeanType(definition, ResolvableType.forClass(factoryBeanClass)); } - private ResolvableType getFactoryBeanType(BeanDefinition definition, - ResolvableType type) throws ClassNotFoundException, LinkageError { + private ResolvableType getFactoryBeanType(BeanDefinition definition, ResolvableType type) + throws ClassNotFoundException, LinkageError { ResolvableType generic = type.as(FactoryBean.class).getGeneric(); if ((generic == null || generic.resolve().equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { - generic = getTypeFromAttribute( - definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); + generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; } - private ResolvableType getTypeFromAttribute(Object attribute) - throws ClassNotFoundException, LinkageError { + private ResolvableType getTypeFromAttribute(Object attribute) throws ClassNotFoundException, LinkageError { if (attribute instanceof Class) { return ResolvableType.forClass((Class) attribute); } @@ -342,8 +324,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } private ResolvableType getType(String name, ResolvableType factoryMethodReturnType) { - if (factoryMethodReturnType != null - && !factoryMethodReturnType.resolve(Object.class).equals(Object.class)) { + if (factoryMethodReturnType != null && !factoryMethodReturnType.resolve(Object.class).equals(Object.class)) { return factoryMethodReturnType; } Class type = this.beanFactory.getType(name); @@ -358,14 +339,10 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { static BeanTypeRegistry get(ListableBeanFactory beanFactory) { Assert.isInstanceOf(DefaultListableBeanFactory.class, beanFactory); DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) beanFactory; - Assert.isTrue(listableBeanFactory.isAllowEagerClassLoading(), - "Bean factory must allow eager class loading"); + Assert.isTrue(listableBeanFactory.isAllowEagerClassLoading(), "Bean factory must allow eager class loading"); if (!listableBeanFactory.containsLocalBean(BEAN_NAME)) { - BeanDefinition definition = BeanDefinitionBuilder - .genericBeanDefinition(BeanTypeRegistry.class, - () -> new BeanTypeRegistry( - (DefaultListableBeanFactory) beanFactory)) - .getBeanDefinition(); + BeanDefinition definition = BeanDefinitionBuilder.genericBeanDefinition(BeanTypeRegistry.class, + () -> new BeanTypeRegistry((DefaultListableBeanFactory) beanFactory)).getBeanDefinition(); listableBeanFactory.registerBeanDefinition(BEAN_NAME, definition); } return listableBeanFactory.getBean(BEAN_NAME, BeanTypeRegistry.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java index 1d6f8e393be..14bb5e099c3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,8 +75,7 @@ public final class ConditionEvaluationReport { * @param condition the condition evaluated * @param outcome the condition outcome */ - public void recordConditionEvaluation(String source, Condition condition, - ConditionOutcome outcome) { + public void recordConditionEvaluation(String source, Condition condition, ConditionOutcome outcome) { Assert.notNull(source, "Source must not be null"); Assert.notNull(condition, "Condition must not be null"); Assert.notNull(outcome, "Outcome must not be null"); @@ -127,8 +126,8 @@ public final class ConditionEvaluationReport { String prefix = source + "$"; this.outcomes.forEach((candidateSource, sourceOutcomes) -> { if (candidateSource.startsWith(prefix)) { - ConditionOutcome outcome = ConditionOutcome.noMatch(ConditionMessage - .forCondition("Ancestor " + source).because("did not match")); + ConditionOutcome outcome = ConditionOutcome + .noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match")); sourceOutcomes.add(ANCESTOR_CONDITION, outcome); } }); @@ -168,8 +167,7 @@ public final class ConditionEvaluationReport { */ public static ConditionEvaluationReport find(BeanFactory beanFactory) { if (beanFactory != null && beanFactory instanceof ConfigurableBeanFactory) { - return ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) beanFactory); + return ConditionEvaluationReport.get((ConfigurableListableBeanFactory) beanFactory); } return null; } @@ -179,8 +177,7 @@ public final class ConditionEvaluationReport { * @param beanFactory the bean factory * @return an existing or new {@link ConditionEvaluationReport} */ - public static ConditionEvaluationReport get( - ConfigurableListableBeanFactory beanFactory) { + public static ConditionEvaluationReport get(ConfigurableListableBeanFactory beanFactory) { synchronized (beanFactory) { ConditionEvaluationReport report; if (beanFactory.containsSingleton(BEAN_NAME)) { @@ -195,12 +192,9 @@ public final class ConditionEvaluationReport { } } - private static void locateParent(BeanFactory beanFactory, - ConditionEvaluationReport report) { - if (beanFactory != null && report.parent == null - && beanFactory.containsBean(BEAN_NAME)) { - report.parent = beanFactory.getBean(BEAN_NAME, - ConditionEvaluationReport.class); + private static void locateParent(BeanFactory beanFactory, ConditionEvaluationReport report) { + if (beanFactory != null && report.parent == null && beanFactory.containsBean(BEAN_NAME)) { + report.parent = beanFactory.getBean(BEAN_NAME, ConditionEvaluationReport.class); } } @@ -208,12 +202,9 @@ public final class ConditionEvaluationReport { ConditionEvaluationReport delta = new ConditionEvaluationReport(); this.outcomes.forEach((source, sourceOutcomes) -> { ConditionAndOutcomes previous = previousReport.outcomes.get(source); - if (previous == null - || previous.isFullMatch() != sourceOutcomes.isFullMatch()) { - sourceOutcomes.forEach( - (conditionAndOutcome) -> delta.recordConditionEvaluation(source, - conditionAndOutcome.getCondition(), - conditionAndOutcome.getOutcome())); + if (previous == null || previous.isFullMatch() != sourceOutcomes.isFullMatch()) { + sourceOutcomes.forEach((conditionAndOutcome) -> delta.recordConditionEvaluation(source, + conditionAndOutcome.getCondition(), conditionAndOutcome.getOutcome())); } }); List newExclusions = new ArrayList<>(this.exclusions); @@ -287,8 +278,7 @@ public final class ConditionEvaluationReport { return false; } ConditionAndOutcome other = (ConditionAndOutcome) obj; - return (ObjectUtils.nullSafeEquals(this.condition.getClass(), - other.condition.getClass()) + return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass()) && ObjectUtils.nullSafeEquals(this.outcome, other.outcome)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java index 54d8dcee2cb..4d29ea93565 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ class ConditionEvaluationReportAutoConfigurationImportListener @Override public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) { if (this.beanFactory != null) { - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); report.recordEvaluationCandidates(event.getCandidateConfigurations()); report.recordExclusions(event.getExclusions()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java index 04e5652f793..400f93d7785 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java @@ -106,8 +106,7 @@ public final class ConditionMessage { * @see #andCondition(String, Object...) * @see #forCondition(Class, Object...) */ - public Builder andCondition(Class condition, - Object... details) { + public Builder andCondition(Class condition, Object... details) { Assert.notNull(condition, "Condition must not be null"); return andCondition("@" + ClassUtils.getShortName(condition), details); } @@ -177,8 +176,7 @@ public final class ConditionMessage { * @see #forCondition(String, Object...) * @see #andCondition(String, Object...) */ - public static Builder forCondition(Class condition, - Object... details) { + public static Builder forCondition(Class condition, Object... details) { return new ConditionMessage().andCondition(condition, details); } @@ -301,8 +299,8 @@ public final class ConditionMessage { if (StringUtils.isEmpty(reason)) { return new ConditionMessage(ConditionMessage.this, this.condition); } - return new ConditionMessage(ConditionMessage.this, this.condition - + (StringUtils.isEmpty(this.condition) ? "" : " ") + reason); + return new ConditionMessage(ConditionMessage.this, + this.condition + (StringUtils.isEmpty(this.condition) ? "" : " ") + reason); } } @@ -320,8 +318,7 @@ public final class ConditionMessage { private final String plural; - private ItemsBuilder(Builder condition, String reason, String singular, - String plural) { + private ItemsBuilder(Builder condition, String reason, String singular, String plural) { this.condition = condition; this.reason = reason; this.singular = singular; @@ -384,16 +381,14 @@ public final class ConditionMessage { Assert.notNull(style, "Style must not be null"); StringBuilder message = new StringBuilder(this.reason); items = style.applyTo(items); - if ((this.condition == null || items.size() <= 1) - && StringUtils.hasLength(this.singular)) { + if ((this.condition == null || items.size() <= 1) && StringUtils.hasLength(this.singular)) { message.append(" ").append(this.singular); } else if (StringUtils.hasLength(this.plural)) { message.append(" ").append(this.plural); } if (items != null && !items.isEmpty()) { - message.append(" ") - .append(StringUtils.collectionToDelimitedString(items, ", ")); + message.append(" ").append(StringUtils.collectionToDelimitedString(items, ", ")); } return this.condition.because(message.toString()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java index e28faab9d28..c8babd84cfe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,16 +132,14 @@ public class ConditionOutcome { } if (getClass() == obj.getClass()) { ConditionOutcome other = (ConditionOutcome) obj; - return (this.match == other.match - && ObjectUtils.nullSafeEquals(this.message, other.message)); + return (this.match == other.match && ObjectUtils.nullSafeEquals(this.message, other.message)); } return super.equals(obj); } @Override public int hashCode() { - return Boolean.hashCode(this.match) * 31 - + ObjectUtils.nullSafeHashCode(this.message); + return Boolean.hashCode(this.match) * 31 + ObjectUtils.nullSafeHashCode(this.message); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/FilteringSpringBootCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/FilteringSpringBootCondition.java index 8ed415ec7dd..1f440e8d6a2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/FilteringSpringBootCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/FilteringSpringBootCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,20 +44,16 @@ abstract class FilteringSpringBootCondition extends SpringBootCondition private ClassLoader beanClassLoader; @Override - public boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata) { - ConditionEvaluationReport report = ConditionEvaluationReport - .find(this.beanFactory); - ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, - autoConfigurationMetadata); + public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { + ConditionEvaluationReport report = ConditionEvaluationReport.find(this.beanFactory); + ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, autoConfigurationMetadata); boolean[] match = new boolean[outcomes.length]; for (int i = 0; i < outcomes.length; i++) { match[i] = (outcomes[i] == null || outcomes[i].isMatch()); if (!match[i] && outcomes[i] != null) { logOutcome(autoConfigurationClasses[i], outcomes[i]); if (report != null) { - report.recordConditionEvaluation(autoConfigurationClasses[i], this, - outcomes[i]); + report.recordConditionEvaluation(autoConfigurationClasses[i], this, outcomes[i]); } } } @@ -85,8 +81,8 @@ abstract class FilteringSpringBootCondition extends SpringBootCondition this.beanClassLoader = classLoader; } - protected List filter(Collection classNames, - ClassNameFilter classNameFilter, ClassLoader classLoader) { + protected List filter(Collection classNames, ClassNameFilter classNameFilter, + ClassLoader classLoader) { if (CollectionUtils.isEmpty(classNames)) { return Collections.emptyList(); } @@ -134,8 +130,7 @@ abstract class FilteringSpringBootCondition extends SpringBootCondition } } - private static Class forName(String className, ClassLoader classLoader) - throws ClassNotFoundException { + private static Class forName(String className, ClassLoader classLoader) throws ClassNotFoundException { if (classLoader != null) { return classLoader.loadClass(className); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java index 7a54cf3faf0..ac03c5aa66b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,9 +62,8 @@ public abstract class NoneNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("NoneNestedConditions") - .because(memberOutcomes.getMatches().size() + " matched " - + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("NoneNestedConditions").because( + memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java index 7411bebb4f8..2647b40d799 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java @@ -67,8 +67,7 @@ import org.springframework.util.StringUtils; * @see ConditionalOnSingleCandidate */ @Order(Ordered.LOWEST_PRECEDENCE) -class OnBeanCondition extends FilteringSpringBootCondition - implements ConfigurationCondition { +class OnBeanCondition extends FilteringSpringBootCondition implements ConfigurationCondition { /** * Bean definition attribute name for factory beans to signal their product type (if @@ -88,48 +87,40 @@ class OnBeanCondition extends FilteringSpringBootCondition for (int i = 0; i < outcomes.length; i++) { String autoConfigurationClass = autoConfigurationClasses[i]; if (autoConfigurationClass != null) { - Set onBeanTypes = autoConfigurationMetadata - .getSet(autoConfigurationClass, "ConditionalOnBean"); + Set onBeanTypes = autoConfigurationMetadata.getSet(autoConfigurationClass, "ConditionalOnBean"); outcomes[i] = getOutcome(onBeanTypes, ConditionalOnBean.class); if (outcomes[i] == null) { - Set onSingleCandidateTypes = autoConfigurationMetadata.getSet( - autoConfigurationClass, "ConditionalOnSingleCandidate"); - outcomes[i] = getOutcome(onSingleCandidateTypes, - ConditionalOnSingleCandidate.class); + Set onSingleCandidateTypes = autoConfigurationMetadata.getSet(autoConfigurationClass, + "ConditionalOnSingleCandidate"); + outcomes[i] = getOutcome(onSingleCandidateTypes, ConditionalOnSingleCandidate.class); } } } return outcomes; } - private ConditionOutcome getOutcome(Set requiredBeanTypes, - Class annotation) { - List missing = filter(requiredBeanTypes, ClassNameFilter.MISSING, - getBeanClassLoader()); + private ConditionOutcome getOutcome(Set requiredBeanTypes, Class annotation) { + List missing = filter(requiredBeanTypes, ClassNameFilter.MISSING, getBeanClassLoader()); if (!missing.isEmpty()) { ConditionMessage message = ConditionMessage.forCondition(annotation) - .didNotFind("required type", "required types") - .items(Style.QUOTE, missing); + .didNotFind("required type", "required types").items(Style.QUOTE, missing); return ConditionOutcome.noMatch(message); } return null; } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage matchMessage = ConditionMessage.empty(); if (metadata.isAnnotated(ConditionalOnBean.class.getName())) { - BeanSearchSpec spec = new BeanSearchSpec(context, metadata, - ConditionalOnBean.class); + BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnBean.class); MatchResult matchResult = getMatchingBeans(context, spec); if (!matchResult.isAllMatched()) { String reason = createOnBeanNoMatchReason(matchResult); - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnBean.class, spec).because(reason)); + return ConditionOutcome + .noMatch(ConditionMessage.forCondition(ConditionalOnBean.class, spec).because(reason)); } - matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec) - .found("bean", "beans") + matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec).found("bean", "beans") .items(Style.QUOTE, matchResult.getNamesOfAllMatches()); } if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) { @@ -137,57 +128,47 @@ class OnBeanCondition extends FilteringSpringBootCondition ConditionalOnSingleCandidate.class); MatchResult matchResult = getMatchingBeans(context, spec); if (!matchResult.isAllMatched()) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnSingleCandidate.class, spec) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec) .didNotFind("any beans").atAll()); } - else if (!hasSingleAutowireCandidate(context.getBeanFactory(), - matchResult.getNamesOfAllMatches(), + else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matchResult.getNamesOfAllMatches(), spec.getStrategy() == SearchStrategy.ALL)) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnSingleCandidate.class, spec) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec) .didNotFind("a primary bean from beans") .items(Style.QUOTE, matchResult.getNamesOfAllMatches())); } - matchMessage = matchMessage - .andCondition(ConditionalOnSingleCandidate.class, spec) - .found("a primary bean from beans") - .items(Style.QUOTE, matchResult.getNamesOfAllMatches()); + matchMessage = matchMessage.andCondition(ConditionalOnSingleCandidate.class, spec) + .found("a primary bean from beans").items(Style.QUOTE, matchResult.getNamesOfAllMatches()); } if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) { - BeanSearchSpec spec = new BeanSearchSpec(context, metadata, - ConditionalOnMissingBean.class); + BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnMissingBean.class); MatchResult matchResult = getMatchingBeans(context, spec); if (matchResult.isAnyMatched()) { String reason = createOnMissingBeanNoMatchReason(matchResult); - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnMissingBean.class, spec) - .because(reason)); + return ConditionOutcome + .noMatch(ConditionMessage.forCondition(ConditionalOnMissingBean.class, spec).because(reason)); } - matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec) - .didNotFind("any beans").atAll(); + matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec).didNotFind("any beans") + .atAll(); } return ConditionOutcome.match(matchMessage); } - protected final MatchResult getMatchingBeans(ConditionContext context, - BeanSearchSpec beans) { + protected final MatchResult getMatchingBeans(ConditionContext context, BeanSearchSpec beans) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); if (beans.getStrategy() == SearchStrategy.ANCESTORS) { BeanFactory parent = beanFactory.getParentBeanFactory(); - Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent, - "Unable to use SearchStrategy.PARENTS"); + Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent, "Unable to use SearchStrategy.PARENTS"); beanFactory = (ConfigurableListableBeanFactory) parent; } MatchResult matchResult = new MatchResult(); boolean considerHierarchy = beans.getStrategy() != SearchStrategy.CURRENT; TypeExtractor typeExtractor = beans.getTypeExtractor(context.getClassLoader()); - List beansIgnoredByType = getNamesOfBeansIgnoredByType( - beans.getIgnoredTypes(), typeExtractor, beanFactory, context, - considerHierarchy); + List beansIgnoredByType = getNamesOfBeansIgnoredByType(beans.getIgnoredTypes(), typeExtractor, + beanFactory, context, considerHierarchy); for (String type : beans.getTypes()) { - Collection typeMatches = getBeanNamesForType(beanFactory, type, - typeExtractor, context.getClassLoader(), considerHierarchy); + Collection typeMatches = getBeanNamesForType(beanFactory, type, typeExtractor, + context.getClassLoader(), considerHierarchy); typeMatches.removeAll(beansIgnoredByType); if (typeMatches.isEmpty()) { matchResult.recordUnmatchedType(type); @@ -197,9 +178,8 @@ class OnBeanCondition extends FilteringSpringBootCondition } } for (String annotation : beans.getAnnotations()) { - List annotationMatches = Arrays - .asList(getBeanNamesForAnnotation(beanFactory, annotation, - context.getClassLoader(), considerHierarchy)); + List annotationMatches = Arrays.asList( + getBeanNamesForAnnotation(beanFactory, annotation, context.getClassLoader(), considerHierarchy)); annotationMatches.removeAll(beansIgnoredByType); if (annotationMatches.isEmpty()) { matchResult.recordUnmatchedAnnotation(annotation); @@ -209,8 +189,7 @@ class OnBeanCondition extends FilteringSpringBootCondition } } for (String beanName : beans.getNames()) { - if (!beansIgnoredByType.contains(beanName) - && containsBean(beanFactory, beanName, considerHierarchy)) { + if (!beansIgnoredByType.contains(beanName) && containsBean(beanFactory, beanName, considerHierarchy)) { matchResult.recordMatchedName(beanName); } else { @@ -220,16 +199,14 @@ class OnBeanCondition extends FilteringSpringBootCondition return matchResult; } - private String[] getBeanNamesForAnnotation( - ConfigurableListableBeanFactory beanFactory, String type, + private String[] getBeanNamesForAnnotation(ConfigurableListableBeanFactory beanFactory, String type, ClassLoader classLoader, boolean considerHierarchy) throws LinkageError { Set names = new HashSet<>(); try { @SuppressWarnings("unchecked") - Class annotationType = (Class) ClassUtils - .forName(type, classLoader); - collectBeanNamesForAnnotation(names, beanFactory, annotationType, - considerHierarchy); + Class annotationType = (Class) ClassUtils.forName(type, + classLoader); + collectBeanNamesForAnnotation(names, beanFactory, annotationType, considerHierarchy); } catch (ClassNotFoundException ex) { // Continue @@ -237,86 +214,75 @@ class OnBeanCondition extends FilteringSpringBootCondition return StringUtils.toStringArray(names); } - private void collectBeanNamesForAnnotation(Set names, - ListableBeanFactory beanFactory, Class annotationType, - boolean considerHierarchy) { + private void collectBeanNamesForAnnotation(Set names, ListableBeanFactory beanFactory, + Class annotationType, boolean considerHierarchy) { BeanTypeRegistry registry = BeanTypeRegistry.get(beanFactory); names.addAll(registry.getNamesForAnnotation(annotationType)); if (considerHierarchy) { - BeanFactory parent = ((HierarchicalBeanFactory) beanFactory) - .getParentBeanFactory(); + BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory(); if (parent instanceof ListableBeanFactory) { - collectBeanNamesForAnnotation(names, (ListableBeanFactory) parent, - annotationType, considerHierarchy); + collectBeanNamesForAnnotation(names, (ListableBeanFactory) parent, annotationType, considerHierarchy); } } } - private List getNamesOfBeansIgnoredByType(List ignoredTypes, - TypeExtractor typeExtractor, ListableBeanFactory beanFactory, - ConditionContext context, boolean considerHierarchy) { + private List getNamesOfBeansIgnoredByType(List ignoredTypes, TypeExtractor typeExtractor, + ListableBeanFactory beanFactory, ConditionContext context, boolean considerHierarchy) { List beanNames = new ArrayList<>(); for (String ignoredType : ignoredTypes) { - beanNames.addAll(getBeanNamesForType(beanFactory, ignoredType, typeExtractor, - context.getClassLoader(), considerHierarchy)); + beanNames.addAll(getBeanNamesForType(beanFactory, ignoredType, typeExtractor, context.getClassLoader(), + considerHierarchy)); } return beanNames; } - private boolean containsBean(ConfigurableListableBeanFactory beanFactory, - String beanName, boolean considerHierarchy) { + private boolean containsBean(ConfigurableListableBeanFactory beanFactory, String beanName, + boolean considerHierarchy) { if (considerHierarchy) { return beanFactory.containsBean(beanName); } return beanFactory.containsLocalBean(beanName); } - private Collection getBeanNamesForType(ListableBeanFactory beanFactory, - String type, TypeExtractor typeExtractor, ClassLoader classLoader, - boolean considerHierarchy) throws LinkageError { + private Collection getBeanNamesForType(ListableBeanFactory beanFactory, String type, + TypeExtractor typeExtractor, ClassLoader classLoader, boolean considerHierarchy) throws LinkageError { try { - return getBeanNamesForType(beanFactory, considerHierarchy, - ClassUtils.forName(type, classLoader), typeExtractor); + return getBeanNamesForType(beanFactory, considerHierarchy, ClassUtils.forName(type, classLoader), + typeExtractor); } catch (ClassNotFoundException | NoClassDefFoundError ex) { return Collections.emptySet(); } } - private Collection getBeanNamesForType(ListableBeanFactory beanFactory, - boolean considerHierarchy, Class type, TypeExtractor typeExtractor) { + private Collection getBeanNamesForType(ListableBeanFactory beanFactory, boolean considerHierarchy, + Class type, TypeExtractor typeExtractor) { Set result = new LinkedHashSet<>(); - collectBeanNamesForType(result, beanFactory, type, typeExtractor, - considerHierarchy); + collectBeanNamesForType(result, beanFactory, type, typeExtractor, considerHierarchy); return result; } - private void collectBeanNamesForType(Set result, - ListableBeanFactory beanFactory, Class type, TypeExtractor typeExtractor, - boolean considerHierarchy) { + private void collectBeanNamesForType(Set result, ListableBeanFactory beanFactory, Class type, + TypeExtractor typeExtractor, boolean considerHierarchy) { BeanTypeRegistry registry = BeanTypeRegistry.get(beanFactory); result.addAll(registry.getNamesForType(type, typeExtractor)); if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory) { - BeanFactory parent = ((HierarchicalBeanFactory) beanFactory) - .getParentBeanFactory(); + BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory(); if (parent instanceof ListableBeanFactory) { - collectBeanNamesForType(result, (ListableBeanFactory) parent, type, - typeExtractor, considerHierarchy); + collectBeanNamesForType(result, (ListableBeanFactory) parent, type, typeExtractor, considerHierarchy); } } } private String createOnBeanNoMatchReason(MatchResult matchResult) { StringBuilder reason = new StringBuilder(); - appendMessageForNoMatches(reason, matchResult.getUnmatchedAnnotations(), - "annotated with"); + appendMessageForNoMatches(reason, matchResult.getUnmatchedAnnotations(), "annotated with"); appendMessageForNoMatches(reason, matchResult.getUnmatchedTypes(), "of type"); appendMessageForNoMatches(reason, matchResult.getUnmatchedNames(), "named"); return reason.toString(); } - private void appendMessageForNoMatches(StringBuilder reason, - Collection unmatched, String description) { + private void appendMessageForNoMatches(StringBuilder reason, Collection unmatched, String description) { if (!unmatched.isEmpty()) { if (reason.length() > 0) { reason.append(" and "); @@ -330,22 +296,20 @@ class OnBeanCondition extends FilteringSpringBootCondition private String createOnMissingBeanNoMatchReason(MatchResult matchResult) { StringBuilder reason = new StringBuilder(); - appendMessageForMatches(reason, matchResult.getMatchedAnnotations(), - "annotated with"); + appendMessageForMatches(reason, matchResult.getMatchedAnnotations(), "annotated with"); appendMessageForMatches(reason, matchResult.getMatchedTypes(), "of type"); if (!matchResult.getMatchedNames().isEmpty()) { if (reason.length() > 0) { reason.append(" and "); } reason.append("found beans named "); - reason.append(StringUtils - .collectionToDelimitedString(matchResult.getMatchedNames(), ", ")); + reason.append(StringUtils.collectionToDelimitedString(matchResult.getMatchedNames(), ", ")); } return reason.toString(); } - private void appendMessageForMatches(StringBuilder reason, - Map> matches, String description) { + private void appendMessageForMatches(StringBuilder reason, Map> matches, + String description) { if (!matches.isEmpty()) { matches.forEach((key, value) -> { if (reason.length() > 0) { @@ -361,20 +325,16 @@ class OnBeanCondition extends FilteringSpringBootCondition } } - private boolean hasSingleAutowireCandidate( - ConfigurableListableBeanFactory beanFactory, Set beanNames, + private boolean hasSingleAutowireCandidate(ConfigurableListableBeanFactory beanFactory, Set beanNames, boolean considerHierarchy) { - return (beanNames.size() == 1 - || getPrimaryBeans(beanFactory, beanNames, considerHierarchy) - .size() == 1); + return (beanNames.size() == 1 || getPrimaryBeans(beanFactory, beanNames, considerHierarchy).size() == 1); } - private List getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, - Set beanNames, boolean considerHierarchy) { + private List getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, Set beanNames, + boolean considerHierarchy) { List primaryBeans = new ArrayList<>(); for (String beanName : beanNames) { - BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, - considerHierarchy); + BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, considerHierarchy); if (beanDefinition != null && beanDefinition.isPrimary()) { primaryBeans.add(beanName); } @@ -382,15 +342,14 @@ class OnBeanCondition extends FilteringSpringBootCondition return primaryBeans; } - private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory, - String beanName, boolean considerHierarchy) { + private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory, String beanName, + boolean considerHierarchy) { if (beanFactory.containsBeanDefinition(beanName)) { return beanFactory.getBeanDefinition(beanName); } - if (considerHierarchy && beanFactory - .getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { - return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory - .getParentBeanFactory()), beanName, considerHierarchy); + if (considerHierarchy && beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { + return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory.getParentBeanFactory()), beanName, + considerHierarchy); } return null; } @@ -411,16 +370,15 @@ class OnBeanCondition extends FilteringSpringBootCondition private final SearchStrategy strategy; - public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, - Class annotationType) { + public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class annotationType) { this(context, metadata, annotationType, null); } - public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, - Class annotationType, Class genericContainer) { + public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class annotationType, + Class genericContainer) { this.annotationType = annotationType; - MultiValueMap attributes = metadata - .getAllAnnotationAttributes(annotationType.getName(), true); + MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), + true); collect(attributes, "name", this.names); collect(attributes, "value", this.types); collect(attributes, "type", this.types); @@ -443,13 +401,11 @@ class OnBeanCondition extends FilteringSpringBootCondition protected void validate(BeanTypeDeductionException ex) { if (!hasAtLeastOne(this.types, this.names, this.annotations)) { - String message = getAnnotationName() - + " did not specify a bean using type, name or annotation"; + String message = getAnnotationName() + " did not specify a bean using type, name or annotation"; if (ex == null) { throw new IllegalStateException(message); } - throw new IllegalStateException(message + " and the attempt to deduce" - + " the bean's type failed", ex); + throw new IllegalStateException(message + " and the attempt to deduce" + " the bean's type failed", ex); } } @@ -461,8 +417,7 @@ class OnBeanCondition extends FilteringSpringBootCondition return "@" + ClassUtils.getShortName(this.annotationType); } - protected void collect(MultiValueMap attributes, String key, - List destination) { + protected void collect(MultiValueMap attributes, String key, List destination) { List values = attributes.get(key); if (values != null) { for (Object value : values) { @@ -476,24 +431,21 @@ class OnBeanCondition extends FilteringSpringBootCondition } } - private void addDeducedBeanType(ConditionContext context, - AnnotatedTypeMetadata metadata, final List beanTypes) { - if (metadata instanceof MethodMetadata - && metadata.isAnnotated(Bean.class.getName())) { - addDeducedBeanTypeForBeanMethod(context, (MethodMetadata) metadata, - beanTypes); + private void addDeducedBeanType(ConditionContext context, AnnotatedTypeMetadata metadata, + final List beanTypes) { + if (metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName())) { + addDeducedBeanTypeForBeanMethod(context, (MethodMetadata) metadata, beanTypes); } } - private void addDeducedBeanTypeForBeanMethod(ConditionContext context, - MethodMetadata metadata, final List beanTypes) { + private void addDeducedBeanTypeForBeanMethod(ConditionContext context, MethodMetadata metadata, + final List beanTypes) { try { Class returnType = getReturnType(context, metadata); beanTypes.add(returnType.getName()); } catch (Throwable ex) { - throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), - metadata.getMethodName(), ex); + throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), metadata.getMethodName(), ex); } } @@ -502,18 +454,16 @@ class OnBeanCondition extends FilteringSpringBootCondition // We should be safe to load at this point since we are in the // REGISTER_BEAN phase ClassLoader classLoader = context.getClassLoader(); - Class returnType = ClassUtils.forName(metadata.getReturnTypeName(), - classLoader); + Class returnType = ClassUtils.forName(metadata.getReturnTypeName(), classLoader); if (isParameterizedContainer(returnType, classLoader)) { returnType = getReturnTypeGeneric(metadata, classLoader); } return returnType; } - private Class getReturnTypeGeneric(MethodMetadata metadata, - ClassLoader classLoader) throws ClassNotFoundException, LinkageError { - Class declaringClass = ClassUtils.forName(metadata.getDeclaringClassName(), - classLoader); + private Class getReturnTypeGeneric(MethodMetadata metadata, ClassLoader classLoader) + throws ClassNotFoundException, LinkageError { + Class declaringClass = ClassUtils.forName(metadata.getDeclaringClassName(), classLoader); Method beanMethod = findBeanMethod(declaringClass, metadata.getMethodName()); return ResolvableType.forMethodReturnType(beanMethod).resolveGeneric(); } @@ -524,15 +474,13 @@ class OnBeanCondition extends FilteringSpringBootCondition return method; } return Arrays.stream(ReflectionUtils.getAllDeclaredMethods(declaringClass)) - .filter((candidate) -> candidate.getName().equals(methodName)) - .filter(this::isBeanMethod).findFirst() - .orElseThrow(() -> new IllegalStateException( - "Unable to find bean method " + methodName)); + .filter((candidate) -> candidate.getName().equals(methodName)).filter(this::isBeanMethod) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Unable to find bean method " + methodName)); } private boolean isBeanMethod(Method method) { - return method != null && MergedAnnotations - .from(method, MergedAnnotations.SearchStrategy.EXHAUSTIVE) + return method != null && MergedAnnotations.from(method, MergedAnnotations.SearchStrategy.EXHAUSTIVE) .isPresent(Bean.class); } @@ -552,8 +500,7 @@ class OnBeanCondition extends FilteringSpringBootCondition private boolean isParameterizedContainer(Class type, ClassLoader classLoader) { for (String candidate : this.parameterizedContainers) { try { - if (ClassUtils.forName(candidate, classLoader) - .isAssignableFrom(type)) { + if (ClassUtils.forName(candidate, classLoader).isAssignableFrom(type)) { return true; } } @@ -608,22 +555,21 @@ class OnBeanCondition extends FilteringSpringBootCondition private static class SingleCandidateBeanSearchSpec extends BeanSearchSpec { - SingleCandidateBeanSearchSpec(ConditionContext context, - AnnotatedTypeMetadata metadata, Class annotationType) { + SingleCandidateBeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, + Class annotationType) { super(context, metadata, annotationType); } @Override - protected void collect(MultiValueMap attributes, String key, - List destination) { + protected void collect(MultiValueMap attributes, String key, List destination) { super.collect(attributes, key, destination); destination.removeAll(Arrays.asList("", Object.class.getName())); } @Override protected void validate(BeanTypeDeductionException ex) { - Assert.isTrue(getTypes().size() == 1, () -> getAnnotationName() - + " annotations must specify only one type (got " + getTypes() + ")"); + Assert.isTrue(getTypes().size() == 1, + () -> getAnnotationName() + " annotations must specify only one type (got " + getTypes() + ")"); } } @@ -653,8 +599,7 @@ class OnBeanCondition extends FilteringSpringBootCondition this.unmatchedNames.add(name); } - private void recordMatchedAnnotation(String annotation, - Collection matchingNames) { + private void recordMatchedAnnotation(String annotation, Collection matchingNames) { this.matchedAnnotations.put(annotation, matchingNames); this.namesOfAllMatches.addAll(matchingNames); } @@ -714,10 +659,8 @@ class OnBeanCondition extends FilteringSpringBootCondition static final class BeanTypeDeductionException extends RuntimeException { - private BeanTypeDeductionException(String className, String beanMethodName, - Throwable cause) { - super("Failed to deduce bean type for " + className + "." + beanMethodName, - cause); + private BeanTypeDeductionException(String className, String beanMethodName, Throwable cause) { + super("Failed to deduce bean type for " + className + "." + beanMethodName, cause); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java index eb17ebea4e9..2f8f3a5e078 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java @@ -50,13 +50,11 @@ class OnClassCondition extends FilteringSpringBootCondition { // processor is available. Using a single additional thread seems to offer the // best performance. More threads make things worse. if (Runtime.getRuntime().availableProcessors() > 1) { - return resolveOutcomesThreaded(autoConfigurationClasses, - autoConfigurationMetadata); + return resolveOutcomesThreaded(autoConfigurationClasses, autoConfigurationMetadata); } else { - OutcomesResolver outcomesResolver = new StandardOutcomesResolver( - autoConfigurationClasses, 0, autoConfigurationClasses.length, - autoConfigurationMetadata, getBeanClassLoader()); + OutcomesResolver outcomesResolver = new StandardOutcomesResolver(autoConfigurationClasses, 0, + autoConfigurationClasses.length, autoConfigurationMetadata, getBeanClassLoader()); return outcomesResolver.resolveOutcomes(); } } @@ -64,11 +62,10 @@ class OnClassCondition extends FilteringSpringBootCondition { private ConditionOutcome[] resolveOutcomesThreaded(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { int split = autoConfigurationClasses.length / 2; - OutcomesResolver firstHalfResolver = createOutcomesResolver( - autoConfigurationClasses, 0, split, autoConfigurationMetadata); - OutcomesResolver secondHalfResolver = new StandardOutcomesResolver( - autoConfigurationClasses, split, autoConfigurationClasses.length, - autoConfigurationMetadata, getBeanClassLoader()); + OutcomesResolver firstHalfResolver = createOutcomesResolver(autoConfigurationClasses, 0, split, + autoConfigurationMetadata); + OutcomesResolver secondHalfResolver = new StandardOutcomesResolver(autoConfigurationClasses, split, + autoConfigurationClasses.length, autoConfigurationMetadata, getBeanClassLoader()); ConditionOutcome[] secondHalf = secondHalfResolver.resolveOutcomes(); ConditionOutcome[] firstHalf = firstHalfResolver.resolveOutcomes(); ConditionOutcome[] outcomes = new ConditionOutcome[autoConfigurationClasses.length]; @@ -77,11 +74,10 @@ class OnClassCondition extends FilteringSpringBootCondition { return outcomes; } - private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, - int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) { - OutcomesResolver outcomesResolver = new StandardOutcomesResolver( - autoConfigurationClasses, start, end, autoConfigurationMetadata, - getBeanClassLoader()); + private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata) { + OutcomesResolver outcomesResolver = new StandardOutcomesResolver(autoConfigurationClasses, start, end, + autoConfigurationMetadata, getBeanClassLoader()); try { return new ThreadedOutcomesResolver(outcomesResolver); } @@ -91,47 +87,36 @@ class OnClassCondition extends FilteringSpringBootCondition { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ClassLoader classLoader = context.getClassLoader(); ConditionMessage matchMessage = ConditionMessage.empty(); List onClasses = getCandidates(metadata, ConditionalOnClass.class); if (onClasses != null) { - List missing = filter(onClasses, ClassNameFilter.MISSING, - classLoader); + List missing = filter(onClasses, ClassNameFilter.MISSING, classLoader); if (!missing.isEmpty()) { - return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class", "required classes") - .items(Style.QUOTE, missing)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) + .didNotFind("required class", "required classes").items(Style.QUOTE, missing)); } matchMessage = matchMessage.andCondition(ConditionalOnClass.class) - .found("required class", "required classes").items(Style.QUOTE, - filter(onClasses, ClassNameFilter.PRESENT, classLoader)); + .found("required class", "required classes") + .items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader)); } - List onMissingClasses = getCandidates(metadata, - ConditionalOnMissingClass.class); + List onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class); if (onMissingClasses != null) { - List present = filter(onMissingClasses, ClassNameFilter.PRESENT, - classLoader); + List present = filter(onMissingClasses, ClassNameFilter.PRESENT, classLoader); if (!present.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnMissingClass.class) - .found("unwanted class", "unwanted classes") - .items(Style.QUOTE, present)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class) + .found("unwanted class", "unwanted classes").items(Style.QUOTE, present)); } matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class) .didNotFind("unwanted class", "unwanted classes") - .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, - classLoader)); + .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, classLoader)); } return ConditionOutcome.match(matchMessage); } - private List getCandidates(AnnotatedTypeMetadata metadata, - Class annotationType) { - MultiValueMap attributes = metadata - .getAllAnnotationAttributes(annotationType.getName(), true); + private List getCandidates(AnnotatedTypeMetadata metadata, Class annotationType) { + MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), true); if (attributes == null) { return null; } @@ -162,8 +147,7 @@ class OnClassCondition extends FilteringSpringBootCondition { private volatile ConditionOutcome[] outcomes; private ThreadedOutcomesResolver(OutcomesResolver outcomesResolver) { - this.thread = new Thread( - () -> this.outcomes = outcomesResolver.resolveOutcomes()); + this.thread = new Thread(() -> this.outcomes = outcomesResolver.resolveOutcomes()); this.thread.start(); } @@ -192,9 +176,8 @@ class OnClassCondition extends FilteringSpringBootCondition { private final ClassLoader beanClassLoader; - private StandardOutcomesResolver(String[] autoConfigurationClasses, int start, - int end, AutoConfigurationMetadata autoConfigurationMetadata, - ClassLoader beanClassLoader) { + private StandardOutcomesResolver(String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata, ClassLoader beanClassLoader) { this.autoConfigurationClasses = autoConfigurationClasses; this.start = start; this.end = end; @@ -204,18 +187,16 @@ class OnClassCondition extends FilteringSpringBootCondition { @Override public ConditionOutcome[] resolveOutcomes() { - return getOutcomes(this.autoConfigurationClasses, this.start, this.end, - this.autoConfigurationMetadata); + return getOutcomes(this.autoConfigurationClasses, this.start, this.end, this.autoConfigurationMetadata); } - private ConditionOutcome[] getOutcomes(String[] autoConfigurationClasses, - int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) { + private ConditionOutcome[] getOutcomes(String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata) { ConditionOutcome[] outcomes = new ConditionOutcome[end - start]; for (int i = start; i < end; i++) { String autoConfigurationClass = autoConfigurationClasses[i]; if (autoConfigurationClass != null) { - String candidates = autoConfigurationMetadata - .get(autoConfigurationClass, "ConditionalOnClass"); + String candidates = autoConfigurationMetadata.get(autoConfigurationClass, "ConditionalOnClass"); if (candidates != null) { outcomes[i - start] = getOutcome(candidates); } @@ -229,10 +210,8 @@ class OnClassCondition extends FilteringSpringBootCondition { if (!candidates.contains(",")) { return getOutcome(candidates, this.beanClassLoader); } - for (String candidate : StringUtils - .commaDelimitedListToStringArray(candidates)) { - ConditionOutcome outcome = getOutcome(candidate, - this.beanClassLoader); + for (String candidate : StringUtils.commaDelimitedListToStringArray(candidates)) { + ConditionOutcome outcome = getOutcome(candidate, this.beanClassLoader); if (outcome != null) { return outcome; } @@ -246,8 +225,7 @@ class OnClassCondition extends FilteringSpringBootCondition { private ConditionOutcome getOutcome(String className, ClassLoader classLoader) { if (ClassNameFilter.MISSING.matches(className, classLoader)) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnClass.class) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) .didNotFind("required class").items(Style.QUOTE, className)); } return null; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java index 1e0da081c82..59a4963274c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,19 +33,15 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnCloudPlatformCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnCloudPlatform.class.getName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + Map attributes = metadata.getAnnotationAttributes(ConditionalOnCloudPlatform.class.getName()); CloudPlatform cloudPlatform = (CloudPlatform) attributes.get("value"); return getMatchOutcome(context.getEnvironment(), cloudPlatform); } - private ConditionOutcome getMatchOutcome(Environment environment, - CloudPlatform cloudPlatform) { + private ConditionOutcome getMatchOutcome(Environment environment, CloudPlatform cloudPlatform) { String name = cloudPlatform.name(); - ConditionMessage.Builder message = ConditionMessage - .forCondition(ConditionalOnCloudPlatform.class); + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnCloudPlatform.class); if (cloudPlatform.isActive(environment)) { return ConditionOutcome.match(message.foundExactly(name)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java index ccf5f2eb91e..a7098f325a9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,32 +36,27 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnExpressionCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - String expression = (String) metadata - .getAnnotationAttributes(ConditionalOnExpression.class.getName()) + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String expression = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName()) .get("value"); expression = wrapIfNecessary(expression); - ConditionMessage.Builder messageBuilder = ConditionMessage - .forCondition(ConditionalOnExpression.class, "(" + expression + ")"); + ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class, + "(" + expression + ")"); expression = context.getEnvironment().resolvePlaceholders(expression); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); if (beanFactory != null) { boolean result = evaluateExpression(beanFactory, expression); return new ConditionOutcome(result, messageBuilder.resultedIn(result)); } - return ConditionOutcome - .noMatch(messageBuilder.because("no BeanFactory available.")); + return ConditionOutcome.noMatch(messageBuilder.because("no BeanFactory available.")); } - private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, - String expression) { + private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, String expression) { BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver(); if (resolver == null) { resolver = new StandardBeanExpressionResolver(); } - BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, - null); + BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, null); Object result = resolver.evaluate(expression, expressionContext); return (result != null && (boolean) result); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java index 58b8faaeb7b..db24b240925 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,23 +40,17 @@ class OnJavaCondition extends SpringBootCondition { private static final JavaVersion JVM_VERSION = JavaVersion.getJavaVersion(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnJava.class.getName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + Map attributes = metadata.getAnnotationAttributes(ConditionalOnJava.class.getName()); Range range = (Range) attributes.get("range"); JavaVersion version = (JavaVersion) attributes.get("value"); return getMatchOutcome(range, JVM_VERSION, version); } - protected ConditionOutcome getMatchOutcome(Range range, JavaVersion runningVersion, - JavaVersion version) { + protected ConditionOutcome getMatchOutcome(Range range, JavaVersion runningVersion, JavaVersion version) { boolean match = isWithin(runningVersion, range, version); - String expected = String.format( - (range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", - version); - ConditionMessage message = ConditionMessage - .forCondition(ConditionalOnJava.class, expected) + String expected = String.format((range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", version); + ConditionMessage message = ConditionMessage.forCondition(ConditionalOnJava.class, expected) .foundExactly(runningVersion); return new ConditionOutcome(match, message); } @@ -68,8 +62,7 @@ class OnJavaCondition extends SpringBootCondition { * @param version the bounds of the range * @return if this version is within the specified range */ - private boolean isWithin(JavaVersion runningVersion, Range range, - JavaVersion version) { + private boolean isWithin(JavaVersion runningVersion, Range range, JavaVersion version) { if (range == Range.EQUAL_OR_NEWER) { return runningVersion.isEqualOrNewerThan(version); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java index f50179bb48c..8ddf0473fc1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,42 +39,37 @@ import org.springframework.util.StringUtils; class OnJndiCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + AnnotationAttributes annotationAttributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); String[] locations = annotationAttributes.getStringArray("value"); try { return getMatchOutcome(locations); } catch (NoClassDefFoundError ex) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class) - .because("JNDI class not found")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found")); } } private ConditionOutcome getMatchOutcome(String[] locations) { if (!isJndiAvailable()) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class) - .notAvailable("JNDI environment")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment")); } if (locations.length == 0) { - return ConditionOutcome.match(ConditionMessage - .forCondition(ConditionalOnJndi.class).available("JNDI environment")); + return ConditionOutcome + .match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment")); } JndiLocator locator = getJndiLocator(locations); String location = locator.lookupFirstLocation(); String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")"; if (location != null) { - return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .foundExactly("\"" + location + "\"")); + return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details) + .foundExactly("\"" + location + "\"")); } - return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .didNotFind("any matching JNDI location").atAll()); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details) + .didNotFind("any matching JNDI location").atAll()); } protected boolean isJndiAvailable() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java index 76119c0d378..23145ed76db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,16 +47,13 @@ import org.springframework.util.StringUtils; class OnPropertyCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List allAnnotationAttributes = annotationAttributesFromMultiValueMap( - metadata.getAllAnnotationAttributes( - ConditionalOnProperty.class.getName())); + metadata.getAllAnnotationAttributes(ConditionalOnProperty.class.getName())); List noMatch = new ArrayList<>(); List match = new ArrayList<>(); for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) { - ConditionOutcome outcome = determineOutcome(annotationAttributes, - context.getEnvironment()); + ConditionOutcome outcome = determineOutcome(annotationAttributes, context.getEnvironment()); (outcome.isMatch() ? match : noMatch).add(outcome.getConditionMessage()); } if (!noMatch.isEmpty()) { @@ -88,27 +85,22 @@ class OnPropertyCondition extends SpringBootCondition { return annotationAttributes; } - private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, - PropertyResolver resolver) { + private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, PropertyResolver resolver) { Spec spec = new Spec(annotationAttributes); List missingProperties = new ArrayList<>(); List nonMatchingProperties = new ArrayList<>(); spec.collectProperties(resolver, missingProperties, nonMatchingProperties); if (!missingProperties.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .didNotFind("property", "properties") - .items(Style.QUOTE, missingProperties)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) + .didNotFind("property", "properties").items(Style.QUOTE, missingProperties)); } if (!nonMatchingProperties.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .found("different value in property", - "different value in properties") - .items(Style.QUOTE, nonMatchingProperties)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) + .found("different value in property", "different value in properties") + .items(Style.QUOTE, nonMatchingProperties)); } - return ConditionOutcome.match(ConditionMessage - .forCondition(ConditionalOnProperty.class, spec).because("matched")); + return ConditionOutcome + .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched")); } private static class Spec { @@ -142,8 +134,7 @@ class OnPropertyCondition extends SpringBootCondition { return (value.length > 0) ? value : name; } - private void collectProperties(PropertyResolver resolver, List missing, - List nonMatching) { + private void collectProperties(PropertyResolver resolver, List missing, List nonMatching) { for (String name : this.names) { String key = this.prefix + name; if (resolver.containsProperty(key)) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyListCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyListCondition.java index ac4ea941f01..413de3b31fc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyListCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyListCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata; */ public class OnPropertyListCondition extends SpringBootCondition { - private static final Bindable> STRING_LIST = Bindable - .listOf(String.class); + private static final Bindable> STRING_LIST = Bindable.listOf(String.class); private final String propertyName; @@ -49,24 +48,19 @@ public class OnPropertyListCondition extends SpringBootCondition { * @param messageBuilder a message builder supplier that should provide a fresh * instance on each call */ - protected OnPropertyListCondition(String propertyName, - Supplier messageBuilder) { + protected OnPropertyListCondition(String propertyName, Supplier messageBuilder) { this.propertyName = propertyName; this.messageBuilder = messageBuilder; } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - BindResult property = Binder.get(context.getEnvironment()) - .bind(this.propertyName, STRING_LIST); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + BindResult property = Binder.get(context.getEnvironment()).bind(this.propertyName, STRING_LIST); ConditionMessage.Builder messageBuilder = this.messageBuilder.get(); if (property.isBound()) { - return ConditionOutcome - .match(messageBuilder.found("property").items(this.propertyName)); + return ConditionOutcome.match(messageBuilder.found("property").items(this.propertyName)); } - return ConditionOutcome - .noMatch(messageBuilder.didNotFind("property").items(this.propertyName)); + return ConditionOutcome.noMatch(messageBuilder.didNotFind("property").items(this.propertyName)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java index 072328ed295..f3188c1cb40 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,17 +42,15 @@ class OnResourceCondition extends SpringBootCondition { private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { MultiValueMap attributes = metadata .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); - ResourceLoader loader = (context.getResourceLoader() != null) - ? context.getResourceLoader() : this.defaultResourceLoader; + ResourceLoader loader = (context.getResourceLoader() != null) ? context.getResourceLoader() + : this.defaultResourceLoader; List locations = new ArrayList<>(); collectValues(locations, attributes.get("resources")); Assert.isTrue(!locations.isEmpty(), - "@ConditionalOnResource annotations must specify at " - + "least one resource location"); + "@ConditionalOnResource annotations must specify at " + "least one resource location"); List missing = new ArrayList<>(); for (String location : locations) { String resource = context.getEnvironment().resolvePlaceholders(location); @@ -61,13 +59,11 @@ class OnResourceCondition extends SpringBootCondition { } } if (!missing.isEmpty()) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnResource.class) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.class) .didNotFind("resource", "resources").items(Style.QUOTE, missing)); } - return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnResource.class) - .found("location", "locations").items(locations)); + return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.class) + .found("location", "locations").items(locations)); } private void collectValues(List names, List values) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java index dd97fe1d246..f0545576986 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,8 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition { for (int i = 0; i < outcomes.length; i++) { String autoConfigurationClass = autoConfigurationClasses[i]; if (autoConfigurationClass != null) { - outcomes[i] = getOutcome(autoConfigurationMetadata - .get(autoConfigurationClass, "ConditionalOnWebApplication")); + outcomes[i] = getOutcome( + autoConfigurationMetadata.get(autoConfigurationClass, "ConditionalOnWebApplication")); } } return outcomes; @@ -66,37 +66,27 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition { if (type == null) { return null; } - ConditionMessage.Builder message = ConditionMessage - .forCondition(ConditionalOnWebApplication.class); + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class); if (ConditionalOnWebApplication.Type.SERVLET.name().equals(type)) { - if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, - getBeanClassLoader())) { - return ConditionOutcome.noMatch( - message.didNotFind("servlet web application classes").atAll()); + if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, getBeanClassLoader())) { + return ConditionOutcome.noMatch(message.didNotFind("servlet web application classes").atAll()); } } if (ConditionalOnWebApplication.Type.REACTIVE.name().equals(type)) { - if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, - getBeanClassLoader())) { - return ConditionOutcome.noMatch( - message.didNotFind("reactive web application classes").atAll()); + if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, getBeanClassLoader())) { + return ConditionOutcome.noMatch(message.didNotFind("reactive web application classes").atAll()); } } - if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, - getBeanClassLoader()) - && !ClassUtils.isPresent(REACTIVE_WEB_APPLICATION_CLASS, - getBeanClassLoader())) { - return ConditionOutcome.noMatch(message - .didNotFind("reactive or servlet web application classes").atAll()); + if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, getBeanClassLoader()) + && !ClassUtils.isPresent(REACTIVE_WEB_APPLICATION_CLASS, getBeanClassLoader())) { + return ConditionOutcome.noMatch(message.didNotFind("reactive or servlet web application classes").atAll()); } return null; } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - boolean required = metadata - .isAnnotated(ConditionalOnWebApplication.class.getName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + boolean required = metadata.isAnnotated(ConditionalOnWebApplication.class.getName()); ConditionOutcome outcome = isWebApplication(context, metadata, required); if (required && !outcome.isMatch()) { return ConditionOutcome.noMatch(outcome.getConditionMessage()); @@ -107,8 +97,8 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition { return ConditionOutcome.match(outcome.getConditionMessage()); } - private ConditionOutcome isWebApplication(ConditionContext context, - AnnotatedTypeMetadata metadata, boolean required) { + private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata, + boolean required) { switch (deduceType(metadata)) { case SERVLET: return isServletWebApplication(context); @@ -119,31 +109,25 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition { } } - private ConditionOutcome isAnyWebApplication(ConditionContext context, - boolean required) { - ConditionMessage.Builder message = ConditionMessage.forCondition( - ConditionalOnWebApplication.class, required ? "(required)" : ""); + private ConditionOutcome isAnyWebApplication(ConditionContext context, boolean required) { + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class, + required ? "(required)" : ""); ConditionOutcome servletOutcome = isServletWebApplication(context); if (servletOutcome.isMatch() && required) { - return new ConditionOutcome(servletOutcome.isMatch(), - message.because(servletOutcome.getMessage())); + return new ConditionOutcome(servletOutcome.isMatch(), message.because(servletOutcome.getMessage())); } ConditionOutcome reactiveOutcome = isReactiveWebApplication(context); if (reactiveOutcome.isMatch() && required) { - return new ConditionOutcome(reactiveOutcome.isMatch(), - message.because(reactiveOutcome.getMessage())); + return new ConditionOutcome(reactiveOutcome.isMatch(), message.because(reactiveOutcome.getMessage())); } return new ConditionOutcome(servletOutcome.isMatch() || reactiveOutcome.isMatch(), - message.because(servletOutcome.getMessage()).append("and") - .append(reactiveOutcome.getMessage())); + message.because(servletOutcome.getMessage()).append("and").append(reactiveOutcome.getMessage())); } private ConditionOutcome isServletWebApplication(ConditionContext context) { ConditionMessage.Builder message = ConditionMessage.forCondition(""); - if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, - context.getClassLoader())) { - return ConditionOutcome.noMatch( - message.didNotFind("servlet web application classes").atAll()); + if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, context.getClassLoader())) { + return ConditionOutcome.noMatch(message.didNotFind("servlet web application classes").atAll()); } if (context.getBeanFactory() != null) { String[] scopes = context.getBeanFactory().getRegisteredScopeNames(); @@ -152,8 +136,7 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition { } } if (context.getEnvironment() instanceof ConfigurableWebEnvironment) { - return ConditionOutcome - .match(message.foundExactly("ConfigurableWebEnvironment")); + return ConditionOutcome.match(message.foundExactly("ConfigurableWebEnvironment")); } if (context.getResourceLoader() instanceof WebApplicationContext) { return ConditionOutcome.match(message.foundExactly("WebApplicationContext")); @@ -163,26 +146,20 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition { private ConditionOutcome isReactiveWebApplication(ConditionContext context) { ConditionMessage.Builder message = ConditionMessage.forCondition(""); - if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, - context.getClassLoader())) { - return ConditionOutcome.noMatch( - message.didNotFind("reactive web application classes").atAll()); + if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, context.getClassLoader())) { + return ConditionOutcome.noMatch(message.didNotFind("reactive web application classes").atAll()); } if (context.getEnvironment() instanceof ConfigurableReactiveWebEnvironment) { - return ConditionOutcome - .match(message.foundExactly("ConfigurableReactiveWebEnvironment")); + return ConditionOutcome.match(message.foundExactly("ConfigurableReactiveWebEnvironment")); } if (context.getResourceLoader() instanceof ReactiveWebApplicationContext) { - return ConditionOutcome - .match(message.foundExactly("ReactiveWebApplicationContext")); + return ConditionOutcome.match(message.foundExactly("ReactiveWebApplicationContext")); } - return ConditionOutcome - .noMatch(message.because("not a reactive web application")); + return ConditionOutcome.noMatch(message.because("not a reactive web application")); } private Type deduceType(AnnotatedTypeMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnWebApplication.class.getName()); + Map attributes = metadata.getAnnotationAttributes(ConditionalOnWebApplication.class.getName()); if (attributes != null) { return (Type) attributes.get("type"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java index c81d6a94454..acb578357d5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,19 +51,16 @@ public abstract class ResourceCondition extends SpringBootCondition { * found if the configuration key is not specified * @since 2.0.0 */ - protected ResourceCondition(String name, String property, - String... resourceLocations) { + protected ResourceCondition(String name, String property, String... resourceLocations) { this.name = name; this.property = property; this.resourceLocations = resourceLocations; } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { if (context.getEnvironment().containsProperty(this.property)) { - return ConditionOutcome.match( - startConditionMessage().foundExactly("property " + this.property)); + return ConditionOutcome.match(startConditionMessage().foundExactly("property " + this.property)); } return getResourceOutcome(context, metadata); } @@ -74,8 +71,7 @@ public abstract class ResourceCondition extends SpringBootCondition { * @param metadata the annotation metadata * @return the condition outcome */ - protected ConditionOutcome getResourceOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List found = new ArrayList<>(); for (String location : this.resourceLocations) { Resource resource = context.getResourceLoader().getResource(location); @@ -84,13 +80,11 @@ public abstract class ResourceCondition extends SpringBootCondition { } } if (found.isEmpty()) { - ConditionMessage message = startConditionMessage() - .didNotFind("resource", "resources") - .items(Style.QUOTE, Arrays.asList(this.resourceLocations)); + ConditionMessage message = startConditionMessage().didNotFind("resource", "resources").items(Style.QUOTE, + Arrays.asList(this.resourceLocations)); return ConditionOutcome.noMatch(message); } - ConditionMessage message = startConditionMessage().found("resource", "resources") - .items(Style.QUOTE, found); + ConditionMessage message = startConditionMessage().found("resource", "resources").items(Style.QUOTE, found); return ConditionOutcome.match(message); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java index cc58c0e8a00..fe343b6976c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ public abstract class SpringBootCondition implements Condition { private final Log logger = LogFactory.getLog(getClass()); @Override - public final boolean matches(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String classOrMethodName = getClassOrMethodName(metadata); try { ConditionOutcome outcome = getMatchOutcome(context, metadata); @@ -50,18 +49,14 @@ public abstract class SpringBootCondition implements Condition { return outcome.isMatch(); } catch (NoClassDefFoundError ex) { - throw new IllegalStateException( - "Could not evaluate condition on " + classOrMethodName + " due to " - + ex.getMessage() + " not " - + "found. Make sure your own configuration does not rely on " - + "that class. This can also happen if you are " - + "@ComponentScanning a springframework package (e.g. if you " - + "put a @ComponentScan in the default package by mistake)", - ex); + throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to " + + ex.getMessage() + " not " + "found. Make sure your own configuration does not rely on " + + "that class. This can also happen if you are " + + "@ComponentScanning a springframework package (e.g. if you " + + "put a @ComponentScan in the default package by mistake)", ex); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Error processing condition on " + getName(metadata), ex); + throw new IllegalStateException("Error processing condition on " + getName(metadata), ex); } } @@ -71,8 +66,7 @@ public abstract class SpringBootCondition implements Condition { } if (metadata instanceof MethodMetadata) { MethodMetadata methodMetadata = (MethodMetadata) metadata; - return methodMetadata.getDeclaringClassName() + "." - + methodMetadata.getMethodName(); + return methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(); } return metadata.toString(); } @@ -83,8 +77,7 @@ public abstract class SpringBootCondition implements Condition { return classMetadata.getClassName(); } MethodMetadata methodMetadata = (MethodMetadata) metadata; - return methodMetadata.getDeclaringClassName() + "#" - + methodMetadata.getMethodName(); + return methodMetadata.getDeclaringClassName() + "#" + methodMetadata.getMethodName(); } protected final void logOutcome(String classOrMethodName, ConditionOutcome outcome) { @@ -93,8 +86,7 @@ public abstract class SpringBootCondition implements Condition { } } - private StringBuilder getLogMessage(String classOrMethodName, - ConditionOutcome outcome) { + private StringBuilder getLogMessage(String classOrMethodName, ConditionOutcome outcome) { StringBuilder message = new StringBuilder(); message.append("Condition "); message.append(ClassUtils.getShortName(getClass())); @@ -108,11 +100,10 @@ public abstract class SpringBootCondition implements Condition { return message; } - private void recordEvaluation(ConditionContext context, String classOrMethodName, - ConditionOutcome outcome) { + private void recordEvaluation(ConditionContext context, String classOrMethodName, ConditionOutcome outcome) { if (context.getBeanFactory() != null) { - ConditionEvaluationReport.get(context.getBeanFactory()) - .recordConditionEvaluation(classOrMethodName, this, outcome); + ConditionEvaluationReport.get(context.getBeanFactory()).recordConditionEvaluation(classOrMethodName, this, + outcome); } } @@ -122,8 +113,7 @@ public abstract class SpringBootCondition implements Condition { * @param metadata the annotation metadata * @return the condition outcome */ - public abstract ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata); + public abstract ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata); /** * Return true if any of the specified conditions match. @@ -132,8 +122,8 @@ public abstract class SpringBootCondition implements Condition { * @param conditions conditions to test * @return {@code true} if any condition matches. */ - protected final boolean anyMatches(ConditionContext context, - AnnotatedTypeMetadata metadata, Condition... conditions) { + protected final boolean anyMatches(ConditionContext context, AnnotatedTypeMetadata metadata, + Condition... conditions) { for (Condition condition : conditions) { if (matches(context, metadata, condition)) { return true; @@ -149,11 +139,9 @@ public abstract class SpringBootCondition implements Condition { * @param condition condition to test * @return {@code true} if the condition matches. */ - protected final boolean matches(ConditionContext context, - AnnotatedTypeMetadata metadata, Condition condition) { + protected final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata, Condition condition) { if (condition instanceof SpringBootCondition) { - return ((SpringBootCondition) condition).getMatchOutcome(context, metadata) - .isMatch(); + return ((SpringBootCondition) condition).getMatchOutcome(context, metadata).isMatch(); } return condition.matches(context, metadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java index 978f3011418..5bc39b42945 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.util.StringUtils; * @author Eddú Meléndez */ @Configuration(proxyBeanMethods = false) -@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, - search = SearchStrategy.CURRENT) +@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Conditional(ResourceBundleCondition.class) @EnableConfigurationProperties @@ -69,8 +68,8 @@ public class MessageSourceAutoConfiguration { public MessageSource messageSource(MessageSourceProperties properties) { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(properties.getBasename())) { - messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray( - StringUtils.trimAllWhitespace(properties.getBasename()))); + messageSource.setBasenames(StringUtils + .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); } if (properties.getEncoding() != null) { messageSource.setDefaultEncoding(properties.getEncoding().name()); @@ -90,10 +89,8 @@ public class MessageSourceAutoConfiguration { private static ConcurrentReferenceHashMap cache = new ConcurrentReferenceHashMap<>(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - String basename = context.getEnvironment() - .getProperty("spring.messages.basename", "messages"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages"); ConditionOutcome outcome = cache.get(basename); if (outcome == null) { outcome = getMatchOutcomeForBasename(context, basename); @@ -102,21 +99,16 @@ public class MessageSourceAutoConfiguration { return outcome; } - private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, - String basename) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("ResourceBundle"); - for (String name : StringUtils.commaDelimitedListToStringArray( - StringUtils.trimAllWhitespace(basename))) { + private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) { + ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle"); + for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) { for (Resource resource : getResources(context.getClassLoader(), name)) { if (resource.exists()) { - return ConditionOutcome - .match(message.found("bundle").items(resource)); + return ConditionOutcome.match(message.found("bundle").items(resource)); } } } - return ConditionOutcome.noMatch( - message.didNotFind("bundle with basename " + basename).atAll()); + return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll()); } private Resource[] getResources(ClassLoader classLoader, String name) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java index 8e49568fcf0..d99003a453d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java @@ -70,8 +70,7 @@ public class CouchbaseAutoConfiguration { } - @ConditionalOnBean( - type = "org.springframework.data.couchbase.config.CouchbaseConfigurer") + @ConditionalOnBean(type = "org.springframework.data.couchbase.config.CouchbaseConfigurer") static class CouchbaseConfigurerAvailable { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseConfiguration.java index 28f14f89dcf..dca51849646 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseConfiguration.java @@ -57,11 +57,9 @@ public class CouchbaseConfiguration { @Bean @Primary public Cluster couchbaseCluster() { - CouchbaseCluster couchbaseCluster = CouchbaseCluster - .create(couchbaseEnvironment(), determineBootstrapHosts()); + CouchbaseCluster couchbaseCluster = CouchbaseCluster.create(couchbaseEnvironment(), determineBootstrapHosts()); if (isRoleBasedAccessControlEnabled()) { - return couchbaseCluster.authenticate(this.properties.getUsername(), - this.properties.getPassword()); + return couchbaseCluster.authenticate(this.properties.getUsername(), this.properties.getPassword()); } return couchbaseCluster; } @@ -78,8 +76,9 @@ public class CouchbaseConfiguration { @Primary @DependsOn("couchbaseClient") public ClusterInfo couchbaseClusterInfo() { - return couchbaseCluster().clusterManager(this.properties.getBucket().getName(), - this.properties.getBucket().getPassword()).info(); + return couchbaseCluster() + .clusterManager(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()) + .info(); } @Bean @@ -93,8 +92,7 @@ public class CouchbaseConfiguration { } private boolean isRoleBasedAccessControlEnabled() { - return this.properties.getUsername() != null - && this.properties.getPassword() != null; + return this.properties.getUsername() != null && this.properties.getPassword() != null; } /** @@ -102,17 +100,14 @@ public class CouchbaseConfiguration { * @param properties the couchbase properties to use * @return the {@link DefaultCouchbaseEnvironment} builder. */ - protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder( - CouchbaseProperties properties) { + protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder(CouchbaseProperties properties) { CouchbaseProperties.Endpoints endpoints = properties.getEnv().getEndpoints(); CouchbaseProperties.Timeouts timeouts = properties.getEnv().getTimeouts(); - DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment - .builder(); + DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment.builder(); if (timeouts.getConnect() != null) { builder = builder.connectTimeout(timeouts.getConnect().toMillis()); } - builder = builder.keyValueServiceConfig( - KeyValueServiceConfig.create(endpoints.getKeyValue())); + builder = builder.keyValueServiceConfig(KeyValueServiceConfig.create(endpoints.getKeyValue())); if (timeouts.getKeyValue() != null) { builder = builder.kvTimeout(timeouts.getKeyValue().toMillis()); } @@ -122,8 +117,7 @@ public class CouchbaseConfiguration { builder = builder.viewServiceConfig(getViewServiceConfig(endpoints)); } if (timeouts.getSocketConnect() != null) { - builder = builder - .socketConnectTimeout((int) timeouts.getSocketConnect().toMillis()); + builder = builder.socketConnectTimeout((int) timeouts.getSocketConnect().toMillis()); } if (timeouts.getView() != null) { builder = builder.viewTimeout(timeouts.getView().toMillis()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java index e5aa85ee296..e7080ec5af2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java @@ -220,8 +220,7 @@ public class CouchbaseProperties { private String keyStorePassword; public Boolean getEnabled() { - return (this.enabled != null) ? this.enabled - : StringUtils.hasText(this.keyStore); + return (this.enabled != null) ? this.enabled : StringUtils.hasText(this.keyStore); } public void setEnabled(Boolean enabled) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java index 5c0596270cc..98898ede88e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.boot.autoconfigure.condition.OnPropertyListCondition; class OnBootstrapHostsCondition extends OnPropertyListCondition { OnBootstrapHostsCondition() { - super("spring.couchbase.bootstrap-hosts", - () -> ConditionMessage.forCondition("Couchbase Bootstrap Hosts")); + super("spring.couchbase.bootstrap-hosts", () -> ConditionMessage.forCondition("Couchbase Bootstrap Hosts")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java index 73a71373908..d0615321641 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java @@ -40,13 +40,12 @@ public class PersistenceExceptionTranslationAutoConfiguration { @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = "spring.dao.exceptiontranslation", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.dao.exceptiontranslation", name = "enabled", matchIfMissing = true) public static PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor( Environment environment) { PersistenceExceptionTranslationPostProcessor postProcessor = new PersistenceExceptionTranslationPostProcessor(); - boolean proxyTargetClass = environment.getProperty( - "spring.aop.proxy-target-class", Boolean.class, Boolean.TRUE); + boolean proxyTargetClass = environment.getProperty("spring.aop.proxy-target-class", Boolean.class, + Boolean.TRUE); postProcessor.setProxyTargetClass(proxyTargetClass); return postProcessor; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java index 60e32afec18..686764b26c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java @@ -45,8 +45,7 @@ import org.springframework.data.util.Streamable; * @author Oliver Gierke */ public abstract class AbstractRepositoryConfigurationSourceSupport - implements ImportBeanDefinitionRegistrar, BeanFactoryAware, ResourceLoaderAware, - EnvironmentAware { + implements ImportBeanDefinitionRegistrar, BeanFactoryAware, ResourceLoaderAware, EnvironmentAware { private ResourceLoader resourceLoader; @@ -55,20 +54,18 @@ public abstract class AbstractRepositoryConfigurationSourceSupport private Environment environment; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, + BeanNameGenerator importBeanNameGenerator) { RepositoryConfigurationDelegate delegate = new RepositoryConfigurationDelegate( - getConfigurationSource(registry, importBeanNameGenerator), - this.resourceLoader, this.environment); + getConfigurationSource(registry, importBeanNameGenerator), this.resourceLoader, this.environment); delegate.registerRepositoriesIn(registry, getRepositoryConfigurationExtension()); } - private AnnotationRepositoryConfigurationSource getConfigurationSource( - BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) { + private AnnotationRepositoryConfigurationSource getConfigurationSource(BeanDefinitionRegistry registry, + BeanNameGenerator importBeanNameGenerator) { AnnotationMetadata metadata = AnnotationMetadata.introspect(getConfiguration()); - return new AutoConfiguredAnnotationRepositoryConfigurationSource(metadata, - getAnnotation(), this.resourceLoader, this.environment, registry, - importBeanNameGenerator) { + return new AutoConfiguredAnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader, + this.environment, registry, importBeanNameGenerator) { }; } @@ -125,9 +122,8 @@ public abstract class AbstractRepositoryConfigurationSourceSupport extends AnnotationRepositoryConfigurationSource { AutoConfiguredAnnotationRepositoryConfigurationSource(AnnotationMetadata metadata, - Class annotation, ResourceLoader resourceLoader, - Environment environment, BeanDefinitionRegistry registry, - BeanNameGenerator generator) { + Class annotation, ResourceLoader resourceLoader, Environment environment, + BeanDefinitionRegistry registry, BeanNameGenerator generator) { super(metadata, annotation, resourceLoader, environment, registry, generator); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java index a9038aa6556..4900574a29a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,29 +35,24 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnRepositoryTypeCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Map attributes = metadata.getAnnotationAttributes( - ConditionalOnRepositoryType.class.getName(), true); - RepositoryType configuredType = getTypeProperty(context.getEnvironment(), - (String) attributes.get("store")); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + Map attributes = metadata.getAnnotationAttributes(ConditionalOnRepositoryType.class.getName(), + true); + RepositoryType configuredType = getTypeProperty(context.getEnvironment(), (String) attributes.get("store")); RepositoryType requiredType = (RepositoryType) attributes.get("type"); - ConditionMessage.Builder message = ConditionMessage - .forCondition(ConditionalOnRepositoryType.class); + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnRepositoryType.class); if (configuredType == requiredType || configuredType == RepositoryType.AUTO) { - return ConditionOutcome.match(message.because("configured type of '" - + configuredType.name() + "' matched required type")); + return ConditionOutcome + .match(message.because("configured type of '" + configuredType.name() + "' matched required type")); } - return ConditionOutcome - .noMatch(message.because("configured type (" + configuredType.name() - + ") did not match required type (" + requiredType.name() + ")")); + return ConditionOutcome.noMatch(message.because("configured type (" + configuredType.name() + + ") did not match required type (" + requiredType.name() + ")")); } private RepositoryType getTypeProperty(Environment environment, String store) { - return RepositoryType.valueOf(environment - .getProperty(String.format("spring.data.%s.repositories.type", store), - "auto") - .toUpperCase(Locale.ENGLISH)); + return RepositoryType + .valueOf(environment.getProperty(String.format("spring.data.%s.repositories.type", store), "auto") + .toUpperCase(Locale.ENGLISH)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java index 35bd1f0727d..58a2a145a21 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java @@ -69,16 +69,15 @@ public class CassandraDataAutoConfiguration { private final Cluster cluster; - public CassandraDataAutoConfiguration(CassandraProperties properties, - Cluster cluster) { + public CassandraDataAutoConfiguration(CassandraProperties properties, Cluster cluster) { this.properties = properties; this.cluster = cluster; } @Bean @ConditionalOnMissingBean - public CassandraMappingContext cassandraMapping(BeanFactory beanFactory, - CassandraCustomConversions conversions) throws ClassNotFoundException { + public CassandraMappingContext cassandraMapping(BeanFactory beanFactory, CassandraCustomConversions conversions) + throws ClassNotFoundException { CassandraMappingContext context = new CassandraMappingContext(); List packages = EntityScanPackages.get(beanFactory).getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(beanFactory)) { @@ -87,8 +86,8 @@ public class CassandraDataAutoConfiguration { if (!packages.isEmpty()) { context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages)); } - PropertyMapper.get().from(this.properties::getKeyspaceName).whenHasText() - .as(this::createSimpleUserTypeResolver).to(context::setUserTypeResolver); + PropertyMapper.get().from(this.properties::getKeyspaceName).whenHasText().as(this::createSimpleUserTypeResolver) + .to(context::setUserTypeResolver); context.setCustomConversions(conversions); return context; } @@ -108,22 +107,19 @@ public class CassandraDataAutoConfiguration { @Bean @ConditionalOnMissingBean(Session.class) - public CassandraSessionFactoryBean cassandraSession(Environment environment, - CassandraConverter converter) { + public CassandraSessionFactoryBean cassandraSession(Environment environment, CassandraConverter converter) { CassandraSessionFactoryBean session = new CassandraSessionFactoryBean(); session.setCluster(this.cluster); session.setConverter(converter); session.setKeyspaceName(this.properties.getKeyspaceName()); Binder binder = Binder.get(environment); - binder.bind("spring.data.cassandra.schema-action", SchemaAction.class) - .ifBound(session::setSchemaAction); + binder.bind("spring.data.cassandra.schema-action", SchemaAction.class).ifBound(session::setSchemaAction); return session; } @Bean @ConditionalOnMissingBean - public CassandraTemplate cassandraTemplate(Session session, - CassandraConverter converter) { + public CassandraTemplate cassandraTemplate(Session session, CassandraConverter converter) { return new CassandraTemplate(session, converter); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.java index d9272cd27f2..ead486f6832 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.java @@ -55,15 +55,14 @@ public class CassandraReactiveDataAutoConfiguration { } @Bean - public ReactiveSessionFactory reactiveCassandraSessionFactory( - ReactiveSession reactiveCassandraSession) { + public ReactiveSessionFactory reactiveCassandraSessionFactory(ReactiveSession reactiveCassandraSession) { return new DefaultReactiveSessionFactory(reactiveCassandraSession); } @Bean @ConditionalOnMissingBean - public ReactiveCassandraTemplate reactiveCassandraTemplate( - ReactiveSession reactiveCassandraSession, CassandraConverter converter) { + public ReactiveCassandraTemplate reactiveCassandraTemplate(ReactiveSession reactiveCassandraSession, + CassandraConverter converter) { return new ReactiveCassandraTemplate(reactiveCassandraSession, converter); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesRegistrar.java index 9069a30deb7..4ecd2e7ba1d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesRegistrar.java @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 2.0.0 */ -class CassandraReactiveRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CassandraReactiveRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesRegistrar.java index 6cb4137181b..f2ca652328a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesRegistrar.java @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 1.3.0 */ -class CassandraRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CassandraRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java index 2e0dff97cc0..40b49ec1293 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java @@ -44,10 +44,8 @@ class CouchbaseConfigurerAdapterConfiguration { @Bean @ConditionalOnMissingBean public CouchbaseConfigurer springBootCouchbaseConfigurer() throws Exception { - return new SpringBootCouchbaseConfigurer( - this.configuration.couchbaseEnvironment(), - this.configuration.couchbaseCluster(), - this.configuration.couchbaseClusterInfo(), + return new SpringBootCouchbaseConfigurer(this.configuration.couchbaseEnvironment(), + this.configuration.couchbaseCluster(), this.configuration.couchbaseClusterInfo(), this.configuration.couchbaseClient()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java index 788d4d5580f..940417d0d5a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java @@ -42,11 +42,9 @@ import org.springframework.data.couchbase.repository.CouchbaseRepository; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Bucket.class, CouchbaseRepository.class }) -@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, - ValidationAutoConfiguration.class }) +@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, ValidationAutoConfiguration.class }) @EnableConfigurationProperties(CouchbaseDataProperties.class) -@Import({ CouchbaseConfigurerAdapterConfiguration.class, - SpringBootCouchbaseDataConfiguration.class }) +@Import({ CouchbaseConfigurerAdapterConfiguration.class, SpringBootCouchbaseDataConfiguration.class }) public class CouchbaseDataAutoConfiguration { @Configuration(proxyBeanMethods = false) @@ -55,8 +53,7 @@ public class CouchbaseDataAutoConfiguration { @Bean @ConditionalOnSingleCandidate(Validator.class) - public ValidatingCouchbaseEventListener validationEventListener( - Validator validator) { + public ValidatingCouchbaseEventListener validationEventListener(Validator validator) { return new ValidatingCouchbaseEventListener(validator); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesRegistrar.java index 71040c5400d..ae31598905a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * * @author Alex Derkach */ -class CouchbaseReactiveRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CouchbaseReactiveRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java index 6d27bc6a04b..2264682c0b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * * @author Eddú Meléndez */ -class CouchbaseRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CouchbaseRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java index 66fee337606..c481162de19 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class SpringBootCouchbaseConfigurer implements CouchbaseConfigurer { private final Bucket bucket; - public SpringBootCouchbaseConfigurer(CouchbaseEnvironment env, Cluster cluster, - ClusterInfo clusterInfo, Bucket bucket) { + public SpringBootCouchbaseConfigurer(CouchbaseEnvironment env, Cluster cluster, ClusterInfo clusterInfo, + Bucket bucket) { this.env = env; this.cluster = cluster; this.clusterInfo = clusterInfo; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java index 3735eeb3514..1c1b1294255 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ class SpringBootCouchbaseDataConfiguration extends AbstractCouchbaseDataConfigur private final CouchbaseConfigurer couchbaseConfigurer; - SpringBootCouchbaseDataConfiguration(ApplicationContext applicationContext, - CouchbaseDataProperties properties, + SpringBootCouchbaseDataConfiguration(ApplicationContext applicationContext, CouchbaseDataProperties properties, ObjectProvider couchbaseConfigurer) { this.applicationContext = applicationContext; this.properties = properties; @@ -71,8 +70,7 @@ class SpringBootCouchbaseDataConfiguration extends AbstractCouchbaseDataConfigur @Override protected Set> getInitialEntitySet() throws ClassNotFoundException { - return new EntityScanner(this.applicationContext).scan(Document.class, - Persistent.class); + return new EntityScanner(this.applicationContext).scan(Document.class, Persistent.class); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseReactiveDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseReactiveDataConfiguration.java index 7e5702c0760..c763d3a3f22 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseReactiveDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseReactiveDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ import org.springframework.data.couchbase.repository.config.ReactiveRepositoryOp @Configuration @ConditionalOnMissingBean(AbstractReactiveCouchbaseDataConfiguration.class) @ConditionalOnBean(CouchbaseConfigurer.class) -class SpringBootCouchbaseReactiveDataConfiguration - extends AbstractReactiveCouchbaseDataConfiguration { +class SpringBootCouchbaseReactiveDataConfiguration extends AbstractReactiveCouchbaseDataConfiguration { private final CouchbaseDataProperties properties; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java index d1c24fa78cc..74736f9f1c4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java @@ -40,8 +40,7 @@ import org.springframework.data.elasticsearch.client.TransportClientFactoryBean; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Client.class, TransportClientFactoryBean.class }) -@ConditionalOnProperty(prefix = "spring.data.elasticsearch", name = "cluster-nodes", - matchIfMissing = false) +@ConditionalOnProperty(prefix = "spring.data.elasticsearch", name = "cluster-nodes", matchIfMissing = false) @EnableConfigurationProperties(ElasticsearchProperties.class) public class ElasticsearchAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java index 8cf642bfdd8..018da354082 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java @@ -42,8 +42,8 @@ import org.springframework.data.elasticsearch.repository.config.EnableReactiveEl */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ ElasticsearchTemplate.class }) -@AutoConfigureAfter({ ElasticsearchAutoConfiguration.class, - RestClientAutoConfiguration.class, ReactiveRestClientAutoConfiguration.class }) +@AutoConfigureAfter({ ElasticsearchAutoConfiguration.class, RestClientAutoConfiguration.class, + ReactiveRestClientAutoConfiguration.class }) @Import({ ElasticsearchDataConfiguration.BaseConfiguration.class, ElasticsearchDataConfiguration.TransportClientConfiguration.class, ElasticsearchDataConfiguration.RestClientConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataConfiguration.java index 4848eb74e1c..00adbace91f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataConfiguration.java @@ -56,8 +56,7 @@ abstract class ElasticsearchDataConfiguration { @Bean @ConditionalOnMissingBean - public ElasticsearchConverter elasticsearchConverter( - SimpleElasticsearchMappingContext mappingContext) { + public ElasticsearchConverter elasticsearchConverter(SimpleElasticsearchMappingContext mappingContext) { return new MappingElasticsearchConverter(mappingContext); } @@ -68,15 +67,13 @@ abstract class ElasticsearchDataConfiguration { } @Bean - public EntityMapper entityMapper( - SimpleElasticsearchMappingContext mappingContext) { + public EntityMapper entityMapper(SimpleElasticsearchMappingContext mappingContext) { return new DefaultEntityMapper(mappingContext); } @Bean @ConditionalOnMissingBean - public ResultsMapper resultsMapper( - SimpleElasticsearchMappingContext mappingContext, + public ResultsMapper resultsMapper(SimpleElasticsearchMappingContext mappingContext, EntityMapper entityMapper) { return new DefaultResultMapper(mappingContext, entityMapper); } @@ -88,8 +85,7 @@ abstract class ElasticsearchDataConfiguration { static class RestClientConfiguration { @Bean - @ConditionalOnMissingBean(value = ElasticsearchOperations.class, - name = "elasticsearchTemplate") + @ConditionalOnMissingBean(value = ElasticsearchOperations.class, name = "elasticsearchTemplate") @ConditionalOnBean(RestHighLevelClient.class) public ElasticsearchRestTemplate elasticsearchTemplate(RestHighLevelClient client, ElasticsearchConverter converter, ResultsMapper resultsMapper) { @@ -103,11 +99,10 @@ abstract class ElasticsearchDataConfiguration { static class TransportClientConfiguration { @Bean - @ConditionalOnMissingBean(value = ElasticsearchOperations.class, - name = "elasticsearchTemplate") + @ConditionalOnMissingBean(value = ElasticsearchOperations.class, name = "elasticsearchTemplate") @ConditionalOnBean(Client.class) - public ElasticsearchTemplate elasticsearchTemplate(Client client, - ElasticsearchConverter converter, ResultsMapper resultsMapper) { + public ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter, + ResultsMapper resultsMapper) { try { return new ElasticsearchTemplate(client, converter, resultsMapper); } @@ -123,14 +118,12 @@ abstract class ElasticsearchDataConfiguration { static class ReactiveRestClientConfiguration { @Bean - @ConditionalOnMissingBean(value = ReactiveElasticsearchOperations.class, - name = "reactiveElasticsearchTemplate") + @ConditionalOnMissingBean(value = ReactiveElasticsearchOperations.class, name = "reactiveElasticsearchTemplate") @ConditionalOnBean(ReactiveElasticsearchClient.class) - public ReactiveElasticsearchTemplate reactiveElasticsearchTemplate( - ReactiveElasticsearchClient client, ElasticsearchConverter converter, - ResultsMapper resultsMapper) { - ReactiveElasticsearchTemplate template = new ReactiveElasticsearchTemplate( - client, converter, resultsMapper); + public ReactiveElasticsearchTemplate reactiveElasticsearchTemplate(ReactiveElasticsearchClient client, + ElasticsearchConverter converter, ResultsMapper resultsMapper) { + ReactiveElasticsearchTemplate template = new ReactiveElasticsearchTemplate(client, converter, + resultsMapper); template.setIndicesOptions(IndicesOptions.strictExpandOpenAndForbidClosed()); template.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); return template; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java index a5522e6b101..709bc2e7d79 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java @@ -39,8 +39,8 @@ import org.springframework.data.elasticsearch.repository.support.ElasticsearchRe */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Client.class, ElasticsearchRepository.class }) -@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", - name = "enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(ElasticsearchRepositoryFactoryBean.class) @Import(ElasticsearchRepositoriesRegistrar.class) public class ElasticsearchRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java index 258ee559c5a..db5109e9552 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Mohsin Husen * @since 1.1.0 */ -class ElasticsearchRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class ElasticsearchRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfiguration.java index 811fc463f63..657b833214c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfiguration.java @@ -36,10 +36,9 @@ import org.springframework.data.elasticsearch.repository.support.ReactiveElastic * @since 2.2.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ ReactiveElasticsearchClient.class, - ReactiveElasticsearchRepository.class }) -@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", - name = "enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnClass({ ReactiveElasticsearchClient.class, ReactiveElasticsearchRepository.class }) +@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(ReactiveElasticsearchRepositoryFactoryBean.class) @Import(ReactiveElasticsearchRepositoriesRegistrar.class) public class ReactiveElasticsearchRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesRegistrar.java index c7bcfa8b416..54e03570315 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesRegistrar.java @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Brian Clozel * @since 2.2.0 */ -class ReactiveElasticsearchRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class ReactiveElasticsearchRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfiguration.java index 26a95f17ee8..8f2ff327be6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfiguration.java @@ -45,10 +45,9 @@ public class ReactiveRestClientAutoConfiguration { @Bean @ConditionalOnMissingBean - public ClientConfiguration clientConfiguration( - ReactiveRestClientProperties properties) { - ClientConfiguration.MaybeSecureClientConfigurationBuilder builder = ClientConfiguration - .builder().connectedTo(properties.getEndpoints().toArray(new String[0])); + public ClientConfiguration clientConfiguration(ReactiveRestClientProperties properties) { + ClientConfiguration.MaybeSecureClientConfigurationBuilder builder = ClientConfiguration.builder() + .connectedTo(properties.getEndpoints().toArray(new String[0])); if (properties.isUseSsl()) { builder.usingSsl(); } @@ -56,14 +55,11 @@ public class ReactiveRestClientAutoConfiguration { return builder.build(); } - private void configureTimeouts( - ClientConfiguration.TerminalClientConfigurationBuilder builder, + private void configureTimeouts(ClientConfiguration.TerminalClientConfigurationBuilder builder, ReactiveRestClientProperties properties) { PropertyMapper map = PropertyMapper.get(); - map.from(properties.getConnectionTimeout()).whenNonNull() - .to(builder::withConnectTimeout); - map.from(properties.getSocketTimeout()).whenNonNull() - .to(builder::withSocketTimeout); + map.from(properties.getConnectionTimeout()).whenNonNull().to(builder::withConnectTimeout); + map.from(properties.getSocketTimeout()).whenNonNull().to(builder::withSocketTimeout); map.from(properties.getUsername()).whenHasText().to((username) -> { HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth(username, properties.getPassword()); @@ -73,8 +69,7 @@ public class ReactiveRestClientAutoConfiguration { @Bean @ConditionalOnMissingBean - public ReactiveElasticsearchClient reactiveElasticsearchClient( - ClientConfiguration clientConfiguration) { + public ReactiveElasticsearchClient reactiveElasticsearchClient(ClientConfiguration clientConfiguration) { return ReactiveRestClients.create(clientConfiguration); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientProperties.java index e322db33565..56d80b10c52 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientProperties.java @@ -35,8 +35,7 @@ public class ReactiveRestClientProperties { /** * Comma-separated list of the Elasticsearch endpoints to connect to. */ - private List endpoints = new ArrayList<>( - Collections.singletonList("localhost:9200")); + private List endpoints = new ArrayList<>(Collections.singletonList("localhost:9200")); /** * Whether the client should use SSL to connect to the endpoints. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfiguration.java index 55e756b5a9d..da0e2c1a7ad 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfiguration.java @@ -45,10 +45,9 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; @SuppressWarnings("deprecation") @Configuration(proxyBeanMethods = false) @ConditionalOnBean(NamedParameterJdbcOperations.class) -@ConditionalOnClass({ NamedParameterJdbcOperations.class, - AbstractJdbcConfiguration.class }) -@ConditionalOnProperty(prefix = "spring.data.jdbc.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnClass({ NamedParameterJdbcOperations.class, AbstractJdbcConfiguration.class }) +@ConditionalOnProperty(prefix = "spring.data.jdbc.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @AutoConfigureAfter(JdbcTemplateAutoConfiguration.class) public class JdbcRepositoriesAutoConfiguration { @@ -60,8 +59,7 @@ public class JdbcRepositoriesAutoConfiguration { } @Configuration - @ConditionalOnMissingBean({ AbstractJdbcConfiguration.class, - JdbcConfiguration.class }) + @ConditionalOnMissingBean({ AbstractJdbcConfiguration.class, JdbcConfiguration.class }) static class SpringBootJdbcConfiguration extends AbstractJdbcConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java index d598940738d..baa90dc7dee 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,12 +34,10 @@ import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean; * @since 1.1.0 * @see BeanDefinition#setDependsOn(String[]) */ -public class EntityManagerFactoryDependsOnPostProcessor - extends AbstractDependsOnBeanFactoryPostProcessor { +public class EntityManagerFactoryDependsOnPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { public EntityManagerFactoryDependsOnPostProcessor(String... dependsOn) { - super(EntityManagerFactory.class, AbstractEntityManagerFactoryBean.class, - dependsOn); + super(EntityManagerFactory.class, AbstractEntityManagerFactoryBean.class, dependsOn); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java index 431fc3a0728..02d6ee8cf16 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java @@ -61,13 +61,11 @@ import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; @Configuration(proxyBeanMethods = false) @ConditionalOnBean(DataSource.class) @ConditionalOnClass(JpaRepository.class) -@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class, - JpaRepositoryConfigExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class, JpaRepositoryConfigExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(JpaRepositoriesRegistrar.class) -@AutoConfigureAfter({ HibernateJpaAutoConfiguration.class, - TaskExecutionAutoConfiguration.class }) +@AutoConfigureAfter({ HibernateJpaAutoConfiguration.class, TaskExecutionAutoConfiguration.class }) public class JpaRepositoriesAutoConfiguration { @Bean @@ -75,21 +73,18 @@ public class JpaRepositoriesAutoConfiguration { public EntityManagerFactoryBuilderCustomizer entityManagerFactoryBootstrapExecutorCustomizer( Map taskExecutors) { return (builder) -> { - AsyncTaskExecutor bootstrapExecutor = determineBootstrapExecutor( - taskExecutors); + AsyncTaskExecutor bootstrapExecutor = determineBootstrapExecutor(taskExecutors); if (bootstrapExecutor != null) { builder.setBootstrapExecutor(bootstrapExecutor); } }; } - private AsyncTaskExecutor determineBootstrapExecutor( - Map taskExecutors) { + private AsyncTaskExecutor determineBootstrapExecutor(Map taskExecutors) { if (taskExecutors.size() == 1) { return taskExecutors.values().iterator().next(); } - return taskExecutors - .get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); + return taskExecutors.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); } private static final class BootstrapExecutorCondition extends AnyNestedCondition { @@ -98,14 +93,14 @@ public class JpaRepositoriesAutoConfiguration { super(ConfigurationPhase.REGISTER_BEAN); } - @ConditionalOnProperty(prefix = "spring.data.jpa.repositories", - name = "bootstrap-mode", havingValue = "deferred", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "bootstrap-mode", + havingValue = "deferred", matchIfMissing = false) static class DeferredBootstrapMode { } - @ConditionalOnProperty(prefix = "spring.data.jpa.repositories", - name = "bootstrap-mode", havingValue = "lazy", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "bootstrap-mode", havingValue = "lazy", + matchIfMissing = false) static class LazyBootstrapMode { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesRegistrar.java index 13a93164c3f..ddc5919ec6b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesRegistrar.java @@ -56,8 +56,7 @@ class JpaRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupp @Override protected BootstrapMode getBootstrapMode() { - return (this.bootstrapMode == null) ? super.getBootstrapMode() - : this.bootstrapMode; + return (this.bootstrapMode == null) ? super.getBootstrapMode() : this.bootstrapMode; } @Override @@ -67,11 +66,9 @@ class JpaRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupp } private void configureBootstrapMode(Environment environment) { - String property = environment - .getProperty("spring.data.jpa.repositories.bootstrap-mode"); + String property = environment.getProperty("spring.data.jpa.repositories.bootstrap-mode"); if (StringUtils.hasText(property)) { - this.bootstrapMode = BootstrapMode - .valueOf(property.toUpperCase(Locale.ENGLISH)); + this.bootstrapMode = BootstrapMode.valueOf(property.toUpperCase(Locale.ENGLISH)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java index 62d0e754a25..bc67a1157b7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java @@ -35,8 +35,8 @@ import org.springframework.data.ldap.repository.support.LdapRepositoryFactoryBea */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ LdapContext.class, LdapRepository.class }) -@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(LdapRepositoryFactoryBean.class) @Import(LdapRepositoriesRegistrar.class) public class LdapRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java index fe8f7d0eb1c..89e1e0e6cb7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import org.springframework.data.mongodb.core.MongoClientFactoryBean; * @since 1.3.0 */ @Order(Ordered.LOWEST_PRECEDENCE) -public class MongoClientDependsOnBeanFactoryPostProcessor - extends AbstractDependsOnBeanFactoryPostProcessor { +public class MongoClientDependsOnBeanFactoryPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { public MongoClientDependsOnBeanFactoryPostProcessor(String... dependsOn) { super(MongoClient.class, MongoClientFactoryBean.class, dependsOn); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java index 03d66c06b91..87e6d29dd7c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java @@ -73,8 +73,7 @@ import org.springframework.util.StringUtils; * @since 1.1.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ MongoClient.class, com.mongodb.client.MongoClient.class, - MongoTemplate.class }) +@ConditionalOnClass({ MongoClient.class, com.mongodb.client.MongoClient.class, MongoTemplate.class }) @Conditional(AnyMongoClientAvailable.class) @EnableConfigurationProperties(MongoProperties.class) @Import(MongoDataConfiguration.class) @@ -93,41 +92,35 @@ public class MongoDataAutoConfiguration { ObjectProvider mongoClient) { MongoClient preferredClient = mongo.getIfAvailable(); if (preferredClient != null) { - return new SimpleMongoDbFactory(preferredClient, - this.properties.getMongoClientDatabase()); + return new SimpleMongoDbFactory(preferredClient, this.properties.getMongoClientDatabase()); } com.mongodb.client.MongoClient fallbackClient = mongoClient.getIfAvailable(); if (fallbackClient != null) { - return new SimpleMongoClientDbFactory(fallbackClient, - this.properties.getMongoClientDatabase()); + return new SimpleMongoClientDbFactory(fallbackClient, this.properties.getMongoClientDatabase()); } throw new IllegalStateException("Expected to find at least one MongoDB client."); } @Bean @ConditionalOnMissingBean - public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, - MongoConverter converter) { + public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter converter) { return new MongoTemplate(mongoDbFactory, converter); } @Bean @ConditionalOnMissingBean(MongoConverter.class) - public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, - MongoMappingContext context, MongoCustomConversions conversions) { + public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, + MongoCustomConversions conversions) { DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory); - MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, - context); + MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context); mappingConverter.setCustomConversions(conversions); return mappingConverter; } @Bean @ConditionalOnMissingBean - public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, - MongoTemplate mongoTemplate) { - return new GridFsTemplate( - new GridFsMongoDbFactory(mongoDbFactory, this.properties), + public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate) { + return new GridFsTemplate(new GridFsMongoDbFactory(mongoDbFactory, this.properties), mongoTemplate.getConverter()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataConfiguration.java index 3bf8988ad2b..5bdd69f12ce 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataConfiguration.java @@ -42,18 +42,15 @@ class MongoDataConfiguration { @Bean @ConditionalOnMissingBean - public MongoMappingContext mongoMappingContext(ApplicationContext applicationContext, - MongoProperties properties, MongoCustomConversions conversions) - throws ClassNotFoundException { + public MongoMappingContext mongoMappingContext(ApplicationContext applicationContext, MongoProperties properties, + MongoCustomConversions conversions) throws ClassNotFoundException { PropertyMapper mapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); MongoMappingContext context = new MongoMappingContext(); mapper.from(properties.isAutoIndexCreation()).to(context::setAutoIndexCreation); - context.setInitialEntitySet(new EntityScanner(applicationContext) - .scan(Document.class, Persistent.class)); + context.setInitialEntitySet(new EntityScanner(applicationContext).scan(Document.class, Persistent.class)); Class strategyClass = properties.getFieldNamingStrategy(); if (strategyClass != null) { - context.setFieldNamingStrategy( - (FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass)); + context.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass)); } context.setSimpleTypeHolder(conversions.getSimpleTypeHolder()); return context; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.java index 558de32cd62..469b76a1513 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.java @@ -65,16 +65,15 @@ public class MongoReactiveDataAutoConfiguration { @Bean @ConditionalOnMissingBean(ReactiveMongoDatabaseFactory.class) - public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory( - MongoProperties properties, MongoClient mongo) { + public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory(MongoProperties properties, + MongoClient mongo) { String database = properties.getMongoClientDatabase(); return new SimpleReactiveMongoDatabaseFactory(mongo, database); } @Bean @ConditionalOnMissingBean - public ReactiveMongoTemplate reactiveMongoTemplate( - ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory, + public ReactiveMongoTemplate reactiveMongoTemplate(ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory, MongoConverter converter) { return new ReactiveMongoTemplate(reactiveMongoDatabaseFactory, converter); } @@ -83,8 +82,7 @@ public class MongoReactiveDataAutoConfiguration { @ConditionalOnMissingBean(MongoConverter.class) public MappingMongoConverter mappingMongoConverter(MongoMappingContext context, MongoCustomConversions conversions) { - MappingMongoConverter mappingConverter = new MappingMongoConverter( - NoOpDbRefResolver.INSTANCE, context); + MappingMongoConverter mappingConverter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, context); mappingConverter.setCustomConversions(conversions); return mappingConverter; } @@ -97,12 +95,9 @@ public class MongoReactiveDataAutoConfiguration { @Bean @ConditionalOnMissingBean - public ReactiveGridFsTemplate reactiveGridFsTemplate( - ReactiveMongoDatabaseFactory reactiveMongoDbFactory, - MappingMongoConverter mappingMongoConverter, - DataBufferFactory dataBufferFactory) { - return new ReactiveGridFsTemplate(dataBufferFactory, reactiveMongoDbFactory, - mappingMongoConverter, null); + public ReactiveGridFsTemplate reactiveGridFsTemplate(ReactiveMongoDatabaseFactory reactiveMongoDbFactory, + MappingMongoConverter mappingMongoConverter, DataBufferFactory dataBufferFactory) { + return new ReactiveGridFsTemplate(dataBufferFactory, reactiveMongoDbFactory, mappingMongoConverter, null); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesRegistrar.java index 7c77cf0f10b..c446b3e6a71 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesRegistrar.java @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Mark Paluch * @since 2.0.0 */ -class MongoReactiveRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class MongoReactiveRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java index fa83b8dc72b..12cba671217 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java @@ -52,8 +52,7 @@ import org.springframework.data.mongodb.repository.support.MongoRepositoryFactor */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ MongoClient.class, MongoRepository.class }) -@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, - MongoRepositoryConfigurationExtension.class }) +@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, MongoRepositoryConfigurationExtension.class }) @ConditionalOnRepositoryType(store = "mongodb", type = RepositoryType.IMPERATIVE) @Import(MongoRepositoriesRegistrar.class) @AutoConfigureAfter(MongoDataAutoConfiguration.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor.java index f0141860cfc..50b5aa5d87d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.data.mongodb.core.ReactiveMongoClientFactoryBean; public class ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { - public ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor( - String... dependsOn) { + public ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor(String... dependsOn) { super(MongoClient.class, ReactiveMongoClientFactoryBean.class, dependsOn); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jBookmarkManagementConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jBookmarkManagementConfiguration.java index 7ff23c2770b..c5b66018bee 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jBookmarkManagementConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jBookmarkManagementConfiguration.java @@ -44,16 +44,14 @@ import org.springframework.web.context.WebApplicationContext; @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Caffeine.class, CaffeineCacheManager.class }) @ConditionalOnMissingBean(BookmarkManager.class) -@ConditionalOnBean({ BeanFactoryBookmarkOperationAdvisor.class, - BookmarkInterceptor.class }) +@ConditionalOnBean({ BeanFactoryBookmarkOperationAdvisor.class, BookmarkInterceptor.class }) class Neo4jBookmarkManagementConfiguration { private static final String BOOKMARK_MANAGER_BEAN_NAME = "bookmarkManager"; @Bean(BOOKMARK_MANAGER_BEAN_NAME) @ConditionalOnWebApplication - @Scope(value = WebApplicationContext.SCOPE_REQUEST, - proxyMode = ScopedProxyMode.INTERFACES) + @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.INTERFACES) public BookmarkManager requestScopedBookmarkManager() { return new CaffeineBookmarkManager(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java index 288147eb436..c892385ca3a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java @@ -56,8 +56,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @since 1.4.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, - PlatformTransactionManager.class }) +@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, PlatformTransactionManager.class }) @ConditionalOnMissingBean(SessionFactory.class) @EnableConfigurationProperties(Neo4jProperties.class) @Import(Neo4jBookmarkManagementConfiguration.class) @@ -71,21 +70,17 @@ public class Neo4jDataAutoConfiguration { @Bean public SessionFactory sessionFactory(org.neo4j.ogm.config.Configuration configuration, - ApplicationContext applicationContext, - ObjectProvider eventListeners) { - SessionFactory sessionFactory = new SessionFactory(configuration, - getPackagesToScan(applicationContext)); + ApplicationContext applicationContext, ObjectProvider eventListeners) { + SessionFactory sessionFactory = new SessionFactory(configuration, getPackagesToScan(applicationContext)); eventListeners.stream().forEach(sessionFactory::register); return sessionFactory; } @Bean @ConditionalOnMissingBean(PlatformTransactionManager.class) - public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory, - Neo4jProperties properties, + public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory, Neo4jProperties properties, ObjectProvider transactionManagerCustomizers) { - return customize(new Neo4jTransactionManager(sessionFactory), - transactionManagerCustomizers.getIfAvailable()); + return customize(new Neo4jTransactionManager(sessionFactory), transactionManagerCustomizers.getIfAvailable()); } private Neo4jTransactionManager customize(Neo4jTransactionManager transactionManager, @@ -97,8 +92,7 @@ public class Neo4jDataAutoConfiguration { } private String[] getPackagesToScan(ApplicationContext applicationContext) { - List packages = EntityScanPackages.get(applicationContext) - .getPackageNames(); + List packages = EntityScanPackages.get(applicationContext).getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(applicationContext)) { packages = AutoConfigurationPackages.get(applicationContext); } @@ -109,8 +103,8 @@ public class Neo4jDataAutoConfiguration { @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ WebMvcConfigurer.class, OpenSessionInViewInterceptor.class }) @ConditionalOnMissingBean(OpenSessionInViewInterceptor.class) - @ConditionalOnProperty(prefix = "spring.data.neo4j", name = "open-in-view", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.data.neo4j", name = "open-in-view", havingValue = "true", + matchIfMissing = true) protected static class Neo4jWebConfiguration { private static final Log logger = LogFactory.getLog(Neo4jWebConfiguration.class); @@ -133,8 +127,7 @@ public class Neo4jDataAutoConfiguration { } @Bean - public WebMvcConfigurer neo4jOpenSessionInViewInterceptorConfigurer( - OpenSessionInViewInterceptor interceptor) { + public WebMvcConfigurer neo4jOpenSessionInViewInterceptorConfigurer(OpenSessionInViewInterceptor interceptor) { return new WebMvcConfigurer() { @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java index fde57b36365..7eff8e1289b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java @@ -166,8 +166,7 @@ public class Neo4jProperties implements ApplicationContextAware { } private void configureUriWithDefaults(Builder builder) { - if (!getEmbedded().isEnabled() - || !ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) { + if (!getEmbedded().isEnabled() || !ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) { builder.uri(DEFAULT_BOLT_URI); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java index 0e93c50e17e..54de8aaa2f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java @@ -50,10 +50,9 @@ import org.springframework.data.neo4j.repository.support.Neo4jRepositoryFactoryB */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Neo4jSession.class, Neo4jRepository.class }) -@ConditionalOnMissingBean({ Neo4jRepositoryFactoryBean.class, - Neo4jRepositoryConfigurationExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.neo4j.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ Neo4jRepositoryFactoryBean.class, Neo4jRepositoryConfigurationExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.neo4j.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(Neo4jRepositoriesRegistrar.class) @AutoConfigureAfter(Neo4jDataAutoConfiguration.class) public class Neo4jRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/JedisConnectionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/JedisConnectionConfiguration.java index 261e6d1262c..8a02384d66c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/JedisConnectionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/JedisConnectionConfiguration.java @@ -56,29 +56,25 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { @Bean @ConditionalOnMissingBean(RedisConnectionFactory.class) public JedisConnectionFactory redisConnectionFactory( - ObjectProvider builderCustomizers) - throws UnknownHostException { + ObjectProvider builderCustomizers) throws UnknownHostException { return createJedisConnectionFactory(builderCustomizers); } private JedisConnectionFactory createJedisConnectionFactory( ObjectProvider builderCustomizers) { - JedisClientConfiguration clientConfiguration = getJedisClientConfiguration( - builderCustomizers); + JedisClientConfiguration clientConfiguration = getJedisClientConfiguration(builderCustomizers); if (getSentinelConfig() != null) { return new JedisConnectionFactory(getSentinelConfig(), clientConfiguration); } if (getClusterConfiguration() != null) { - return new JedisConnectionFactory(getClusterConfiguration(), - clientConfiguration); + return new JedisConnectionFactory(getClusterConfiguration(), clientConfiguration); } return new JedisConnectionFactory(getStandaloneConfig(), clientConfiguration); } private JedisClientConfiguration getJedisClientConfiguration( ObjectProvider builderCustomizers) { - JedisClientConfigurationBuilder builder = applyProperties( - JedisClientConfiguration.builder()); + JedisClientConfigurationBuilder builder = applyProperties(JedisClientConfiguration.builder()); RedisProperties.Pool pool = getProperties().getJedis().getPool(); if (pool != null) { applyPooling(pool, builder); @@ -86,13 +82,11 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { if (StringUtils.hasText(getProperties().getUrl())) { customizeConfigurationFromUrl(builder); } - builderCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder.build(); } - private JedisClientConfigurationBuilder applyProperties( - JedisClientConfigurationBuilder builder) { + private JedisClientConfigurationBuilder applyProperties(JedisClientConfigurationBuilder builder) { if (getProperties().isSsl()) { builder.useSsl(); } @@ -114,8 +108,7 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { config.setMaxIdle(pool.getMaxIdle()); config.setMinIdle(pool.getMinIdle()); if (pool.getTimeBetweenEvictionRuns() != null) { - config.setTimeBetweenEvictionRunsMillis( - pool.getTimeBetweenEvictionRuns().toMillis()); + config.setTimeBetweenEvictionRunsMillis(pool.getTimeBetweenEvictionRuns().toMillis()); } if (pool.getMaxWait() != null) { config.setMaxWaitMillis(pool.getMaxWait().toMillis()); @@ -123,8 +116,7 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { return config; } - private void customizeConfigurationFromUrl( - JedisClientConfiguration.JedisClientConfigurationBuilder builder) { + private void customizeConfigurationFromUrl(JedisClientConfiguration.JedisClientConfigurationBuilder builder) { ConnectionInfo connectionInfo = parseUrl(getProperties().getUrl()); if (connectionInfo.isUseSsl()) { builder.useSsl(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java index 7fc5902d0cd..ce6642dc6e4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java @@ -65,20 +65,17 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { public LettuceConnectionFactory redisConnectionFactory( ObjectProvider builderCustomizers, ClientResources clientResources) throws UnknownHostException { - LettuceClientConfiguration clientConfig = getLettuceClientConfiguration( - builderCustomizers, clientResources, + LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(builderCustomizers, clientResources, getProperties().getLettuce().getPool()); return createLettuceConnectionFactory(clientConfig); } - private LettuceConnectionFactory createLettuceConnectionFactory( - LettuceClientConfiguration clientConfiguration) { + private LettuceConnectionFactory createLettuceConnectionFactory(LettuceClientConfiguration clientConfiguration) { if (getSentinelConfig() != null) { return new LettuceConnectionFactory(getSentinelConfig(), clientConfiguration); } if (getClusterConfiguration() != null) { - return new LettuceConnectionFactory(getClusterConfiguration(), - clientConfiguration); + return new LettuceConnectionFactory(getClusterConfiguration(), clientConfiguration); } return new LettuceConnectionFactory(getStandaloneConfig(), clientConfiguration); } @@ -92,8 +89,7 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { customizeConfigurationFromUrl(builder); } builder.clientResources(clientResources); - builderCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder.build(); } @@ -114,17 +110,14 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { } if (getProperties().getLettuce() != null) { RedisProperties.Lettuce lettuce = getProperties().getLettuce(); - if (lettuce.getShutdownTimeout() != null - && !lettuce.getShutdownTimeout().isZero()) { - builder.shutdownTimeout( - getProperties().getLettuce().getShutdownTimeout()); + if (lettuce.getShutdownTimeout() != null && !lettuce.getShutdownTimeout().isZero()) { + builder.shutdownTimeout(getProperties().getLettuce().getShutdownTimeout()); } } return builder; } - private void customizeConfigurationFromUrl( - LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { + private void customizeConfigurationFromUrl(LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { ConnectionInfo connectionInfo = parseUrl(getProperties().getUrl()); if (connectionInfo.isUseSsl()) { builder.useSsl(); @@ -137,8 +130,7 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { private static class PoolBuilderFactory { public LettuceClientConfigurationBuilder createBuilder(Pool properties) { - return LettucePoolingClientConfiguration.builder() - .poolConfig(getPoolConfig(properties)); + return LettucePoolingClientConfiguration.builder().poolConfig(getPoolConfig(properties)); } private GenericObjectPoolConfig getPoolConfig(Pool properties) { @@ -147,8 +139,7 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { config.setMaxIdle(properties.getMaxIdle()); config.setMinIdle(properties.getMinIdle()); if (properties.getTimeBetweenEvictionRuns() != null) { - config.setTimeBetweenEvictionRunsMillis( - properties.getTimeBetweenEvictionRuns().toMillis()); + config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis()); } if (properties.getMaxWait() != null) { config.setMaxWaitMillis(properties.getMaxWait().toMillis()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java index 606892b3ac1..e8d85756f9c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java @@ -51,8 +51,8 @@ public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") - public RedisTemplate redisTemplate( - RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { + public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) + throws UnknownHostException { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); return template; @@ -60,8 +60,8 @@ public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean - public StringRedisTemplate stringRedisTemplate( - RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { + public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) + throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisConnectionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisConnectionConfiguration.java index 1cafdd93600..8665da70eff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisConnectionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisConnectionConfiguration.java @@ -100,8 +100,7 @@ abstract class RedisConnectionConfiguration { return null; } RedisProperties.Cluster clusterProperties = this.properties.getCluster(); - RedisClusterConfiguration config = new RedisClusterConfiguration( - clusterProperties.getNodes()); + RedisClusterConfiguration config = new RedisClusterConfiguration(clusterProperties.getNodes()); if (clusterProperties.getMaxRedirects() != null) { config.setMaxRedirects(clusterProperties.getMaxRedirects()); } @@ -124,8 +123,7 @@ abstract class RedisConnectionConfiguration { nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1]))); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Invalid redis sentinel " + "property '" + node + "'", ex); + throw new IllegalStateException("Invalid redis sentinel " + "property '" + node + "'", ex); } } return nodes; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java index 6be5d1a2e05..92662cd83b5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java @@ -41,8 +41,7 @@ import org.springframework.data.redis.serializer.RedisSerializationContext; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ ReactiveRedisConnectionFactory.class, ReactiveRedisTemplate.class, - Flux.class }) +@ConditionalOnClass({ ReactiveRedisConnectionFactory.class, ReactiveRedisTemplate.class, Flux.class }) @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisReactiveAutoConfiguration { @@ -50,15 +49,13 @@ public class RedisReactiveAutoConfiguration { @ConditionalOnMissingBean(name = "reactiveRedisTemplate") @ConditionalOnBean(ReactiveRedisConnectionFactory.class) public ReactiveRedisTemplate reactiveRedisTemplate( - ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, - ResourceLoader resourceLoader) { + ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, ResourceLoader resourceLoader) { JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer( resourceLoader.getClassLoader()); RedisSerializationContext serializationContext = RedisSerializationContext - .newSerializationContext().key(jdkSerializer).value(jdkSerializer) - .hashKey(jdkSerializer).hashValue(jdkSerializer).build(); - return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, - serializationContext); + .newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer) + .hashValue(jdkSerializer).build(); + return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java index dfab9a07621..2faee920edf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java @@ -40,8 +40,8 @@ import org.springframework.data.redis.repository.support.RedisRepositoryFactoryB @Configuration(proxyBeanMethods = false) @ConditionalOnClass(EnableRedisRepositories.class) @ConditionalOnBean(RedisConnectionFactory.class) -@ConditionalOnProperty(prefix = "spring.data.redis.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.redis.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(RedisRepositoryFactoryBean.class) @Import(RedisRepositoriesRegistrar.class) @AutoConfigureAfter(RedisAutoConfiguration.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java index 94a74f21fe2..1383c41d318 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguratio @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnMissingBean(RepositoryRestMvcConfiguration.class) @ConditionalOnClass(RepositoryRestMvcConfiguration.class) -@AutoConfigureAfter({ HttpMessageConvertersAutoConfiguration.class, - JacksonAutoConfiguration.class }) +@AutoConfigureAfter({ HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class }) @EnableConfigurationProperties(RepositoryRestProperties.class) @Import(RepositoryRestMvcConfiguration.class) public class RepositoryRestMvcAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java index 4918ef4c7ca..d90b176f4f8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java @@ -44,10 +44,9 @@ import org.springframework.data.solr.repository.support.SolrRepositoryFactoryBea */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SolrClient.class, SolrRepository.class }) -@ConditionalOnMissingBean({ SolrRepositoryFactoryBean.class, - SolrRepositoryConfigExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.solr.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ SolrRepositoryFactoryBean.class, SolrRepositoryConfigExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.solr.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(SolrRepositoriesRegistrar.class) public class SolrRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java index cdb620a1a48..1152f04fd07 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java @@ -48,8 +48,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration(proxyBeanMethods = false) @EnableSpringDataWebSupport @ConditionalOnWebApplication(type = Type.SERVLET) -@ConditionalOnClass({ PageableHandlerMethodArgumentResolver.class, - WebMvcConfigurer.class }) +@ConditionalOnClass({ PageableHandlerMethodArgumentResolver.class, WebMvcConfigurer.class }) @ConditionalOnMissingBean(PageableHandlerMethodArgumentResolver.class) @EnableConfigurationProperties(SpringDataWebProperties.class) @AutoConfigureAfter(RepositoryRestMvcAutoConfiguration.class) @@ -71,8 +70,7 @@ public class SpringDataWebAutoConfiguration { resolver.setOneIndexedParameters(pageable.isOneIndexedParameters()); resolver.setPrefix(pageable.getPrefix()); resolver.setQualifierDelimiter(pageable.getQualifierDelimiter()); - resolver.setFallbackPageable( - PageRequest.of(0, pageable.getDefaultPageSize())); + resolver.setFallbackPageable(PageRequest.of(0, pageable.getDefaultPageSize())); resolver.setMaxPageSize(pageable.getMaxPageSize()); }; } @@ -80,8 +78,7 @@ public class SpringDataWebAutoConfiguration { @Bean @ConditionalOnMissingBean public SortHandlerMethodArgumentResolverCustomizer sortCustomizer() { - return (resolver) -> resolver - .setSortParameter(this.properties.getSort().getSortParameter()); + return (resolver) -> resolver.setSortParameter(this.properties.getSort().getSortParameter()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java index 9700bf473da..9ef5fbc8871 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,7 @@ import org.springframework.util.ClassUtils; * @author Stephane Nicoll * @author Phillip Webb */ -class NoSuchBeanDefinitionFailureAnalyzer - extends AbstractInjectionFailureAnalyzer +class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyzer implements BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @@ -71,37 +70,30 @@ class NoSuchBeanDefinitionFailureAnalyzer public void setBeanFactory(BeanFactory beanFactory) throws BeansException { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; - this.metadataReaderFactory = new CachingMetadataReaderFactory( - this.beanFactory.getBeanClassLoader()); + this.metadataReaderFactory = new CachingMetadataReaderFactory(this.beanFactory.getBeanClassLoader()); // Get early as won't be accessible once context has failed to start this.report = ConditionEvaluationReport.get(this.beanFactory); } @Override - protected FailureAnalysis analyze(Throwable rootFailure, - NoSuchBeanDefinitionException cause, String description) { + protected FailureAnalysis analyze(Throwable rootFailure, NoSuchBeanDefinitionException cause, String description) { if (cause.getNumberOfBeansFound() != 0) { return null; } - List autoConfigurationResults = getAutoConfigurationResults( - cause); - List userConfigurationResults = getUserConfigurationResults( - cause); + List autoConfigurationResults = getAutoConfigurationResults(cause); + List userConfigurationResults = getUserConfigurationResults(cause); StringBuilder message = new StringBuilder(); message.append(String.format("%s required %s that could not be found.%n", - (description != null) ? description : "A component", - getBeanDescription(cause))); + (description != null) ? description : "A component", getBeanDescription(cause))); List injectionAnnotations = findInjectionAnnotations(rootFailure); if (!injectionAnnotations.isEmpty()) { - message.append(String - .format("%nThe injection point has the following annotations:%n")); + message.append(String.format("%nThe injection point has the following annotations:%n")); for (Annotation injectionAnnotation : injectionAnnotations) { message.append(String.format("\t- %s%n", injectionAnnotation)); } } if (!autoConfigurationResults.isEmpty() || !userConfigurationResults.isEmpty()) { - message.append(String.format( - "%nThe following candidates were found but could not be injected:%n")); + message.append(String.format("%nThe following candidates were found but could not be injected:%n")); for (AutoConfigurationResult result : autoConfigurationResults) { message.append(String.format("\t- %s%n", result)); } @@ -110,9 +102,8 @@ class NoSuchBeanDefinitionFailureAnalyzer } } String action = String.format("Consider %s %s in your configuration.", - (!autoConfigurationResults.isEmpty() - || !userConfigurationResults.isEmpty()) - ? "revisiting the entries above or defining" : "defining", + (!autoConfigurationResults.isEmpty() || !userConfigurationResults.isEmpty()) + ? "revisiting the entries above or defining" : "defining", getBeanDescription(cause)); return new FailureAnalysis(message.toString(), action, cause); } @@ -129,25 +120,21 @@ class NoSuchBeanDefinitionFailureAnalyzer return resolvableType.getRawClass(); } - private List getAutoConfigurationResults( - NoSuchBeanDefinitionException cause) { + private List getAutoConfigurationResults(NoSuchBeanDefinitionException cause) { List results = new ArrayList<>(); collectReportedConditionOutcomes(cause, results); collectExcludedAutoConfiguration(cause, results); return results; } - private List getUserConfigurationResults( - NoSuchBeanDefinitionException cause) { + private List getUserConfigurationResults(NoSuchBeanDefinitionException cause) { ResolvableType type = cause.getResolvableType(); if (type == null) { return Collections.emptyList(); } - String[] beanNames = BeanFactoryUtils - .beanNamesForTypeIncludingAncestors(this.beanFactory, type); + String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, type); return Arrays.stream(beanNames) - .map((beanName) -> new UserConfigurationResult( - getFactoryMethodMetadata(beanName), + .map((beanName) -> new UserConfigurationResult(getFactoryMethodMetadata(beanName), this.beanFactory.getBean(beanName).equals(null))) .collect(Collectors.toList()); } @@ -162,14 +149,13 @@ class NoSuchBeanDefinitionFailureAnalyzer private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, List results) { - this.report.getConditionAndOutcomesBySource().forEach( - (source, sourceOutcomes) -> collectReportedConditionOutcomes(cause, - new Source(source), sourceOutcomes, results)); + this.report.getConditionAndOutcomesBySource() + .forEach((source, sourceOutcomes) -> collectReportedConditionOutcomes(cause, new Source(source), + sourceOutcomes, results)); } - private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, - Source source, ConditionAndOutcomes sourceOutcomes, - List results) { + private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, Source source, + ConditionAndOutcomes sourceOutcomes, List results) { if (sourceOutcomes.isFullMatch()) { return; } @@ -177,8 +163,7 @@ class NoSuchBeanDefinitionFailureAnalyzer for (ConditionAndOutcome conditionAndOutcome : sourceOutcomes) { if (!conditionAndOutcome.getOutcome().isMatch()) { for (MethodMetadata method : methods) { - results.add(new AutoConfigurationResult(method, - conditionAndOutcome.getOutcome())); + results.add(new AutoConfigurationResult(method, conditionAndOutcome.getOutcome())); } } } @@ -192,8 +177,7 @@ class NoSuchBeanDefinitionFailureAnalyzer for (MethodMetadata method : methods) { String message = String.format("auto-configuration '%s' was excluded", ClassUtils.getShortName(excludedClass)); - results.add(new AutoConfigurationResult(method, - new ConditionOutcome(false, message))); + results.add(new AutoConfigurationResult(method, new ConditionOutcome(false, message))); } } } @@ -204,8 +188,7 @@ class NoSuchBeanDefinitionFailureAnalyzer if (unsatisfiedDependencyException == null) { return Collections.emptyList(); } - return Arrays.asList( - unsatisfiedDependencyException.getInjectionPoint().getAnnotations()); + return Arrays.asList(unsatisfiedDependencyException.getInjectionPoint().getAnnotations()); } private class Source { @@ -238,8 +221,7 @@ class NoSuchBeanDefinitionFailureAnalyzer this.methods = findBeanMethods(source, cause); } - private List findBeanMethods(Source source, - NoSuchBeanDefinitionException cause) { + private List findBeanMethods(Source source, NoSuchBeanDefinitionException cause) { try { MetadataReader classMetadata = NoSuchBeanDefinitionFailureAnalyzer.this.metadataReaderFactory .getMetadataReader(source.getClassName()); @@ -258,23 +240,19 @@ class NoSuchBeanDefinitionFailureAnalyzer } } - private boolean isMatch(MethodMetadata candidate, Source source, - NoSuchBeanDefinitionException cause) { - if (source.getMethodName() != null - && !source.getMethodName().equals(candidate.getMethodName())) { + private boolean isMatch(MethodMetadata candidate, Source source, NoSuchBeanDefinitionException cause) { + if (source.getMethodName() != null && !source.getMethodName().equals(candidate.getMethodName())) { return false; } String name = cause.getBeanName(); ResolvableType resolvableType = cause.getResolvableType(); - return ((name != null && hasName(candidate, name)) || (resolvableType != null - && hasType(candidate, extractBeanType(resolvableType)))); + return ((name != null && hasName(candidate, name)) + || (resolvableType != null && hasType(candidate, extractBeanType(resolvableType)))); } private boolean hasName(MethodMetadata methodMetadata, String name) { - Map attributes = methodMetadata - .getAnnotationAttributes(Bean.class.getName()); - String[] candidates = (attributes != null) ? (String[]) attributes.get("name") - : null; + Map attributes = methodMetadata.getAnnotationAttributes(Bean.class.getName()); + String[] candidates = (attributes != null) ? (String[]) attributes.get("name") : null; if (candidates != null) { for (String candidate : candidates) { if (candidate.equals(name)) { @@ -293,8 +271,7 @@ class NoSuchBeanDefinitionFailureAnalyzer } try { Class returnType = ClassUtils.forName(returnTypeName, - NoSuchBeanDefinitionFailureAnalyzer.this.beanFactory - .getBeanClassLoader()); + NoSuchBeanDefinitionFailureAnalyzer.this.beanFactory.getBeanClassLoader()); return type.isAssignableFrom(returnType); } catch (Throwable ex) { @@ -315,16 +292,14 @@ class NoSuchBeanDefinitionFailureAnalyzer private final ConditionOutcome conditionOutcome; - AutoConfigurationResult(MethodMetadata methodMetadata, - ConditionOutcome conditionOutcome) { + AutoConfigurationResult(MethodMetadata methodMetadata, ConditionOutcome conditionOutcome) { this.methodMetadata = methodMetadata; this.conditionOutcome = conditionOutcome; } @Override public String toString() { - return String.format("Bean method '%s' in '%s' not loaded because %s", - this.methodMetadata.getMethodName(), + return String.format("Bean method '%s' in '%s' not loaded because %s", this.methodMetadata.getMethodName(), ClassUtils.getShortName(this.methodMetadata.getDeclaringClassName()), this.conditionOutcome.getMessage()); } @@ -346,9 +321,8 @@ class NoSuchBeanDefinitionFailureAnalyzer public String toString() { StringBuilder sb = new StringBuilder("User-defined bean"); if (this.methodMetadata != null) { - sb.append(String.format(" method '%s' in '%s'", - this.methodMetadata.getMethodName(), ClassUtils.getShortName( - this.methodMetadata.getDeclaringClassName()))); + sb.append(String.format(" method '%s' in '%s'", this.methodMetadata.getMethodName(), + ClassUtils.getShortName(this.methodMetadata.getDeclaringClassName()))); } if (this.nullBean) { sb.append(" ignored as the bean value is null"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java index d1b06c86846..2c88e562200 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java @@ -105,16 +105,13 @@ public class EntityScanPackages { * @param registry the source registry * @param packageNames the package names to register */ - public static void register(BeanDefinitionRegistry registry, - Collection packageNames) { + public static void register(BeanDefinitionRegistry registry, Collection packageNames) { Assert.notNull(registry, "Registry must not be null"); Assert.notNull(packageNames, "PackageNames must not be null"); if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); - ConstructorArgumentValues constructorArguments = beanDefinition - .getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - addPackageNames(constructorArguments, packageNames)); + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + constructorArguments.addIndexedArgumentValue(0, addPackageNames(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); @@ -126,11 +123,9 @@ public class EntityScanPackages { } } - private static String[] addPackageNames( - ConstructorArgumentValues constructorArguments, + private static String[] addPackageNames(ConstructorArgumentValues constructorArguments, Collection packageNames) { - String[] existing = (String[]) constructorArguments - .getIndexedArgumentValue(0, String[].class).getValue(); + String[] existing = (String[]) constructorArguments.getIndexedArgumentValue(0, String[].class).getValue(); Set merged = new LinkedHashSet<>(); merged.addAll(Arrays.asList(existing)); merged.addAll(packageNames); @@ -144,25 +139,22 @@ public class EntityScanPackages { static class Registrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, getPackagesToScan(metadata)); } private Set getPackagesToScan(AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(EntityScan.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); - Class[] basePackageClasses = attributes - .getClassArray("basePackageClasses"); + Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); for (Class basePackageClass : basePackageClasses) { packagesToScan.add(ClassUtils.getPackageName(basePackageClass)); } if (packagesToScan.isEmpty()) { String packageName = ClassUtils.getPackageName(metadata.getClassName()); - Assert.state(!StringUtils.isEmpty(packageName), - "@EntityScan cannot be used with the default package"); + Assert.state(!StringUtils.isEmpty(packageName), "@EntityScan cannot be used with the default package"); return Collections.singleton(packageName); } return packagesToScan; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java index 91939f96795..99bab3b6a6e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,14 +58,12 @@ public class EntityScanner { * @throws ClassNotFoundException if an entity class cannot be loaded */ @SafeVarargs - public final Set> scan(Class... annotationTypes) - throws ClassNotFoundException { + public final Set> scan(Class... annotationTypes) throws ClassNotFoundException { List packages = getPackages(); if (packages.isEmpty()) { return Collections.emptySet(); } - ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( - false); + ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.setEnvironment(this.context.getEnvironment()); scanner.setResourceLoader(this.context); for (Class annotationType : annotationTypes) { @@ -74,10 +72,8 @@ public class EntityScanner { Set> entitySet = new HashSet<>(); for (String basePackage : packages) { if (StringUtils.hasText(basePackage)) { - for (BeanDefinition candidate : scanner - .findCandidateComponents(basePackage)) { - entitySet.add(ClassUtils.forName(candidate.getBeanClassName(), - this.context.getClassLoader())); + for (BeanDefinition candidate : scanner.findCandidateComponents(basePackage)) { + entitySet.add(ClassUtils.forName(candidate.getBeanClassName(), this.context.getClassLoader())); } } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java index 02f628781cd..5f72f32e46f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java @@ -56,19 +56,16 @@ public class JestAutoConfiguration { public JestClient jestClient(JestProperties properties, ObjectProvider gson, ObjectProvider builderCustomizers) { JestClientFactory factory = new JestClientFactory(); - factory.setHttpClientConfig( - createHttpClientConfig(properties, gson, builderCustomizers)); + factory.setHttpClientConfig(createHttpClientConfig(properties, gson, builderCustomizers)); return factory.getObject(); } - protected HttpClientConfig createHttpClientConfig(JestProperties properties, - ObjectProvider gson, + protected HttpClientConfig createHttpClientConfig(JestProperties properties, ObjectProvider gson, ObjectProvider builderCustomizers) { - HttpClientConfig.Builder builder = new HttpClientConfig.Builder( - properties.getUris()); + HttpClientConfig.Builder builder = new HttpClientConfig.Builder(properties.getUris()); PropertyMapper map = PropertyMapper.get(); - map.from(properties::getUsername).whenHasText().to((username) -> builder - .defaultCredentials(username, properties.getPassword())); + map.from(properties::getUsername).whenHasText() + .to((username) -> builder.defaultCredentials(username, properties.getPassword())); Proxy proxy = properties.getProxy(); map.from(proxy::getHost).whenHasText().to((host) -> { Assert.notNull(proxy.getPort(), "Proxy port must not be null"); @@ -76,12 +73,9 @@ public class JestAutoConfiguration { }); map.from(gson::getIfUnique).whenNonNull().to(builder::gson); map.from(properties::isMultiThreaded).to(builder::multiThreaded); - map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::connTimeout); - map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::readTimeout); - builderCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis).to(builder::connTimeout); + map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis).to(builder::readTimeout); + builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java index 88643dc8e6c..d2d6facf8e2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class JestProperties { /** * Comma-separated list of the Elasticsearch instances to use. */ - private List uris = new ArrayList<>( - Collections.singletonList("http://localhost:9200")); + private List uris = new ArrayList<>(Collections.singletonList("http://localhost:9200")); /** * Login username. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfiguration.java index f6bf0d23e81..2c2ba9db1cf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfiguration.java @@ -58,28 +58,25 @@ public class RestClientAutoConfiguration { @ConditionalOnMissingBean public RestClientBuilder restClientBuilder(RestClientProperties properties, ObjectProvider builderCustomizers) { - HttpHost[] hosts = properties.getUris().stream().map(HttpHost::create) - .toArray(HttpHost[]::new); + HttpHost[] hosts = properties.getUris().stream().map(HttpHost::create).toArray(HttpHost[]::new); RestClientBuilder builder = RestClient.builder(hosts); PropertyMapper map = PropertyMapper.get(); map.from(properties::getUsername).whenHasText().to((username) -> { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - Credentials credentials = new UsernamePasswordCredentials( - properties.getUsername(), properties.getPassword()); + Credentials credentials = new UsernamePasswordCredentials(properties.getUsername(), + properties.getPassword()); credentialsProvider.setCredentials(AuthScope.ANY, credentials); - builder.setHttpClientConfigCallback((httpClientBuilder) -> httpClientBuilder - .setDefaultCredentialsProvider(credentialsProvider)); + builder.setHttpClientConfigCallback( + (httpClientBuilder) -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); }); builder.setRequestConfigCallback((requestConfigBuilder) -> { - map.from(properties::getConnectionTimeout).whenNonNull() - .asInt(Duration::toMillis) + map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) .to(requestConfigBuilder::setConnectTimeout); map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) .to(requestConfigBuilder::setSocketTimeout); return requestConfigBuilder; }); - builderCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @@ -89,8 +86,7 @@ public class RestClientAutoConfiguration { @Bean @ConditionalOnMissingBean - public RestHighLevelClient restHighLevelClient( - RestClientBuilder restClientBuilder) { + public RestHighLevelClient restHighLevelClient(RestClientBuilder restClientBuilder) { return new RestHighLevelClient(restClientBuilder); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientProperties.java index c4884e1340f..7711e7cfc08 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientProperties.java @@ -35,8 +35,7 @@ public class RestClientProperties { /** * Comma-separated list of the Elasticsearch instances to use. */ - private List uris = new ArrayList<>( - Collections.singletonList("http://localhost:9200")); + private List uris = new ArrayList<>(Collections.singletonList("http://localhost:9200")); /** * Credentials username. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java index 160097dc0da..5106c3d1d8f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java @@ -87,8 +87,8 @@ import org.springframework.util.StringUtils; @ConditionalOnClass(Flyway.class) @Conditional(FlywayDataSourceCondition.class) @ConditionalOnProperty(prefix = "spring.flyway", name = "enabled", matchIfMissing = true) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, + HibernateJpaAutoConfiguration.class }) public class FlywayAutoConfiguration { @Bean @@ -98,8 +98,7 @@ public class FlywayAutoConfiguration { } @Bean - public FlywaySchemaManagementProvider flywayDefaultDdlModeProvider( - ObjectProvider flyways) { + public FlywaySchemaManagementProvider flywayDefaultDdlModeProvider(ObjectProvider flyways) { return new FlywaySchemaManagementProvider(flyways); } @@ -109,46 +108,34 @@ public class FlywayAutoConfiguration { public static class FlywayConfiguration { @Bean - public Flyway flyway(FlywayProperties properties, - DataSourceProperties dataSourceProperties, ResourceLoader resourceLoader, - ObjectProvider dataSource, + public Flyway flyway(FlywayProperties properties, DataSourceProperties dataSourceProperties, + ResourceLoader resourceLoader, ObjectProvider dataSource, @FlywayDataSource ObjectProvider flywayDataSource, ObjectProvider fluentConfigurationCustomizers, - ObjectProvider callbacks, - ObjectProvider flywayCallbacks) { - FluentConfiguration configuration = new FluentConfiguration( - resourceLoader.getClassLoader()); - DataSource dataSourceToMigrate = configureDataSource(configuration, - properties, dataSourceProperties, flywayDataSource.getIfAvailable(), - dataSource.getIfAvailable()); + ObjectProvider callbacks, ObjectProvider flywayCallbacks) { + FluentConfiguration configuration = new FluentConfiguration(resourceLoader.getClassLoader()); + DataSource dataSourceToMigrate = configureDataSource(configuration, properties, dataSourceProperties, + flywayDataSource.getIfAvailable(), dataSource.getIfAvailable()); checkLocationExists(dataSourceToMigrate, properties, resourceLoader); configureProperties(configuration, properties); - List orderedCallbacks = callbacks.orderedStream() - .collect(Collectors.toList()); + List orderedCallbacks = callbacks.orderedStream().collect(Collectors.toList()); configureCallbacks(configuration, orderedCallbacks); - fluentConfigurationCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(configuration)); + fluentConfigurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration)); Flyway flyway = configuration.load(); - List orderedFlywayCallbacks = flywayCallbacks.orderedStream() - .collect(Collectors.toList()); + List orderedFlywayCallbacks = flywayCallbacks.orderedStream().collect(Collectors.toList()); configureFlywayCallbacks(flyway, orderedCallbacks, orderedFlywayCallbacks); return flyway; } - private DataSource configureDataSource(FluentConfiguration configuration, - FlywayProperties properties, DataSourceProperties dataSourceProperties, - DataSource flywayDataSource, DataSource dataSource) { + private DataSource configureDataSource(FluentConfiguration configuration, FlywayProperties properties, + DataSourceProperties dataSourceProperties, DataSource flywayDataSource, DataSource dataSource) { if (properties.isCreateDataSource()) { - String url = getProperty(properties::getUrl, - dataSourceProperties::getUrl); - String user = getProperty(properties::getUser, - dataSourceProperties::getUsername); - String password = getProperty(properties::getPassword, - dataSourceProperties::getPassword); + String url = getProperty(properties::getUrl, dataSourceProperties::getUrl); + String user = getProperty(properties::getUser, dataSourceProperties::getUsername); + String password = getProperty(properties::getPassword, dataSourceProperties::getPassword); configuration.dataSource(url, user, password); if (!CollectionUtils.isEmpty(properties.getInitSqls())) { - String initSql = StringUtils - .collectionToDelimitedString(properties.getInitSqls(), "\n"); + String initSql = StringUtils.collectionToDelimitedString(properties.getInitSqls(), "\n"); configuration.initSql(initSql); } } @@ -161,87 +148,62 @@ public class FlywayAutoConfiguration { return configuration.getDataSource(); } - private void checkLocationExists(DataSource dataSource, - FlywayProperties properties, ResourceLoader resourceLoader) { + private void checkLocationExists(DataSource dataSource, FlywayProperties properties, + ResourceLoader resourceLoader) { if (properties.isCheckLocation()) { - List locations = new LocationResolver(dataSource) - .resolveLocations(properties.getLocations()); + List locations = new LocationResolver(dataSource).resolveLocations(properties.getLocations()); if (!hasAtLeastOneLocation(resourceLoader, locations)) { throw new FlywayMigrationScriptMissingException(locations); } } } - private void configureProperties(FluentConfiguration configuration, - FlywayProperties properties) { + private void configureProperties(FluentConfiguration configuration, FlywayProperties properties) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); String[] locations = new LocationResolver(configuration.getDataSource()) .resolveLocations(properties.getLocations()).toArray(new String[0]); map.from(locations).to(configuration::locations); map.from(properties.getEncoding()).to(configuration::encoding); map.from(properties.getConnectRetries()).to(configuration::connectRetries); - map.from(properties.getSchemas()).as(StringUtils::toStringArray) - .to(configuration::schemas); + map.from(properties.getSchemas()).as(StringUtils::toStringArray).to(configuration::schemas); map.from(properties.getTable()).to(configuration::table); - map.from(properties.getBaselineDescription()) - .to(configuration::baselineDescription); + map.from(properties.getBaselineDescription()).to(configuration::baselineDescription); map.from(properties.getBaselineVersion()).to(configuration::baselineVersion); map.from(properties.getInstalledBy()).to(configuration::installedBy); map.from(properties.getPlaceholders()).to(configuration::placeholders); - map.from(properties.getPlaceholderPrefix()) - .to(configuration::placeholderPrefix); - map.from(properties.getPlaceholderSuffix()) - .to(configuration::placeholderSuffix); - map.from(properties.isPlaceholderReplacement()) - .to(configuration::placeholderReplacement); - map.from(properties.getSqlMigrationPrefix()) - .to(configuration::sqlMigrationPrefix); + map.from(properties.getPlaceholderPrefix()).to(configuration::placeholderPrefix); + map.from(properties.getPlaceholderSuffix()).to(configuration::placeholderSuffix); + map.from(properties.isPlaceholderReplacement()).to(configuration::placeholderReplacement); + map.from(properties.getSqlMigrationPrefix()).to(configuration::sqlMigrationPrefix); map.from(properties.getSqlMigrationSuffixes()).as(StringUtils::toStringArray) .to(configuration::sqlMigrationSuffixes); - map.from(properties.getSqlMigrationSeparator()) - .to(configuration::sqlMigrationSeparator); - map.from(properties.getRepeatableSqlMigrationPrefix()) - .to(configuration::repeatableSqlMigrationPrefix); + map.from(properties.getSqlMigrationSeparator()).to(configuration::sqlMigrationSeparator); + map.from(properties.getRepeatableSqlMigrationPrefix()).to(configuration::repeatableSqlMigrationPrefix); map.from(properties.getTarget()).to(configuration::target); - map.from(properties.isBaselineOnMigrate()) - .to(configuration::baselineOnMigrate); + map.from(properties.isBaselineOnMigrate()).to(configuration::baselineOnMigrate); map.from(properties.isCleanDisabled()).to(configuration::cleanDisabled); - map.from(properties.isCleanOnValidationError()) - .to(configuration::cleanOnValidationError); + map.from(properties.isCleanOnValidationError()).to(configuration::cleanOnValidationError); map.from(properties.isGroup()).to(configuration::group); - map.from(properties.isIgnoreMissingMigrations()) - .to(configuration::ignoreMissingMigrations); - map.from(properties.isIgnoreIgnoredMigrations()) - .to(configuration::ignoreIgnoredMigrations); - map.from(properties.isIgnorePendingMigrations()) - .to(configuration::ignorePendingMigrations); - map.from(properties.isIgnoreFutureMigrations()) - .to(configuration::ignoreFutureMigrations); + map.from(properties.isIgnoreMissingMigrations()).to(configuration::ignoreMissingMigrations); + map.from(properties.isIgnoreIgnoredMigrations()).to(configuration::ignoreIgnoredMigrations); + map.from(properties.isIgnorePendingMigrations()).to(configuration::ignorePendingMigrations); + map.from(properties.isIgnoreFutureMigrations()).to(configuration::ignoreFutureMigrations); map.from(properties.isMixed()).to(configuration::mixed); map.from(properties.isOutOfOrder()).to(configuration::outOfOrder); - map.from(properties.isSkipDefaultCallbacks()) - .to(configuration::skipDefaultCallbacks); - map.from(properties.isSkipDefaultResolvers()) - .to(configuration::skipDefaultResolvers); - map.from(properties.isValidateOnMigrate()) - .to(configuration::validateOnMigrate); + map.from(properties.isSkipDefaultCallbacks()).to(configuration::skipDefaultCallbacks); + map.from(properties.isSkipDefaultResolvers()).to(configuration::skipDefaultResolvers); + map.from(properties.isValidateOnMigrate()).to(configuration::validateOnMigrate); // Pro properties map.from(properties.getBatch()).whenNonNull().to(configuration::batch); - map.from(properties.getDryRunOutput()).whenNonNull() - .to(configuration::dryRunOutput); - map.from(properties.getErrorOverrides()).whenNonNull() - .to(configuration::errorOverrides); - map.from(properties.getLicenseKey()).whenNonNull() - .to(configuration::licenseKey); - map.from(properties.getOracleSqlplus()).whenNonNull() - .to(configuration::oracleSqlplus); + map.from(properties.getDryRunOutput()).whenNonNull().to(configuration::dryRunOutput); + map.from(properties.getErrorOverrides()).whenNonNull().to(configuration::errorOverrides); + map.from(properties.getLicenseKey()).whenNonNull().to(configuration::licenseKey); + map.from(properties.getOracleSqlplus()).whenNonNull().to(configuration::oracleSqlplus); map.from(properties.getStream()).whenNonNull().to(configuration::stream); - map.from(properties.getUndoSqlMigrationPrefix()).whenNonNull() - .to(configuration::undoSqlMigrationPrefix); + map.from(properties.getUndoSqlMigrationPrefix()).whenNonNull().to(configuration::undoSqlMigrationPrefix); } - private void configureCallbacks(FluentConfiguration configuration, - List callbacks) { + private void configureCallbacks(FluentConfiguration configuration, List callbacks) { if (!callbacks.isEmpty()) { configuration.callbacks(callbacks.toArray(new Callback[0])); } @@ -251,22 +213,19 @@ public class FlywayAutoConfiguration { List flywayCallbacks) { if (!flywayCallbacks.isEmpty()) { if (!callbacks.isEmpty()) { - throw new IllegalStateException( - "Found a mixture of Callback and FlywayCallback beans." - + " One type must be used exclusively."); + throw new IllegalStateException("Found a mixture of Callback and FlywayCallback beans." + + " One type must be used exclusively."); } flyway.setCallbacks(flywayCallbacks.toArray(new FlywayCallback[0])); } } - private String getProperty(Supplier property, - Supplier defaultValue) { + private String getProperty(Supplier property, Supplier defaultValue) { String value = property.get(); return (value != null) ? value : defaultValue.get(); } - private boolean hasAtLeastOneLocation(ResourceLoader resourceLoader, - Collection locations) { + private boolean hasAtLeastOneLocation(ResourceLoader resourceLoader, Collection locations) { for (String location : locations) { if (resourceLoader.getResource(normalizePrefix(location)).exists()) { return true; @@ -283,8 +242,7 @@ public class FlywayAutoConfiguration { @ConditionalOnMissingBean public FlywayMigrationInitializer flywayInitializer(Flyway flyway, ObjectProvider migrationStrategy) { - return new FlywayMigrationInitializer(flyway, - migrationStrategy.getIfAvailable()); + return new FlywayMigrationInitializer(flyway, migrationStrategy.getIfAvailable()); } /** @@ -344,8 +302,7 @@ public class FlywayAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class FlywayJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class FlywayJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public FlywayJpaDependencyConfiguration() { super("flyway"); @@ -360,8 +317,7 @@ public class FlywayAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(JdbcOperations.class) @ConditionalOnBean(JdbcOperations.class) - protected static class FlywayJdbcOperationsDependencyConfiguration - extends JdbcOperationsDependsOnPostProcessor { + protected static class FlywayJdbcOperationsDependencyConfiguration extends JdbcOperationsDependsOnPostProcessor { public FlywayJdbcOperationsDependencyConfiguration() { super("flyway"); @@ -403,14 +359,12 @@ public class FlywayAutoConfiguration { return locations; } - private List replaceVendorLocations(List locations, - DatabaseDriver databaseDriver) { + private List replaceVendorLocations(List locations, DatabaseDriver databaseDriver) { if (databaseDriver == DatabaseDriver.UNKNOWN) { return locations; } String vendor = databaseDriver.getId(); - return locations.stream() - .map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor)) + return locations.stream().map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor)) .collect(Collectors.toList()); } @@ -439,8 +393,7 @@ public class FlywayAutoConfiguration { /** * Convert a String or Number to a {@link MigrationVersion}. */ - private static class StringOrNumberToMigrationVersionConverter - implements GenericConverter { + private static class StringOrNumberToMigrationVersionConverter implements GenericConverter { private static final Set CONVERTIBLE_TYPES; @@ -457,8 +410,7 @@ public class FlywayAutoConfiguration { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { String value = ObjectUtils.nullSafeToString(source); return MigrationVersion.fromVersion(value); } @@ -476,8 +428,7 @@ public class FlywayAutoConfiguration { } - @ConditionalOnProperty(prefix = "spring.flyway", name = "url", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.flyway", name = "url", matchIfMissing = false) private static final class FlywayUrlCondition { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java index 1ffdd2a9529..8f07fdeb1e2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @author Dave Syer * @since 1.1.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java index 17aa347e283..cca907e4191 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public class FlywayMigrationInitializer implements InitializingBean, Ordered { * @param flyway the flyway instance * @param migrationStrategy the migration strategy or {@code null} */ - public FlywayMigrationInitializer(Flyway flyway, - FlywayMigrationStrategy migrationStrategy) { + public FlywayMigrationInitializer(Flyway flyway, FlywayMigrationStrategy migrationStrategy) { Assert.notNull(flyway, "Flyway must not be null"); this.flyway = flyway; this.migrationStrategy = migrationStrategy; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingException.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingException.java index effe0ad1803..4ac622585c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingException.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingException.java @@ -31,9 +31,8 @@ public class FlywayMigrationScriptMissingException extends RuntimeException { private final List locations; FlywayMigrationScriptMissingException(List locations) { - super(locations.isEmpty() ? "Migration script locations not configured" - : "Cannot find migration scripts in: " + locations - + " (please add migration scripts or check your Flyway configuration)"); + super(locations.isEmpty() ? "Migration script locations not configured" : "Cannot find migration scripts in: " + + locations + " (please add migration scripts or check your Flyway configuration)"); this.locations = new ArrayList<>(locations); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzer.java index 077182fcba1..ebf282e1536 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzer.java @@ -30,18 +30,14 @@ class FlywayMigrationScriptMissingFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - FlywayMigrationScriptMissingException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, FlywayMigrationScriptMissingException cause) { StringBuilder description = new StringBuilder("Flyway failed to initialize: "); if (cause.getLocations().isEmpty()) { - return new FailureAnalysis(description - .append("no migration scripts location is configured").toString(), + return new FailureAnalysis(description.append("no migration scripts location is configured").toString(), "Check your Flyway configuration", cause); } - description.append(String.format( - "none of the following migration scripts locations could be found:%n%n")); - cause.getLocations().forEach( - (location) -> description.append(String.format("\t- %s%n", location))); + description.append(String.format("none of the following migration scripts locations could be found:%n%n")); + cause.getLocations().forEach((location) -> description.append(String.format("\t- %s%n", location))); return new FailureAnalysis(description.toString(), "Review the locations above or check your Flyway configuration", cause); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java index 0acd2171b7d..a4c6844e5ee 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java @@ -52,8 +52,7 @@ public class FlywayProperties { * Locations of migrations scripts. Can contain the special "{vendor}" placeholder to * use vendor-specific locations. */ - private List locations = new ArrayList<>( - Collections.singletonList("classpath:db/migration")); + private List locations = new ArrayList<>(Collections.singletonList("classpath:db/migration")); /** * Encoding of SQL migrations. @@ -118,8 +117,7 @@ public class FlywayProperties { /** * File name suffix for SQL migrations. */ - private List sqlMigrationSuffixes = new ArrayList<>( - Collections.singleton(".sql")); + private List sqlMigrationSuffixes = new ArrayList<>(Collections.singleton(".sql")); /** * File name separator for SQL migrations. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java index 8df847f43ea..210bfb3b23c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,10 +42,8 @@ class FlywaySchemaManagementProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { return StreamSupport.stream(this.flywayInstances.spliterator(), false) - .map((flyway) -> flyway.getConfiguration().getDataSource()) - .filter(dataSource::equals).findFirst() - .map((managedDataSource) -> SchemaManagement.MANAGED) - .orElse(SchemaManagement.UNMANAGED); + .map((flyway) -> flyway.getConfiguration().getDataSource()).filter(dataSource::equals).findFirst() + .map((managedDataSource) -> SchemaManagement.MANAGED).orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java index f5e3d600d28..4ddd5c8a8bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java @@ -42,22 +42,19 @@ import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory; * @since 1.1.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ freemarker.template.Configuration.class, - FreeMarkerConfigurationFactory.class }) +@ConditionalOnClass({ freemarker.template.Configuration.class, FreeMarkerConfigurationFactory.class }) @EnableConfigurationProperties(FreeMarkerProperties.class) -@Import({ FreeMarkerServletWebConfiguration.class, - FreeMarkerReactiveWebConfiguration.class, FreeMarkerNonWebConfiguration.class }) +@Import({ FreeMarkerServletWebConfiguration.class, FreeMarkerReactiveWebConfiguration.class, + FreeMarkerNonWebConfiguration.class }) public class FreeMarkerAutoConfiguration { - private static final Log logger = LogFactory - .getLog(FreeMarkerAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(FreeMarkerAutoConfiguration.class); private final ApplicationContext applicationContext; private final FreeMarkerProperties properties; - public FreeMarkerAutoConfiguration(ApplicationContext applicationContext, - FreeMarkerProperties properties) { + public FreeMarkerAutoConfiguration(ApplicationContext applicationContext, FreeMarkerProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @@ -67,8 +64,7 @@ public class FreeMarkerAutoConfiguration { if (logger.isWarnEnabled() && this.properties.isCheckTemplateLocation()) { List locations = getLocations(); if (locations.stream().noneMatch(this::locationExists)) { - logger.warn("Cannot find template location(s): " + locations - + " (please add some templates, " + logger.warn("Cannot find template location(s): " + locations + " (please add some templates, " + "check your FreeMarker configuration, or set " + "spring.freemarker.checkTemplateLocation=false)"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerReactiveWebConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerReactiveWebConfiguration.java index 89481d18af8..9217cc57244 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerReactiveWebConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerReactiveWebConfiguration.java @@ -51,8 +51,7 @@ class FreeMarkerReactiveWebConfiguration extends AbstractFreeMarkerConfiguration } @Bean - public freemarker.template.Configuration freeMarkerConfiguration( - FreeMarkerConfig configurer) { + public freemarker.template.Configuration freeMarkerConfiguration(FreeMarkerConfig configurer) { return configurer.getConfiguration(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.java index 3bf447d9acb..b126f696246 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.java @@ -60,8 +60,7 @@ class FreeMarkerServletWebConfiguration extends AbstractFreeMarkerConfiguration } @Bean - public freemarker.template.Configuration freeMarkerConfiguration( - FreeMarkerConfig configurer) { + public freemarker.template.Configuration freeMarkerConfiguration(FreeMarkerConfig configurer) { return configurer.getConfiguration(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java index 974b1bd1626..4d31e74e488 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,23 +30,19 @@ import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvi * @author Andy Wilkinson * @since 1.1.0 */ -public class FreeMarkerTemplateAvailabilityProvider - extends PathBasedTemplateAvailabilityProvider { +public class FreeMarkerTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider { public FreeMarkerTemplateAvailabilityProvider() { - super("freemarker.template.Configuration", - FreeMarkerTemplateAvailabilityProperties.class, "spring.freemarker"); + super("freemarker.template.Configuration", FreeMarkerTemplateAvailabilityProperties.class, "spring.freemarker"); } - static final class FreeMarkerTemplateAvailabilityProperties - extends TemplateAvailabilityProperties { + static final class FreeMarkerTemplateAvailabilityProperties extends TemplateAvailabilityProperties { private List templateLoaderPath = new ArrayList<>( Arrays.asList(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH)); FreeMarkerTemplateAvailabilityProperties() { - super(FreeMarkerProperties.DEFAULT_PREFIX, - FreeMarkerProperties.DEFAULT_SUFFIX); + super(FreeMarkerProperties.DEFAULT_PREFIX, FreeMarkerProperties.DEFAULT_SUFFIX); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java index 44bf1eb525d..cb64718c6e2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java @@ -63,8 +63,7 @@ import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; @EnableConfigurationProperties(GroovyTemplateProperties.class) public class GroovyTemplateAutoConfiguration { - private static final Log logger = LogFactory - .getLog(GroovyTemplateAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(GroovyTemplateAutoConfiguration.class); @Configuration(proxyBeanMethods = false) @ConditionalOnClass(GroovyMarkupConfigurer.class) @@ -74,8 +73,7 @@ public class GroovyTemplateAutoConfiguration { private final GroovyTemplateProperties properties; - public GroovyMarkupConfiguration(ApplicationContext applicationContext, - GroovyTemplateProperties properties, + public GroovyMarkupConfiguration(ApplicationContext applicationContext, GroovyTemplateProperties properties, ObjectProvider templateEngine) { this.applicationContext = applicationContext; this.properties = properties; @@ -84,13 +82,11 @@ public class GroovyTemplateAutoConfiguration { @PostConstruct public void checkTemplateLocationExists() { if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) { - TemplateLocation location = new TemplateLocation( - this.properties.getResourceLoaderPath()); + TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath()); if (!location.exists(this.applicationContext)) { logger.warn("Cannot find template location: " + location + " (please add some templates, check your Groovy " - + "configuration, or set spring.groovy.template." - + "check-template-location=false)"); + + "configuration, or set spring.groovy.template." + "check-template-location=false)"); } } } @@ -104,11 +100,9 @@ public class GroovyTemplateAutoConfiguration { */ private boolean isUsingGroovyAllJar() { try { - ProtectionDomain domain = MarkupTemplateEngine.class - .getProtectionDomain(); + ProtectionDomain domain = MarkupTemplateEngine.class.getProtectionDomain(); CodeSource codeSource = domain.getCodeSource(); - if (codeSource != null - && codeSource.getLocation().toString().contains("-all")) { + if (codeSource != null && codeSource.getLocation().toString().contains("-all")) { return true; } return false; @@ -121,8 +115,7 @@ public class GroovyTemplateAutoConfiguration { @Bean @ConditionalOnMissingBean(GroovyMarkupConfig.class) @ConfigurationProperties(prefix = "spring.groovy.template.configuration") - public GroovyMarkupConfigurer groovyMarkupConfigurer( - ObjectProvider templateEngine) { + public GroovyMarkupConfigurer groovyMarkupConfigurer(ObjectProvider templateEngine) { GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); configurer.setResourceLoaderPath(this.properties.getResourceLoaderPath()); configurer.setCacheTemplates(this.properties.isCache()); @@ -133,16 +126,14 @@ public class GroovyTemplateAutoConfiguration { } @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, - UrlBasedViewResolver.class }) + @ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, UrlBasedViewResolver.class }) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(name = "spring.groovy.template.enabled", matchIfMissing = true) public static class GroovyWebConfiguration { @Bean @ConditionalOnMissingBean(name = "groovyMarkupViewResolver") - public GroovyMarkupViewResolver groovyMarkupViewResolver( - GroovyTemplateProperties properties) { + public GroovyMarkupViewResolver groovyMarkupViewResolver(GroovyTemplateProperties properties) { GroovyMarkupViewResolver resolver = new GroovyMarkupViewResolver(); properties.applyToMvcViewResolver(resolver); return resolver; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java index cfd6ce5eacb..bae9057c839 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,23 +30,19 @@ import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvi * @author Dave Syer * @since 1.1.0 */ -public class GroovyTemplateAvailabilityProvider - extends PathBasedTemplateAvailabilityProvider { +public class GroovyTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider { public GroovyTemplateAvailabilityProvider() { - super("groovy.text.TemplateEngine", GroovyTemplateAvailabilityProperties.class, - "spring.groovy.template"); + super("groovy.text.TemplateEngine", GroovyTemplateAvailabilityProperties.class, "spring.groovy.template"); } - static final class GroovyTemplateAvailabilityProperties - extends TemplateAvailabilityProperties { + static final class GroovyTemplateAvailabilityProperties extends TemplateAvailabilityProperties { private List resourceLoaderPath = new ArrayList<>( Arrays.asList(GroovyTemplateProperties.DEFAULT_RESOURCE_LOADER_PATH)); GroovyTemplateAvailabilityProperties() { - super(GroovyTemplateProperties.DEFAULT_PREFIX, - GroovyTemplateProperties.DEFAULT_SUFFIX); + super(GroovyTemplateProperties.DEFAULT_PREFIX, GroovyTemplateProperties.DEFAULT_SUFFIX); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java index 6494f14ce76..f54f1e81841 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java @@ -57,13 +57,11 @@ public class GsonAutoConfiguration { } @Bean - public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer( - GsonProperties gsonProperties) { + public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) { return new StandardGsonBuilderCustomizer(gsonProperties); } - static final class StandardGsonBuilderCustomizer - implements GsonBuilderCustomizer, Ordered { + static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered { private final GsonProperties properties; @@ -80,23 +78,17 @@ public class GsonAutoConfiguration { public void customize(GsonBuilder builder) { GsonProperties properties = this.properties; PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(properties::getGenerateNonExecutableJson) - .toCall(builder::generateNonExecutableJson); + map.from(properties::getGenerateNonExecutableJson).toCall(builder::generateNonExecutableJson); map.from(properties::getExcludeFieldsWithoutExposeAnnotation) .toCall(builder::excludeFieldsWithoutExposeAnnotation); - map.from(properties::getSerializeNulls).whenTrue() - .toCall(builder::serializeNulls); - map.from(properties::getEnableComplexMapKeySerialization) - .toCall(builder::enableComplexMapKeySerialization); - map.from(properties::getDisableInnerClassSerialization) - .toCall(builder::disableInnerClassSerialization); - map.from(properties::getLongSerializationPolicy) - .to(builder::setLongSerializationPolicy); + map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls); + map.from(properties::getEnableComplexMapKeySerialization).toCall(builder::enableComplexMapKeySerialization); + map.from(properties::getDisableInnerClassSerialization).toCall(builder::disableInnerClassSerialization); + map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy); map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy); map.from(properties::getPrettyPrinting).toCall(builder::setPrettyPrinting); map.from(properties::getLenient).toCall(builder::setLenient); - map.from(properties::getDisableHtmlEscaping) - .toCall(builder::disableHtmlEscaping); + map.from(properties::getDisableHtmlEscaping).toCall(builder::disableHtmlEscaping); map.from(properties::getDateFormat).to(builder::setDateFormat); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonProperties.java index 17b0c4ba02d..958ced32320 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,8 +101,7 @@ public class GsonProperties { return this.excludeFieldsWithoutExposeAnnotation; } - public void setExcludeFieldsWithoutExposeAnnotation( - Boolean excludeFieldsWithoutExposeAnnotation) { + public void setExcludeFieldsWithoutExposeAnnotation(Boolean excludeFieldsWithoutExposeAnnotation) { this.excludeFieldsWithoutExposeAnnotation = excludeFieldsWithoutExposeAnnotation; } @@ -118,8 +117,7 @@ public class GsonProperties { return this.enableComplexMapKeySerialization; } - public void setEnableComplexMapKeySerialization( - Boolean enableComplexMapKeySerialization) { + public void setEnableComplexMapKeySerialization(Boolean enableComplexMapKeySerialization) { this.enableComplexMapKeySerialization = enableComplexMapKeySerialization; } @@ -127,8 +125,7 @@ public class GsonProperties { return this.disableInnerClassSerialization; } - public void setDisableInnerClassSerialization( - Boolean disableInnerClassSerialization) { + public void setDisableInnerClassSerialization(Boolean disableInnerClassSerialization) { this.disableInnerClassSerialization = disableInnerClassSerialization; } @@ -136,8 +133,7 @@ public class GsonProperties { return this.longSerializationPolicy; } - public void setLongSerializationPolicy( - LongSerializationPolicy longSerializationPolicy) { + public void setLongSerializationPolicy(LongSerializationPolicy longSerializationPolicy) { this.longSerializationPolicy = longSerializationPolicy; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java index ef149a37e7a..89e03abd5aa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java @@ -39,8 +39,7 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass(WebServlet.class) -@ConditionalOnProperty(prefix = "spring.h2.console", name = "enabled", - havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(prefix = "spring.h2.console", name = "enabled", havingValue = "true", matchIfMissing = false) @EnableConfigurationProperties(H2ConsoleProperties.class) public class H2ConsoleAutoConfiguration { @@ -48,8 +47,7 @@ public class H2ConsoleAutoConfiguration { public ServletRegistrationBean h2Console(H2ConsoleProperties properties) { String path = properties.getPath(); String urlMapping = path + (path.endsWith("/") ? "*" : "/*"); - ServletRegistrationBean registration = new ServletRegistrationBean<>( - new WebServlet(), urlMapping); + ServletRegistrationBean registration = new ServletRegistrationBean<>(new WebServlet(), urlMapping); H2ConsoleProperties.Settings settings = properties.getSettings(); if (settings.isTrace()) { registration.addInitParameter("trace", ""); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java index e84ab952972..3a831c69804 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java @@ -52,8 +52,7 @@ import org.springframework.web.bind.annotation.RequestMapping; @ConditionalOnClass({ EntityModel.class, RequestMapping.class, Plugin.class }) @ConditionalOnWebApplication @AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) @EnableConfigurationProperties(HateoasProperties.class) @Import(HypermediaHttpMessageConverterConfiguration.class) public class HypermediaAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java index 4c67a4af403..321dff0e392 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java @@ -46,8 +46,8 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl public class HypermediaHttpMessageConverterConfiguration { @Bean - @ConditionalOnProperty(prefix = "spring.hateoas", - name = "use-hal-as-default-json-media-type", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.hateoas", name = "use-hal-as-default-json-media-type", + matchIfMissing = true) public static HalMessageConverterSupportedMediaTypesCustomizer halMessageConverterSupportedMediaTypeCustomizer() { return new HalMessageConverterSupportedMediaTypesCustomizer(); } @@ -59,8 +59,7 @@ public class HypermediaHttpMessageConverterConfiguration { * {@code Jackson2ModuleRegisteringBeanPostProcessor} has registered the converter and * it is unordered. */ - private static class HalMessageConverterSupportedMediaTypesCustomizer - implements BeanFactoryAware { + private static class HalMessageConverterSupportedMediaTypesCustomizer implements BeanFactoryAware { private volatile BeanFactory beanFactory; @@ -72,11 +71,9 @@ public class HypermediaHttpMessageConverterConfiguration { } } - private void configureHttpMessageConverters( - Collection handlerAdapters) { + private void configureHttpMessageConverters(Collection handlerAdapters) { for (RequestMappingHandlerAdapter handlerAdapter : handlerAdapters) { - for (HttpMessageConverter messageConverter : handlerAdapter - .getMessageConverters()) { + for (HttpMessageConverter messageConverter : handlerAdapter.getMessageConverters()) { configureHttpMessageConverter(messageConverter); } } @@ -84,13 +81,11 @@ public class HypermediaHttpMessageConverterConfiguration { private void configureHttpMessageConverter(HttpMessageConverter converter) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - List supportedMediaTypes = new ArrayList<>( - converter.getSupportedMediaTypes()); + List supportedMediaTypes = new ArrayList<>(converter.getSupportedMediaTypes()); if (!supportedMediaTypes.contains(MediaType.APPLICATION_JSON)) { supportedMediaTypes.add(MediaType.APPLICATION_JSON); } - ((AbstractHttpMessageConverter) converter) - .setSupportedMediaTypes(supportedMediaTypes); + ((AbstractHttpMessageConverter) converter).setSupportedMediaTypes(supportedMediaTypes); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfiguration.java index 6d5ccf91656..20260048aa8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfiguration.java @@ -49,8 +49,7 @@ class HazelcastClientConfiguration { static class HazelcastClientConfigFileConfiguration { @Bean - public HazelcastInstance hazelcastInstance(HazelcastProperties properties) - throws IOException { + public HazelcastInstance hazelcastInstance(HazelcastProperties properties) throws IOException { Resource config = properties.resolveConfigLocation(); if (config != null) { return new HazelcastClientFactory(config).getHazelcastInstance(); @@ -78,9 +77,8 @@ class HazelcastClientConfiguration { static class ConfigAvailableCondition extends HazelcastConfigResourceCondition { ConfigAvailableCondition() { - super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast-client.xml", - "classpath:/hazelcast-client.xml", "file:./hazelcast-client.yaml", - "classpath:/hazelcast-client.yaml"); + super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast-client.xml", "classpath:/hazelcast-client.xml", + "file:./hazelcast-client.yaml", "classpath:/hazelcast-client.yaml"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientFactory.java index d9535eabbf5..7bf5e0d305d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientFactory.java @@ -57,8 +57,7 @@ public class HazelcastClientFactory { this.clientConfig = clientConfig; } - private ClientConfig getClientConfig(Resource clientConfigLocation) - throws IOException { + private ClientConfig getClientConfig(Resource clientConfigLocation) throws IOException { URL configUrl = clientConfigLocation.getURL(); String configFileName = configUrl.getPath(); if (configFileName.endsWith(".yaml")) { @@ -73,8 +72,7 @@ public class HazelcastClientFactory { */ public HazelcastInstance getHazelcastInstance() { if (StringUtils.hasText(this.clientConfig.getInstanceName())) { - return HazelcastClient - .getHazelcastClientByName(this.clientConfig.getInstanceName()); + return HazelcastClient.getHazelcastClientByName(this.clientConfig.getInstanceName()); } return HazelcastClient.newHazelcastClient(this.clientConfig); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java index f86196f41e9..f49a89d7c06 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,19 +37,17 @@ public abstract class HazelcastConfigResourceCondition extends ResourceCondition private final String configSystemProperty; - protected HazelcastConfigResourceCondition(String configSystemProperty, - String... resourceLocations) { + protected HazelcastConfigResourceCondition(String configSystemProperty, String... resourceLocations) { super("Hazelcast", "spring.hazelcast.config", resourceLocations); Assert.notNull(configSystemProperty, "ConfigSystemProperty must not be null"); this.configSystemProperty = configSystemProperty; } @Override - protected ConditionOutcome getResourceOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { if (System.getProperty(this.configSystemProperty) != null) { - return ConditionOutcome.match(startConditionMessage().because( - "System property '" + this.configSystemProperty + "' is set.")); + return ConditionOutcome.match( + startConditionMessage().because("System property '" + this.configSystemProperty + "' is set.")); } return super.getResourceOutcome(context, metadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java index df2ea84fd94..e7d06ad26e3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java @@ -40,10 +40,8 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; * @since 1.3.2 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ HazelcastInstance.class, - LocalContainerEntityManagerFactoryBean.class }) -@AutoConfigureAfter({ HazelcastAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@ConditionalOnClass({ HazelcastInstance.class, LocalContainerEntityManagerFactoryBean.class }) +@AutoConfigureAfter({ HazelcastAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class HazelcastJpaDependencyAutoConfiguration { @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java index 271708447fb..74b69d48920 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,8 @@ public class HazelcastProperties { if (this.config == null) { return null; } - Assert.isTrue(this.config.exists(), () -> "Hazelcast configuration does not " - + "exist '" + this.config.getDescription() + "'"); + Assert.isTrue(this.config.exists(), + () -> "Hazelcast configuration does not " + "exist '" + this.config.getDescription() + "'"); return this.config; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastServerConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastServerConfiguration.java index 2432a7f92db..11dd3f432d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastServerConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastServerConfiguration.java @@ -47,8 +47,7 @@ class HazelcastServerConfiguration { static class HazelcastServerConfigFileConfiguration { @Bean - public HazelcastInstance hazelcastInstance(HazelcastProperties properties) - throws IOException { + public HazelcastInstance hazelcastInstance(HazelcastProperties properties) throws IOException { Resource config = properties.resolveConfigLocation(); if (config != null) { return new HazelcastInstanceFactory(config).getHazelcastInstance(); @@ -76,8 +75,7 @@ class HazelcastServerConfiguration { static class ConfigAvailableCondition extends HazelcastConfigResourceCondition { ConfigAvailableCondition() { - super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", - "classpath:/hazelcast.xml", "file:./hazelcast.yaml", + super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", "classpath:/hazelcast.xml", "file:./hazelcast.yaml", "classpath:/hazelcast.yaml"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/GsonHttpMessageConvertersConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/GsonHttpMessageConvertersConfiguration.java index 8efeff02378..daf0d49e8b7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/GsonHttpMessageConvertersConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/GsonHttpMessageConvertersConfiguration.java @@ -56,15 +56,13 @@ class GsonHttpMessageConvertersConfiguration { } - private static class PreferGsonOrJacksonAndJsonbUnavailableCondition - extends AnyNestedCondition { + private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition { PreferGsonOrJacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } - @ConditionalOnProperty( - name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, + @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "gson") static class GsonPreferred { @@ -77,8 +75,7 @@ class GsonHttpMessageConvertersConfiguration { } - private static class JacksonAndJsonbUnavailableCondition - extends NoneNestedConditions { + private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions { JacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); @@ -89,8 +86,7 @@ class GsonHttpMessageConvertersConfiguration { } - @ConditionalOnProperty( - name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, + @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java index 0577b17b23a..31c6063171b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java @@ -87,8 +87,7 @@ public class HttpMessageConverters implements Iterable> * default converter is found). The {@link #postProcessConverters(List)} method can be * used for further converter manipulation. */ - public HttpMessageConverters( - Collection> additionalConverters) { + public HttpMessageConverters(Collection> additionalConverters) { this(true, additionalConverters); } @@ -100,16 +99,14 @@ public class HttpMessageConverters implements Iterable> * found). The {@link #postProcessConverters(List)} method can be used for further * converter manipulation. */ - public HttpMessageConverters(boolean addDefaultConverters, - Collection> converters) { + public HttpMessageConverters(boolean addDefaultConverters, Collection> converters) { List> combined = getCombinedConverters(converters, addDefaultConverters ? getDefaultConverters() : Collections.emptyList()); combined = postProcessConverters(combined); this.converters = Collections.unmodifiableList(combined); } - private List> getCombinedConverters( - Collection> converters, + private List> getCombinedConverters(Collection> converters, List> defaultConverters) { List> combined = new ArrayList<>(); List> processing = new ArrayList<>(converters); @@ -124,17 +121,14 @@ public class HttpMessageConverters implements Iterable> } combined.add(defaultConverter); if (defaultConverter instanceof AllEncompassingFormHttpMessageConverter) { - configurePartConverters( - (AllEncompassingFormHttpMessageConverter) defaultConverter, - converters); + configurePartConverters((AllEncompassingFormHttpMessageConverter) defaultConverter, converters); } } combined.addAll(0, processing); return combined; } - private boolean isReplacement(HttpMessageConverter defaultConverter, - HttpMessageConverter candidate) { + private boolean isReplacement(HttpMessageConverter defaultConverter, HttpMessageConverter candidate) { for (Class nonReplacingConverter : NON_REPLACING_CONVERTERS) { if (nonReplacingConverter.isInstance(candidate)) { return false; @@ -143,25 +137,19 @@ public class HttpMessageConverters implements Iterable> return ClassUtils.isAssignableValue(defaultConverter.getClass(), candidate); } - private void configurePartConverters( - AllEncompassingFormHttpMessageConverter formConverter, + private void configurePartConverters(AllEncompassingFormHttpMessageConverter formConverter, Collection> converters) { - List> partConverters = extractPartConverters( - formConverter); - List> combinedConverters = getCombinedConverters( - converters, partConverters); + List> partConverters = extractPartConverters(formConverter); + List> combinedConverters = getCombinedConverters(converters, partConverters); combinedConverters = postProcessPartConverters(combinedConverters); formConverter.setPartConverters(combinedConverters); } @SuppressWarnings("unchecked") - private List> extractPartConverters( - FormHttpMessageConverter formConverter) { - Field field = ReflectionUtils.findField(FormHttpMessageConverter.class, - "partConverters"); + private List> extractPartConverters(FormHttpMessageConverter formConverter) { + Field field = ReflectionUtils.findField(FormHttpMessageConverter.class, "partConverters"); ReflectionUtils.makeAccessible(field); - return (List>) ReflectionUtils.getField(field, - formConverter); + return (List>) ReflectionUtils.getField(field, formConverter); } /** @@ -170,8 +158,7 @@ public class HttpMessageConverters implements Iterable> * @param converters a mutable list of the converters that will be used. * @return the final converts list to use */ - protected List> postProcessConverters( - List> converters) { + protected List> postProcessConverters(List> converters) { return converters; } @@ -183,15 +170,14 @@ public class HttpMessageConverters implements Iterable> * @return the final converts list to use * @since 1.3.0 */ - protected List> postProcessPartConverters( - List> converters) { + protected List> postProcessPartConverters(List> converters) { return converters; } private List> getDefaultConverters() { List> converters = new ArrayList<>(); - if (ClassUtils.isPresent("org.springframework.web.servlet.config.annotation." - + "WebMvcConfigurationSupport", null)) { + if (ClassUtils.isPresent("org.springframework.web.servlet.config.annotation." + "WebMvcConfigurationSupport", + null)) { converters.addAll(new WebMvcConfigurationSupport() { public List> defaultMessageConverters() { @@ -209,8 +195,7 @@ public class HttpMessageConverters implements Iterable> private void reorderXmlConvertersToEnd(List> converters) { List> xml = new ArrayList<>(); - for (Iterator> iterator = converters.iterator(); iterator - .hasNext();) { + for (Iterator> iterator = converters.iterator(); iterator.hasNext();) { HttpMessageConverter converter = iterator.next(); if ((converter instanceof AbstractXmlHttpMessageConverter) || (converter instanceof MappingJackson2XmlHttpMessageConverter)) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.java index 43b7c81d023..f184662c2fc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.java @@ -54,10 +54,8 @@ import org.springframework.http.converter.StringHttpMessageConverter; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(HttpMessageConverter.class) @Conditional(NotReactiveWebApplicationCondition.class) -@AutoConfigureAfter({ GsonAutoConfiguration.class, JacksonAutoConfiguration.class, - JsonbAutoConfiguration.class }) -@Import({ JacksonHttpMessageConvertersConfiguration.class, - GsonHttpMessageConvertersConfiguration.class, +@AutoConfigureAfter({ GsonAutoConfiguration.class, JacksonAutoConfiguration.class, JsonbAutoConfiguration.class }) +@Import({ JacksonHttpMessageConvertersConfiguration.class, GsonHttpMessageConvertersConfiguration.class, JsonbHttpMessageConvertersConfiguration.class }) public class HttpMessageConvertersAutoConfiguration { @@ -65,10 +63,8 @@ public class HttpMessageConvertersAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpMessageConverters messageConverters( - ObjectProvider> converters) { - return new HttpMessageConverters( - converters.orderedStream().collect(Collectors.toList())); + public HttpMessageConverters messageConverters(ObjectProvider> converters) { + return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList())); } @Configuration(proxyBeanMethods = false) @@ -78,8 +74,7 @@ public class HttpMessageConvertersAutoConfiguration { @Bean @ConditionalOnMissingBean - public StringHttpMessageConverter stringHttpMessageConverter( - HttpProperties httpProperties) { + public StringHttpMessageConverter stringHttpMessageConverter(HttpProperties httpProperties) { StringHttpMessageConverter converter = new StringHttpMessageConverter( httpProperties.getEncoding().getCharset()); converter.setWriteAcceptCharset(false); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpProperties.java index 60ada16ca08..0b36c5b47fa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -133,8 +133,7 @@ public class HttpProperties { } public boolean shouldForce(Type type) { - Boolean force = (type != Type.REQUEST) ? this.forceResponse - : this.forceRequest; + Boolean force = (type != Type.REQUEST) ? this.forceResponse : this.forceRequest; if (force == null) { force = this.force; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration.java index 252017e916e..6f78eaaa702 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration.java @@ -41,8 +41,7 @@ class JacksonHttpMessageConvertersConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ObjectMapper.class) @ConditionalOnBean(ObjectMapper.class) - @ConditionalOnProperty( - name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, + @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing = true) protected static class MappingJackson2HttpMessageConverterConfiguration { @@ -51,8 +50,7 @@ class JacksonHttpMessageConvertersConfiguration { ignoredType = { "org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" }) - public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter( - ObjectMapper objectMapper) { + public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } @@ -67,8 +65,7 @@ class JacksonHttpMessageConvertersConfiguration { @ConditionalOnMissingBean public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter( Jackson2ObjectMapperBuilder builder) { - return new MappingJackson2XmlHttpMessageConverter( - builder.createXmlMapper(true).build()); + return new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JsonbHttpMessageConvertersConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JsonbHttpMessageConvertersConfiguration.java index a68a7b0005c..889bdc54164 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JsonbHttpMessageConvertersConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/JsonbHttpMessageConvertersConfiguration.java @@ -55,22 +55,19 @@ class JsonbHttpMessageConvertersConfiguration { } - private static class PreferJsonbOrMissingJacksonAndGsonCondition - extends AnyNestedCondition { + private static class PreferJsonbOrMissingJacksonAndGsonCondition extends AnyNestedCondition { PreferJsonbOrMissingJacksonAndGsonCondition() { super(ConfigurationPhase.REGISTER_BEAN); } - @ConditionalOnProperty( - name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, + @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } - @ConditionalOnMissingBean({ MappingJackson2HttpMessageConverter.class, - GsonHttpMessageConverter.class }) + @ConditionalOnMissingBean({ MappingJackson2HttpMessageConverter.class, GsonHttpMessageConverter.class }) static class JacksonAndGsonMissing { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java index 0735abf7c27..9d60fbaff0a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java @@ -60,10 +60,8 @@ public class CodecsAutoConfiguration { public CodecCustomizer jacksonCodecCustomizer(ObjectMapper objectMapper) { return (configurer) -> { CodecConfigurer.DefaultCodecs defaults = configurer.defaultCodecs(); - defaults.jackson2JsonDecoder( - new Jackson2JsonDecoder(objectMapper, EMPTY_MIME_TYPES)); - defaults.jackson2JsonEncoder( - new Jackson2JsonEncoder(objectMapper, EMPTY_MIME_TYPES)); + defaults.jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, EMPTY_MIME_TYPES)); + defaults.jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, EMPTY_MIME_TYPES)); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfiguration.java index 8197c75726d..e64f047e955 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfiguration.java @@ -47,12 +47,11 @@ public class InfluxDbAutoConfiguration { @ConditionalOnProperty("spring.influx.url") public InfluxDB influxDb(InfluxDbProperties properties, ObjectProvider builder) { - return new InfluxDBImpl(properties.getUrl(), properties.getUser(), - properties.getPassword(), determineBuilder(builder.getIfAvailable())); + return new InfluxDBImpl(properties.getUrl(), properties.getUser(), properties.getPassword(), + determineBuilder(builder.getIfAvailable())); } - private static OkHttpClient.Builder determineBuilder( - InfluxDbOkHttpClientBuilderProvider builder) { + private static OkHttpClient.Builder determineBuilder(InfluxDbOkHttpClientBuilderProvider builder) { if (builder != null) { return builder.get(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbOkHttpClientBuilderProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbOkHttpClientBuilderProvider.java index c1073c3ba83..67dc383089d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbOkHttpClientBuilderProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbOkHttpClientBuilderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,6 @@ import org.influxdb.InfluxDB; * @since 2.1.0 */ @FunctionalInterface -public interface InfluxDbOkHttpClientBuilderProvider - extends Supplier { +public interface InfluxDbOkHttpClientBuilderProvider extends Supplier { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java index 48e7a9d2b30..2d0148311f8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java @@ -62,21 +62,19 @@ public class ProjectInfoAutoConfiguration { @ConditionalOnMissingBean @Bean public GitProperties gitProperties() throws Exception { - return new GitProperties(loadFrom(this.properties.getGit().getLocation(), "git", - this.properties.getGit().getEncoding())); + return new GitProperties( + loadFrom(this.properties.getGit().getLocation(), "git", this.properties.getGit().getEncoding())); } - @ConditionalOnResource( - resources = "${spring.info.build.location:classpath:META-INF/build-info.properties}") + @ConditionalOnResource(resources = "${spring.info.build.location:classpath:META-INF/build-info.properties}") @ConditionalOnMissingBean @Bean public BuildProperties buildProperties() throws Exception { - return new BuildProperties(loadFrom(this.properties.getBuild().getLocation(), - "build", this.properties.getBuild().getEncoding())); + return new BuildProperties( + loadFrom(this.properties.getBuild().getLocation(), "build", this.properties.getBuild().getEncoding())); } - protected Properties loadFrom(Resource location, String prefix, Charset encoding) - throws IOException { + protected Properties loadFrom(Resource location, String prefix, Charset encoding) throws IOException { prefix = prefix.endsWith(".") ? prefix : prefix + "."; Properties source = loadSource(location, encoding); Properties target = new Properties(); @@ -88,11 +86,9 @@ public class ProjectInfoAutoConfiguration { return target; } - private Properties loadSource(Resource location, Charset encoding) - throws IOException { + private Properties loadSource(Resource location, Charset encoding) throws IOException { if (encoding != null) { - return PropertiesLoaderUtils - .loadProperties(new EncodedResource(location, encoding)); + return PropertiesLoaderUtils.loadProperties(new EncodedResource(location, encoding)); } return PropertiesLoaderUtils.loadProperties(location); } @@ -102,8 +98,7 @@ public class ProjectInfoAutoConfiguration { private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ResourceLoader loader = context.getResourceLoader(); loader = (loader != null) ? loader : this.defaultResourceLoader; Environment environment = context.getEnvironment(); @@ -111,14 +106,11 @@ public class ProjectInfoAutoConfiguration { if (location == null) { location = "classpath:git.properties"; } - ConditionMessage.Builder message = ConditionMessage - .forCondition("GitResource"); + ConditionMessage.Builder message = ConditionMessage.forCondition("GitResource"); if (loader.getResource(location).exists()) { - return ConditionOutcome - .match(message.found("git info at").items(location)); + return ConditionOutcome.match(message.found("git info at").items(location)); } - return ConditionOutcome - .noMatch(message.didNotFind("git info at").items(location)); + return ConditionOutcome.noMatch(message.didNotFind("git info at").items(location)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java index e253182149d..ad533bc5881 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ public class ProjectInfoProperties { /** * Location of the generated build-info.properties file. */ - private Resource location = new ClassPathResource( - "META-INF/build-info.properties"); + private Resource location = new ClassPathResource("META-INF/build-info.properties"); /** * File encoding. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java index 32a73d3970b..7b9b31ace53 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java @@ -75,23 +75,19 @@ public class IntegrationAutoConfiguration { */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(EnableIntegrationMBeanExport.class) - @ConditionalOnMissingBean(value = IntegrationMBeanExporter.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = IntegrationMBeanExporter.class, search = SearchStrategy.CURRENT) @ConditionalOnBean(MBeanServer.class) - @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) protected static class IntegrationJmxConfiguration { @Bean - public IntegrationMBeanExporter integrationMbeanExporter(BeanFactory beanFactory, - Environment environment) { + public IntegrationMBeanExporter integrationMbeanExporter(BeanFactory beanFactory, Environment environment) { IntegrationMBeanExporter exporter = new IntegrationMBeanExporter(); String defaultDomain = environment.getProperty("spring.jmx.default-domain"); if (StringUtils.hasLength(defaultDomain)) { exporter.setDefaultDomain(defaultDomain); } - String serverBean = environment.getProperty("spring.jmx.server", - "mbeanServer"); + String serverBean = environment.getProperty("spring.jmx.server", "mbeanServer"); exporter.setServer(beanFactory.getBean(serverBean, MBeanServer.class)); return exporter; } @@ -104,8 +100,7 @@ public class IntegrationAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(EnableIntegrationManagement.class) @ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class, - name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, - search = SearchStrategy.CURRENT) + name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT) protected static class IntegrationManagementConfiguration { @Configuration(proxyBeanMethods = false) @@ -136,11 +131,9 @@ public class IntegrationAutoConfiguration { @Bean @ConditionalOnMissingBean - public IntegrationDataSourceInitializer integrationDataSourceInitializer( - DataSource dataSource, ResourceLoader resourceLoader, - IntegrationProperties properties) { - return new IntegrationDataSourceInitializer(dataSource, resourceLoader, - properties); + public IntegrationDataSourceInitializer integrationDataSourceInitializer(DataSource dataSource, + ResourceLoader resourceLoader, IntegrationProperties properties) { + return new IntegrationDataSourceInitializer(dataSource, resourceLoader, properties); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java index 090b98a8cfa..cae4e57a79b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java @@ -35,8 +35,7 @@ import org.springframework.integration.config.IntegrationComponentScanRegistrar; * @author Artem Bilan * @author Phillip Webb */ -class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScanRegistrar - implements BeanFactoryAware { +class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScanRegistrar implements BeanFactoryAware { private BeanFactory beanFactory; @@ -48,15 +47,14 @@ class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScan @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, final BeanDefinitionRegistry registry) { - super.registerBeanDefinitions(AnnotationMetadata - .introspect(IntegrationComponentScanConfiguration.class), registry); + super.registerBeanDefinitions(AnnotationMetadata.introspect(IntegrationComponentScanConfiguration.class), + registry); } @Override - protected Collection getBasePackages( - AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - return (AutoConfigurationPackages.has(this.beanFactory) - ? AutoConfigurationPackages.get(this.beanFactory) + protected Collection getBasePackages(AnnotationMetadata importingClassMetadata, + BeanDefinitionRegistry registry) { + return (AutoConfigurationPackages.has(this.beanFactory) ? AutoConfigurationPackages.get(this.beanFactory) : Collections.emptyList()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceInitializer.java index f1f362f049d..b11f56bfb86 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ public class IntegrationDataSourceInitializer extends AbstractDataSourceInitiali private final IntegrationProperties.Jdbc properties; - public IntegrationDataSourceInitializer(DataSource dataSource, - ResourceLoader resourceLoader, IntegrationProperties properties) { + public IntegrationDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader, + IntegrationProperties properties) { super(dataSource, resourceLoader); Assert.notNull(properties, "IntegrationProperties must not be null"); this.properties = properties.getJdbc(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java index 64b44296b37..f8ba410e1bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java @@ -109,44 +109,37 @@ public class JacksonAutoConfiguration { } @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, DateTime.class, - DateTimeSerializer.class, JacksonJodaDateFormat.class }) + @ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, DateTime.class, DateTimeSerializer.class, + JacksonJodaDateFormat.class }) static class JodaDateTimeJacksonConfiguration { - private static final Log logger = LogFactory - .getLog(JodaDateTimeJacksonConfiguration.class); + private static final Log logger = LogFactory.getLog(JodaDateTimeJacksonConfiguration.class); @Bean - public SimpleModule jodaDateTimeSerializationModule( - JacksonProperties jacksonProperties) { + public SimpleModule jodaDateTimeSerializationModule(JacksonProperties jacksonProperties) { SimpleModule module = new SimpleModule(); - JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat( - jacksonProperties); + JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(jacksonProperties); if (jacksonJodaFormat != null) { - module.addSerializer(DateTime.class, - new DateTimeSerializer(jacksonJodaFormat, 0)); + module.addSerializer(DateTime.class, new DateTimeSerializer(jacksonJodaFormat, 0)); } return module; } - private JacksonJodaDateFormat getJacksonJodaDateFormat( - JacksonProperties jacksonProperties) { + private JacksonJodaDateFormat getJacksonJodaDateFormat(JacksonProperties jacksonProperties) { if (jacksonProperties.getJodaDateTimeFormat() != null) { - return new JacksonJodaDateFormat(DateTimeFormat - .forPattern(jacksonProperties.getJodaDateTimeFormat()) - .withZoneUTC()); + return new JacksonJodaDateFormat( + DateTimeFormat.forPattern(jacksonProperties.getJodaDateTimeFormat()).withZoneUTC()); } if (jacksonProperties.getDateFormat() != null) { try { - return new JacksonJodaDateFormat(DateTimeFormat - .forPattern(jacksonProperties.getDateFormat()).withZoneUTC()); + return new JacksonJodaDateFormat( + DateTimeFormat.forPattern(jacksonProperties.getDateFormat()).withZoneUTC()); } catch (IllegalArgumentException ex) { if (logger.isWarnEnabled()) { logger.warn("spring.jackson.date-format could not be used to " + "configure formatting of Joda's DateTime. You may want " - + "to configure spring.jackson.joda-date-time-format as " - + "well."); + + "to configure spring.jackson.joda-date-time-format as " + "well."); } } } @@ -173,8 +166,7 @@ public class JacksonAutoConfiguration { @Bean @ConditionalOnMissingBean - public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder( - ApplicationContext applicationContext, + public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(ApplicationContext applicationContext, List customizers) { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.applicationContext(applicationContext); @@ -198,10 +190,8 @@ public class JacksonAutoConfiguration { @Bean public StandardJackson2ObjectMapperBuilderCustomizer standardJacksonObjectMapperBuilderCustomizer( - ApplicationContext applicationContext, - JacksonProperties jacksonProperties) { - return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext, - jacksonProperties); + ApplicationContext applicationContext, JacksonProperties jacksonProperties) { + return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext, jacksonProperties); } static final class StandardJackson2ObjectMapperBuilderCustomizer @@ -211,8 +201,7 @@ public class JacksonAutoConfiguration { private final JacksonProperties jacksonProperties; - StandardJackson2ObjectMapperBuilderCustomizer( - ApplicationContext applicationContext, + StandardJackson2ObjectMapperBuilderCustomizer(ApplicationContext applicationContext, JacksonProperties jacksonProperties) { this.applicationContext = applicationContext; this.jacksonProperties = jacksonProperties; @@ -227,8 +216,7 @@ public class JacksonAutoConfiguration { public void customize(Jackson2ObjectMapperBuilder builder) { if (this.jacksonProperties.getDefaultPropertyInclusion() != null) { - builder.serializationInclusion( - this.jacksonProperties.getDefaultPropertyInclusion()); + builder.serializationInclusion(this.jacksonProperties.getDefaultPropertyInclusion()); } if (this.jacksonProperties.getTimeZone() != null) { builder.timeZone(this.jacksonProperties.getTimeZone()); @@ -246,8 +234,7 @@ public class JacksonAutoConfiguration { configureLocale(builder); } - private void configureFeatures(Jackson2ObjectMapperBuilder builder, - Map features) { + private void configureFeatures(Jackson2ObjectMapperBuilder builder, Map features) { features.forEach((feature, value) -> { if (value != null) { if (value) { @@ -272,19 +259,16 @@ public class JacksonAutoConfiguration { if (dateFormat != null) { try { Class dateFormatClass = ClassUtils.forName(dateFormat, null); - builder.dateFormat( - (DateFormat) BeanUtils.instantiateClass(dateFormatClass)); + builder.dateFormat((DateFormat) BeanUtils.instantiateClass(dateFormatClass)); } catch (ClassNotFoundException ex) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat( - dateFormat); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); // Since Jackson 2.6.3 we always need to set a TimeZone (see // gh-4170). If none in our properties fallback to the Jackson's // default TimeZone timeZone = this.jacksonProperties.getTimeZone(); if (timeZone == null) { - timeZone = new ObjectMapper().getSerializationConfig() - .getTimeZone(); + timeZone = new ObjectMapper().getSerializationConfig().getTimeZone(); } simpleDateFormat.setTimeZone(timeZone); builder.dateFormat(simpleDateFormat); @@ -292,8 +276,7 @@ public class JacksonAutoConfiguration { } } - private void configurePropertyNamingStrategy( - Jackson2ObjectMapperBuilder builder) { + private void configurePropertyNamingStrategy(Jackson2ObjectMapperBuilder builder) { // We support a fully qualified class name extending Jackson's // PropertyNamingStrategy or a string value corresponding to the constant // names in PropertyNamingStrategy which hold default provided @@ -301,8 +284,7 @@ public class JacksonAutoConfiguration { String strategy = this.jacksonProperties.getPropertyNamingStrategy(); if (strategy != null) { try { - configurePropertyNamingStrategyClass(builder, - ClassUtils.forName(strategy, null)); + configurePropertyNamingStrategyClass(builder, ClassUtils.forName(strategy, null)); } catch (ClassNotFoundException ex) { configurePropertyNamingStrategyField(builder, strategy); @@ -310,24 +292,21 @@ public class JacksonAutoConfiguration { } } - private void configurePropertyNamingStrategyClass( - Jackson2ObjectMapperBuilder builder, + private void configurePropertyNamingStrategyClass(Jackson2ObjectMapperBuilder builder, Class propertyNamingStrategyClass) { - builder.propertyNamingStrategy((PropertyNamingStrategy) BeanUtils - .instantiateClass(propertyNamingStrategyClass)); + builder.propertyNamingStrategy( + (PropertyNamingStrategy) BeanUtils.instantiateClass(propertyNamingStrategyClass)); } - private void configurePropertyNamingStrategyField( - Jackson2ObjectMapperBuilder builder, String fieldName) { + private void configurePropertyNamingStrategyField(Jackson2ObjectMapperBuilder builder, String fieldName) { // Find the field (this way we automatically support new constants // that may be added by Jackson in the future) - Field field = ReflectionUtils.findField(PropertyNamingStrategy.class, - fieldName, PropertyNamingStrategy.class); - Assert.notNull(field, () -> "Constant named '" + fieldName - + "' not found on " + PropertyNamingStrategy.class.getName()); + Field field = ReflectionUtils.findField(PropertyNamingStrategy.class, fieldName, + PropertyNamingStrategy.class); + Assert.notNull(field, () -> "Constant named '" + fieldName + "' not found on " + + PropertyNamingStrategy.class.getName()); try { - builder.propertyNamingStrategy( - (PropertyNamingStrategy) field.get(null)); + builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null)); } catch (Exception ex) { throw new IllegalStateException(ex); @@ -335,8 +314,7 @@ public class JacksonAutoConfiguration { } private void configureModules(Jackson2ObjectMapperBuilder builder) { - Collection moduleBeans = getBeans(this.applicationContext, - Module.class); + Collection moduleBeans = getBeans(this.applicationContext, Module.class); builder.modulesToInstall(moduleBeans.toArray(new Module[0])); } @@ -347,10 +325,8 @@ public class JacksonAutoConfiguration { } } - private static Collection getBeans(ListableBeanFactory beanFactory, - Class type) { - return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type) - .values(); + private static Collection getBeans(ListableBeanFactory beanFactory, Class type) { + return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type).values(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java index eb4aaf713b0..7135fe80345 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,20 +65,17 @@ public class JacksonProperties { * Jackson visibility thresholds that can be used to limit which methods (and fields) * are auto-detected. */ - private final Map visibility = new EnumMap<>( - PropertyAccessor.class); + private final Map visibility = new EnumMap<>(PropertyAccessor.class); /** * Jackson on/off features that affect the way Java objects are serialized. */ - private final Map serialization = new EnumMap<>( - SerializationFeature.class); + private final Map serialization = new EnumMap<>(SerializationFeature.class); /** * Jackson on/off features that affect the way Java objects are deserialized. */ - private final Map deserialization = new EnumMap<>( - DeserializationFeature.class); + private final Map deserialization = new EnumMap<>(DeserializationFeature.class); /** * Jackson general purpose on/off features. @@ -88,14 +85,12 @@ public class JacksonProperties { /** * Jackson on/off features for parsers. */ - private final Map parser = new EnumMap<>( - JsonParser.Feature.class); + private final Map parser = new EnumMap<>(JsonParser.Feature.class); /** * Jackson on/off features for generators. */ - private final Map generator = new EnumMap<>( - JsonGenerator.Feature.class); + private final Map generator = new EnumMap<>(JsonGenerator.Feature.class); /** * Controls the inclusion of properties during serialization. Configured with one of @@ -166,8 +161,7 @@ public class JacksonProperties { return this.defaultPropertyInclusion; } - public void setDefaultPropertyInclusion( - JsonInclude.Include defaultPropertyInclusion) { + public void setDefaultPropertyInclusion(JsonInclude.Include defaultPropertyInclusion) { this.defaultPropertyInclusion = defaultPropertyInclusion; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java index 80597c9f4cb..a6c510b4c69 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }) @EnableConfigurationProperties(DataSourceProperties.class) -@Import({ DataSourcePoolMetadataProvidersConfiguration.class, - DataSourceInitializationConfiguration.class }) +@Import({ DataSourcePoolMetadataProvidersConfiguration.class, DataSourceInitializationConfiguration.class }) public class DataSourceAutoConfiguration { @Configuration(proxyBeanMethods = false) @@ -100,16 +99,12 @@ public class DataSourceAutoConfiguration { static class PooledDataSourceAvailableCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("PooledDataSource"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("PooledDataSource"); if (getDataSourceClassLoader(context) != null) { - return ConditionOutcome - .match(message.foundExactly("supported DataSource")); + return ConditionOutcome.match(message.foundExactly("supported DataSource")); } - return ConditionOutcome - .noMatch(message.didNotFind("supported DataSource").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("supported DataSource").atAll()); } /** @@ -119,8 +114,7 @@ public class DataSourceAutoConfiguration { * @return the class loader */ private ClassLoader getDataSourceClassLoader(ConditionContext context) { - Class dataSourceClass = DataSourceBuilder - .findType(context.getClassLoader()); + Class dataSourceClass = DataSourceBuilder.findType(context.getClassLoader()); return (dataSourceClass != null) ? dataSourceClass.getClassLoader() : null; } @@ -136,19 +130,14 @@ public class DataSourceAutoConfiguration { private final SpringBootCondition pooledCondition = new PooledDataSourceCondition(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("EmbeddedDataSource"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource"); if (anyMatches(context, metadata, this.pooledCondition)) { - return ConditionOutcome - .noMatch(message.foundExactly("supported pooled data source")); + return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source")); } - EmbeddedDatabaseType type = EmbeddedDatabaseConnection - .get(context.getClassLoader()).getType(); + EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType(); if (type == null) { - return ConditionOutcome - .noMatch(message.didNotFind("embedded database").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll()); } return ConditionOutcome.match(message.found("embedded database").items(type)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java index 441168e7329..c270cbf7f51 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.util.StringUtils; * @author Patryk Kostrzewa * @author Stephane Nicoll */ -class DataSourceBeanCreationFailureAnalyzer - extends AbstractFailureAnalyzer +class DataSourceBeanCreationFailureAnalyzer extends AbstractFailureAnalyzer implements EnvironmentAware { private Environment environment; @@ -45,8 +44,7 @@ class DataSourceBeanCreationFailureAnalyzer } @Override - protected FailureAnalysis analyze(Throwable rootFailure, - DataSourceBeanCreationException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, DataSourceBeanCreationException cause) { return getFailureAnalysis(cause); } @@ -62,8 +60,7 @@ class DataSourceBeanCreationFailureAnalyzer if (!StringUtils.hasText(cause.getProperties().getUrl())) { description.append("'url' attribute is not specified and "); } - description - .append(String.format("no embedded datasource could be configured.%n")); + description.append(String.format("no embedded datasource could be configured.%n")); description.append(String.format("%nReason: %s%n", cause.getMessage())); return description.toString(); } @@ -72,12 +69,11 @@ class DataSourceBeanCreationFailureAnalyzer StringBuilder action = new StringBuilder(); action.append(String.format("Consider the following:%n")); if (EmbeddedDatabaseConnection.NONE == cause.getConnection()) { - action.append(String.format("\tIf you want an embedded database (H2, HSQL or " - + "Derby), please put it on the classpath.%n")); + action.append(String.format( + "\tIf you want an embedded database (H2, HSQL or " + "Derby), please put it on the classpath.%n")); } else { - action.append(String.format("\tReview the configuration of %s%n.", - cause.getConnection())); + action.append(String.format("\tReview the configuration of %s%n.", cause.getConnection())); } action.append("\tIf you have database settings to be loaded from a particular " + "profile you may need to activate it").append(getActiveProfiles()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java index ae2a6045a91..26778687891 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java @@ -39,8 +39,7 @@ import org.springframework.util.StringUtils; abstract class DataSourceConfiguration { @SuppressWarnings("unchecked") - protected static T createDataSource(DataSourceProperties properties, - Class type) { + protected static T createDataSource(DataSourceProperties properties, Class type) { return (T) properties.initializeDataSourceBuilder().type(type).build(); } @@ -50,18 +49,16 @@ abstract class DataSourceConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "org.apache.tomcat.jdbc.pool.DataSource", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource", + matchIfMissing = true) static class Tomcat { @Bean @ConfigurationProperties(prefix = "spring.datasource.tomcat") - public org.apache.tomcat.jdbc.pool.DataSource dataSource( - DataSourceProperties properties) { - org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource( - properties, org.apache.tomcat.jdbc.pool.DataSource.class); - DatabaseDriver databaseDriver = DatabaseDriver - .fromJdbcUrl(properties.determineUrl()); + public org.apache.tomcat.jdbc.pool.DataSource dataSource(DataSourceProperties properties) { + org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource(properties, + org.apache.tomcat.jdbc.pool.DataSource.class); + DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl()); String validationQuery = databaseDriver.getValidationQuery(); if (validationQuery != null) { dataSource.setTestOnBorrow(true); @@ -78,15 +75,14 @@ abstract class DataSourceConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(HikariDataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "com.zaxxer.hikari.HikariDataSource", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource", + matchIfMissing = true) static class Hikari { @Bean @ConfigurationProperties(prefix = "spring.datasource.hikari") public HikariDataSource dataSource(DataSourceProperties properties) { - HikariDataSource dataSource = createDataSource(properties, - HikariDataSource.class); + HikariDataSource dataSource = createDataSource(properties, HikariDataSource.class); if (StringUtils.hasText(properties.getName())) { dataSource.setPoolName(properties.getName()); } @@ -101,17 +97,14 @@ abstract class DataSourceConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(org.apache.commons.dbcp2.BasicDataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "org.apache.commons.dbcp2.BasicDataSource", + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.commons.dbcp2.BasicDataSource", matchIfMissing = true) static class Dbcp2 { @Bean @ConfigurationProperties(prefix = "spring.datasource.dbcp2") - public org.apache.commons.dbcp2.BasicDataSource dataSource( - DataSourceProperties properties) { - return createDataSource(properties, - org.apache.commons.dbcp2.BasicDataSource.class); + public org.apache.commons.dbcp2.BasicDataSource dataSource(DataSourceProperties properties) { + return createDataSource(properties, org.apache.commons.dbcp2.BasicDataSource.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializationConfiguration.java index 60f81714829..fd6e68c6d1a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializationConfiguration.java @@ -30,8 +30,7 @@ import org.springframework.core.type.AnnotationMetadata; * @author Stephane Nicoll */ @Configuration(proxyBeanMethods = false) -@Import({ DataSourceInitializerInvoker.class, - DataSourceInitializationConfiguration.Registrar.class }) +@Import({ DataSourceInitializerInvoker.class, DataSourceInitializationConfiguration.Registrar.class }) class DataSourceInitializationConfiguration { /** diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java index 50e70fcaea0..8ce43395db0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,12 +64,10 @@ class DataSourceInitializer { * @param properties the matching configuration * @param resourceLoader the resource loader to use (can be null) */ - DataSourceInitializer(DataSource dataSource, DataSourceProperties properties, - ResourceLoader resourceLoader) { + DataSourceInitializer(DataSource dataSource, DataSourceProperties properties, ResourceLoader resourceLoader) { this.dataSource = dataSource; this.properties = properties; - this.resourceLoader = (resourceLoader != null) ? resourceLoader - : new DefaultResourceLoader(); + this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(); } /** @@ -92,8 +90,7 @@ class DataSourceInitializer { * @see DataSourceProperties#getSchema() */ public boolean createSchema() { - List scripts = getScripts("spring.datasource.schema", - this.properties.getSchema(), "schema"); + List scripts = getScripts("spring.datasource.schema", this.properties.getSchema(), "schema"); if (!scripts.isEmpty()) { if (!isEnabled()) { logger.debug("Initialization disabled (not running DDL scripts)"); @@ -111,8 +108,7 @@ class DataSourceInitializer { * @see DataSourceProperties#getData() */ public void initSchema() { - List scripts = getScripts("spring.datasource.data", - this.properties.getData(), "data"); + List scripts = getScripts("spring.datasource.data", this.properties.getData(), "data"); if (!scripts.isEmpty()) { if (!isEnabled()) { logger.debug("Initialization disabled (not running data scripts)"); @@ -145,8 +141,7 @@ class DataSourceInitializer { } } - private List getScripts(String propertyName, List resources, - String fallback) { + private List getScripts(String propertyName, List resources, String fallback) { if (resources != null) { return getResources(propertyName, resources, true); } @@ -157,8 +152,7 @@ class DataSourceInitializer { return getResources(propertyName, fallbackResources, false); } - private List getResources(String propertyName, List locations, - boolean validate) { + private List getResources(String propertyName, List locations, boolean validate) { List resources = new ArrayList<>(); for (String location : locations) { for (Resource resource : doGetResources(location)) { @@ -166,8 +160,8 @@ class DataSourceInitializer { resources.add(resource); } else if (validate) { - throw new InvalidConfigurationPropertyValueException(propertyName, - resource, "The specified resource does not exist."); + throw new InvalidConfigurationPropertyValueException(propertyName, resource, + "The specified resource does not exist."); } } } @@ -176,14 +170,13 @@ class DataSourceInitializer { private Resource[] doGetResources(String location) { try { - SortedResourcesFactoryBean factory = new SortedResourcesFactoryBean( - this.resourceLoader, Collections.singletonList(location)); + SortedResourcesFactoryBean factory = new SortedResourcesFactoryBean(this.resourceLoader, + Collections.singletonList(location)); factory.afterPropertiesSet(); return factory.getObject(); } catch (Exception ex) { - throw new IllegalStateException("Unable to load resources from " + location, - ex); + throw new IllegalStateException("Unable to load resources from " + location, ex); } } @@ -203,9 +196,8 @@ class DataSourceInitializer { DataSource dataSource = this.dataSource; if (StringUtils.hasText(username) && StringUtils.hasText(password)) { dataSource = DataSourceBuilder.create(this.properties.getClassLoader()) - .driverClassName(this.properties.determineDriverClassName()) - .url(this.properties.determineUrl()).username(username) - .password(password).build(); + .driverClassName(this.properties.determineDriverClassName()).url(this.properties.determineUrl()) + .username(username).password(password).build(); } DatabasePopulatorUtils.execute(populator, dataSource); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvoker.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvoker.java index 692b2938bf9..d9891f03531 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvoker.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvoker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,11 +34,9 @@ import org.springframework.context.ApplicationListener; * @author Stephane Nicoll * @see DataSourceAutoConfiguration */ -class DataSourceInitializerInvoker - implements ApplicationListener, InitializingBean { +class DataSourceInitializerInvoker implements ApplicationListener, InitializingBean { - private static final Log logger = LogFactory - .getLog(DataSourceInitializerInvoker.class); + private static final Log logger = LogFactory.getLog(DataSourceInitializerInvoker.class); private final ObjectProvider dataSource; @@ -50,8 +48,8 @@ class DataSourceInitializerInvoker private boolean initialized; - DataSourceInitializerInvoker(ObjectProvider dataSource, - DataSourceProperties properties, ApplicationContext applicationContext) { + DataSourceInitializerInvoker(ObjectProvider dataSource, DataSourceProperties properties, + ApplicationContext applicationContext) { this.dataSource = dataSource; this.properties = properties; this.applicationContext = applicationContext; @@ -70,8 +68,7 @@ class DataSourceInitializerInvoker private void initialize(DataSourceInitializer initializer) { try { - this.applicationContext.publishEvent( - new DataSourceSchemaCreatedEvent(initializer.getDataSource())); + this.applicationContext.publishEvent(new DataSourceSchemaCreatedEvent(initializer.getDataSource())); // The listener might not be registered yet, so don't rely on it. if (!this.initialized) { this.dataSourceInitializer.initSchema(); @@ -79,8 +76,7 @@ class DataSourceInitializerInvoker } } catch (IllegalStateException ex) { - logger.warn("Could not send event to complete DataSource initialization (" - + ex.getMessage() + ")"); + logger.warn("Could not send event to complete DataSource initialization (" + ex.getMessage() + ")"); } } @@ -99,8 +95,7 @@ class DataSourceInitializerInvoker if (this.dataSourceInitializer == null) { DataSource ds = this.dataSource.getIfUnique(); if (ds != null) { - this.dataSourceInitializer = new DataSourceInitializer(ds, - this.properties, this.applicationContext); + this.dataSourceInitializer = new DataSourceInitializer(ds, this.properties, this.applicationContext); } } return this.dataSourceInitializer; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerPostProcessor.java index 972cb8c3e5f..0fa272f7cad 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,12 @@ class DataSourceInitializerPostProcessor implements BeanPostProcessor, Ordered { private BeanFactory beanFactory; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { // force initialization of this bean as soon as we see a DataSource this.beanFactory.getBean(DataSourceInitializerInvoker.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfiguration.java index f9129b7d84d..c30fb564a66 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfiguration.java @@ -42,8 +42,7 @@ import org.springframework.jmx.export.MBeanExporter; * @author Stephane Nicoll */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) class DataSourceJmxConfiguration { private static final Log logger = LogFactory.getLog(DataSourceJmxConfiguration.class); @@ -64,11 +63,9 @@ class DataSourceJmxConfiguration { @PostConstruct public void validateMBeans() { - HikariDataSource hikariDataSource = DataSourceUnwrapper - .unwrap(this.dataSource, HikariDataSource.class); + HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(this.dataSource, HikariDataSource.class); if (hikariDataSource != null && hikariDataSource.isRegisterMbeans()) { - this.mBeanExporter - .ifUnique((exporter) -> exporter.addExcludedBean("dataSource")); + this.mBeanExporter.ifUnique((exporter) -> exporter.addExcludedBean("dataSource")); } } @@ -83,8 +80,7 @@ class DataSourceJmxConfiguration { @Bean @ConditionalOnMissingBean(name = "dataSourceMBean") public Object dataSourceMBean(DataSource dataSource) { - DataSourceProxy dataSourceProxy = DataSourceUnwrapper.unwrap(dataSource, - DataSourceProxy.class); + DataSourceProxy dataSourceProxy = DataSourceUnwrapper.unwrap(dataSource, DataSourceProxy.class); if (dataSourceProxy != null) { try { return dataSourceProxy.createPool().getJmxPool(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java index 26b01434854..53748faad47 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -162,8 +162,7 @@ public class DataSourceProperties implements BeanClassLoaderAware, InitializingB @Override public void afterPropertiesSet() throws Exception { - this.embeddedDatabaseConnection = EmbeddedDatabaseConnection - .get(this.classLoader); + this.embeddedDatabaseConnection = EmbeddedDatabaseConnection.get(this.classLoader); } /** @@ -172,9 +171,8 @@ public class DataSourceProperties implements BeanClassLoaderAware, InitializingB * this instance */ public DataSourceBuilder initializeDataSourceBuilder() { - return DataSourceBuilder.create(getClassLoader()).type(getType()) - .driverClassName(determineDriverClassName()).url(determineUrl()) - .username(determineUsername()).password(determinePassword()); + return DataSourceBuilder.create(getClassLoader()).type(getType()).driverClassName(determineDriverClassName()) + .url(determineUrl()).username(determineUsername()).password(determinePassword()); } public String getName() { @@ -221,8 +219,7 @@ public class DataSourceProperties implements BeanClassLoaderAware, InitializingB */ public String determineDriverClassName() { if (StringUtils.hasText(this.driverClassName)) { - Assert.state(driverClassIsLoadable(), - () -> "Cannot load driver class: " + this.driverClassName); + Assert.state(driverClassIsLoadable(), () -> "Cannot load driver class: " + this.driverClassName); return this.driverClassName; } String driverClassName = null; @@ -233,8 +230,7 @@ public class DataSourceProperties implements BeanClassLoaderAware, InitializingB driverClassName = this.embeddedDatabaseConnection.getDriverClassName(); } if (!StringUtils.hasText(driverClassName)) { - throw new DataSourceBeanCreationException( - "Failed to determine a suitable driver class", this, + throw new DataSourceBeanCreationException("Failed to determine a suitable driver class", this, this.embeddedDatabaseConnection); } return driverClassName; @@ -277,11 +273,9 @@ public class DataSourceProperties implements BeanClassLoaderAware, InitializingB return this.url; } String databaseName = determineDatabaseName(); - String url = (databaseName != null) - ? this.embeddedDatabaseConnection.getUrl(databaseName) : null; + String url = (databaseName != null) ? this.embeddedDatabaseConnection.getUrl(databaseName) : null; if (!StringUtils.hasText(url)) { - throw new DataSourceBeanCreationException( - "Failed to determine suitable jdbc url", this, + throw new DataSourceBeanCreationException("Failed to determine suitable jdbc url", this, this.embeddedDatabaseConnection); } return url; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java index 7197519bc0c..33e9acec560 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java @@ -56,10 +56,8 @@ public class DataSourceTransactionManagerAutoConfiguration { @ConditionalOnMissingBean(PlatformTransactionManager.class) public DataSourceTransactionManager transactionManager(DataSource dataSource, ObjectProvider transactionManagerCustomizers) { - DataSourceTransactionManager transactionManager = new DataSourceTransactionManager( - dataSource); - transactionManagerCustomizers.ifAvailable( - (customizers) -> customizers.customize(transactionManager)); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager)); return transactionManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java index ce65ed4c758..36c80a2eb15 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java @@ -44,8 +44,7 @@ public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware { @Bean(destroyMethod = "shutdown") public EmbeddedDatabase dataSource(DataSourceProperties properties) { - return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()) + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()) .setName(properties.determineDatabaseName()).build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java index f75b6ab63a3..412a2d21a56 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,24 +26,20 @@ import org.springframework.jdbc.CannotGetJdbcConnectionException; * * @author Stephane Nicoll */ -class HikariDriverConfigurationFailureAnalyzer - extends AbstractFailureAnalyzer { +class HikariDriverConfigurationFailureAnalyzer extends AbstractFailureAnalyzer { private static final String EXPECTED_MESSAGE = "Failed to obtain JDBC Connection:" + " cannot use driverClassName and dataSourceClassName together."; @Override - protected FailureAnalysis analyze(Throwable rootFailure, - CannotGetJdbcConnectionException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, CannotGetJdbcConnectionException cause) { if (!EXPECTED_MESSAGE.equals(cause.getMessage())) { return null; } return new FailureAnalysis( - "Configuration of the Hikari connection pool failed: " - + "'dataSourceClassName' is not supported.", + "Configuration of the Hikari connection pool failed: " + "'dataSourceClassName' is not supported.", "Spring Boot auto-configures only a driver and can't specify a custom " - + "DataSource. Consider configuring the Hikari DataSource in " - + "your own configuration.", + + "DataSource. Consider configuring the Hikari DataSource in " + "your own configuration.", cause); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcOperationsDependsOnPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcOperationsDependsOnPostProcessor.java index 80ef213210e..c8062b32f17 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcOperationsDependsOnPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcOperationsDependsOnPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.jdbc.core.JdbcOperations; * @since 2.0.4 * @see BeanDefinition#setDependsOn(String[]) */ -public class JdbcOperationsDependsOnPostProcessor - extends AbstractDependsOnBeanFactoryPostProcessor { +public class JdbcOperationsDependsOnPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { public JdbcOperationsDependsOnPostProcessor(String... dependsOn) { super(JdbcOperations.class, dependsOn); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfiguration.java index 71cef13e2c6..2fdb9af5425 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfiguration.java @@ -43,8 +43,7 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; @ConditionalOnSingleCandidate(DataSource.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(JdbcProperties.class) -@Import({ JdbcTemplateConfiguration.class, - NamedParameterJdbcTemplateConfiguration.class }) +@Import({ JdbcTemplateConfiguration.class, NamedParameterJdbcTemplateConfiguration.class }) public class JdbcTemplateAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java index 7ce0afbd048..40314d313ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java @@ -41,8 +41,7 @@ import org.springframework.jmx.support.JmxUtils; * @since 1.2.0 */ @Configuration(proxyBeanMethods = false) -@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, - DataSourceAutoConfiguration.class }) +@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, DataSourceAutoConfiguration.class }) @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }) @ConditionalOnProperty(prefix = "spring.datasource", name = "jndi-name") @EnableConfigurationProperties(DataSourceProperties.class) @@ -50,18 +49,15 @@ public class JndiDataSourceAutoConfiguration { @Bean(destroyMethod = "") @ConditionalOnMissingBean - public DataSource dataSource(DataSourceProperties properties, - ApplicationContext context) { + public DataSource dataSource(DataSourceProperties properties, ApplicationContext context) { JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); DataSource dataSource = dataSourceLookup.getDataSource(properties.getJndiName()); excludeMBeanIfNecessary(dataSource, "dataSource", context); return dataSource; } - private void excludeMBeanIfNecessary(Object candidate, String beanName, - ApplicationContext context) { - for (MBeanExporter mbeanExporter : context.getBeansOfType(MBeanExporter.class) - .values()) { + private void excludeMBeanIfNecessary(Object candidate, String beanName, ApplicationContext context) { + for (MBeanExporter mbeanExporter : context.getBeansOfType(MBeanExporter.class).values()) { if (JmxUtils.isMBean(candidate.getClass())) { mbeanExporter.addExcludedBean(beanName); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcOperationsDependsOnPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcOperationsDependsOnPostProcessor.java index 23c2da14000..a8bbc2432f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcOperationsDependsOnPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcOperationsDependsOnPostProcessor.java @@ -30,8 +30,7 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; * @since 2.1.4 * @see BeanDefinition#setDependsOn(String[]) */ -public class NamedParameterJdbcOperationsDependsOnPostProcessor - extends AbstractDependsOnBeanFactoryPostProcessor { +public class NamedParameterJdbcOperationsDependsOnPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { public NamedParameterJdbcOperationsDependsOnPostProcessor(String... dependsOn) { super(NamedParameterJdbcOperations.class, dependsOn); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcTemplateConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcTemplateConfiguration.java index d6bd7afc1ba..0512fe9a28c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcTemplateConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/NamedParameterJdbcTemplateConfiguration.java @@ -37,8 +37,7 @@ class NamedParameterJdbcTemplateConfiguration { @Bean @Primary - public NamedParameterJdbcTemplate namedParameterJdbcTemplate( - JdbcTemplate jdbcTemplate) { + public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) { return new NamedParameterJdbcTemplate(jdbcTemplate); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java index c90e02604b6..ccc56ca16f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java @@ -55,8 +55,7 @@ import org.springframework.util.StringUtils; @Configuration(proxyBeanMethods = false) @AutoConfigureBefore(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(DataSourceProperties.class) -@ConditionalOnClass({ DataSource.class, TransactionManager.class, - EmbeddedDatabaseType.class }) +@ConditionalOnClass({ DataSource.class, TransactionManager.class, EmbeddedDatabaseType.class }) @ConditionalOnBean(XADataSourceWrapper.class) @ConditionalOnMissingBean(DataSource.class) public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { @@ -64,11 +63,9 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { private ClassLoader classLoader; @Bean - public DataSource dataSource(XADataSourceWrapper wrapper, - DataSourceProperties properties, ObjectProvider xaDataSource) - throws Exception { - return wrapper.wrapDataSource( - xaDataSource.getIfAvailable(() -> createXaDataSource(properties))); + public DataSource dataSource(XADataSourceWrapper wrapper, DataSourceProperties properties, + ObjectProvider xaDataSource) throws Exception { + return wrapper.wrapDataSource(xaDataSource.getIfAvailable(() -> createXaDataSource(properties))); } @Override @@ -79,11 +76,9 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { private XADataSource createXaDataSource(DataSourceProperties properties) { String className = properties.getXa().getDataSourceClassName(); if (!StringUtils.hasLength(className)) { - className = DatabaseDriver.fromJdbcUrl(properties.determineUrl()) - .getXaDataSourceClassName(); + className = DatabaseDriver.fromJdbcUrl(properties.determineUrl()).getXaDataSourceClassName(); } - Assert.state(StringUtils.hasLength(className), - "No XA DataSource class name specified"); + Assert.state(StringUtils.hasLength(className), "No XA DataSource class name specified"); XADataSource dataSource = createXaDataSourceInstance(className); bindXaProperties(dataSource, properties); return dataSource; @@ -97,19 +92,16 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { return (XADataSource) instance; } catch (Exception ex) { - throw new IllegalStateException( - "Unable to create XADataSource instance from '" + className + "'"); + throw new IllegalStateException("Unable to create XADataSource instance from '" + className + "'"); } } - private void bindXaProperties(XADataSource target, - DataSourceProperties dataSourceProperties) { + private void bindXaProperties(XADataSource target, DataSourceProperties dataSourceProperties) { Binder binder = new Binder(getBinderSource(dataSourceProperties)); binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(target)); } - private ConfigurationPropertySource getBinderSource( - DataSourceProperties dataSourceProperties) { + private ConfigurationPropertySource getBinderSource(DataSourceProperties dataSourceProperties) { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("user", dataSourceProperties.determineUsername()); source.put("password", dataSourceProperties.determinePassword()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java index 4aef9867f6c..b095859cb64 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java @@ -45,8 +45,8 @@ public class DataSourcePoolMetadataProvidersConfiguration { @Bean public DataSourcePoolMetadataProvider tomcatPoolDataSourceMetadataProvider() { return (dataSource) -> { - org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = DataSourceUnwrapper - .unwrap(dataSource, org.apache.tomcat.jdbc.pool.DataSource.class); + org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = DataSourceUnwrapper.unwrap(dataSource, + org.apache.tomcat.jdbc.pool.DataSource.class); if (tomcatDataSource != null) { return new TomcatDataSourcePoolMetadata(tomcatDataSource); } @@ -63,8 +63,7 @@ public class DataSourcePoolMetadataProvidersConfiguration { @Bean public DataSourcePoolMetadataProvider hikariPoolDataSourceMetadataProvider() { return (dataSource) -> { - HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, - HikariDataSource.class); + HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class); if (hikariDataSource != null) { return new HikariDataSourcePoolMetadata(hikariDataSource); } @@ -81,8 +80,7 @@ public class DataSourcePoolMetadataProvidersConfiguration { @Bean public DataSourcePoolMetadataProvider commonsDbcp2PoolDataSourceMetadataProvider() { return (dataSource) -> { - BasicDataSource dbcpDataSource = DataSourceUnwrapper.unwrap(dataSource, - BasicDataSource.class); + BasicDataSource dbcpDataSource = DataSourceUnwrapper.unwrap(dataSource, BasicDataSource.class); if (dbcpDataSource != null) { return new CommonsDbcp2DataSourcePoolMetadata(dbcpDataSource); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java index 38222be5d5e..fd095bd432a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java @@ -109,8 +109,7 @@ public class JerseyAutoConfiguration implements ServletContextAware { } private void customize() { - this.customizers.orderedStream() - .forEach((customizer) -> customizer.customize(this.config)); + this.customizers.orderedStream().forEach((customizer) -> customizer.customize(this.config)); } @Bean @@ -126,23 +125,18 @@ public class JerseyAutoConfiguration implements ServletContextAware { @Bean @ConditionalOnMissingBean public JerseyApplicationPath jerseyApplicationPath() { - return new DefaultJerseyApplicationPath(this.jersey.getApplicationPath(), - this.config); + return new DefaultJerseyApplicationPath(this.jersey.getApplicationPath(), this.config); } @Bean @ConditionalOnMissingBean(name = "jerseyFilterRegistration") - @ConditionalOnProperty(prefix = "spring.jersey", name = "type", - havingValue = "filter") - public FilterRegistrationBean jerseyFilterRegistration( - JerseyApplicationPath applicationPath) { + @ConditionalOnProperty(prefix = "spring.jersey", name = "type", havingValue = "filter") + public FilterRegistrationBean jerseyFilterRegistration(JerseyApplicationPath applicationPath) { FilterRegistrationBean registration = new FilterRegistrationBean<>(); registration.setFilter(new ServletContainer(this.config)); - registration.setUrlPatterns( - Collections.singletonList(applicationPath.getUrlMapping())); + registration.setUrlPatterns(Collections.singletonList(applicationPath.getUrlMapping())); registration.setOrder(this.jersey.getFilter().getOrder()); - registration.addInitParameter(ServletProperties.FILTER_CONTEXT_PATH, - stripPattern(applicationPath.getPath())); + registration.addInitParameter(ServletProperties.FILTER_CONTEXT_PATH, stripPattern(applicationPath.getPath())); addInitParameters(registration); registration.setName("jerseyFilter"); registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); @@ -158,10 +152,8 @@ public class JerseyAutoConfiguration implements ServletContextAware { @Bean @ConditionalOnMissingBean(name = "jerseyServletRegistration") - @ConditionalOnProperty(prefix = "spring.jersey", name = "type", - havingValue = "servlet", matchIfMissing = true) - public ServletRegistrationBean jerseyServletRegistration( - JerseyApplicationPath applicationPath) { + @ConditionalOnProperty(prefix = "spring.jersey", name = "type", havingValue = "servlet", matchIfMissing = true) + public ServletRegistrationBean jerseyServletRegistration(JerseyApplicationPath applicationPath) { ServletRegistrationBean registration = new ServletRegistrationBean<>( new ServletContainer(this.config), applicationPath.getUrlMapping()); addInitParameters(registration); @@ -181,20 +173,17 @@ public class JerseyAutoConfiguration implements ServletContextAware { @Override public void setServletContext(ServletContext servletContext) { String servletRegistrationName = getServletRegistrationName(); - ServletRegistration registration = servletContext - .getServletRegistration(servletRegistrationName); + ServletRegistration registration = servletContext.getServletRegistration(servletRegistrationName); if (registration != null) { if (logger.isInfoEnabled()) { - logger.info("Configuring existing registration for Jersey servlet '" - + servletRegistrationName + "'"); + logger.info("Configuring existing registration for Jersey servlet '" + servletRegistrationName + "'"); } registration.setInitParameters(this.jersey.getInit()); } } @Order(Ordered.HIGHEST_PRECEDENCE) - public static final class JerseyWebApplicationInitializer - implements WebApplicationInitializer { + public static final class JerseyWebApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { @@ -211,12 +200,10 @@ public class JerseyAutoConfiguration implements ServletContextAware { static class JacksonResourceConfigCustomizer { @Bean - public ResourceConfigCustomizer resourceConfigCustomizer( - final ObjectMapper objectMapper) { + public ResourceConfigCustomizer resourceConfigCustomizer(final ObjectMapper objectMapper) { return (ResourceConfig config) -> { config.register(JacksonFeature.class); - config.register(new ObjectMapperContextResolver(objectMapper), - ContextResolver.class); + config.register(new ObjectMapperContextResolver(objectMapper), ContextResolver.class); }; } @@ -229,22 +216,18 @@ public class JerseyAutoConfiguration implements ServletContextAware { JaxbAnnotationIntrospector jaxbAnnotationIntrospector = new JaxbAnnotationIntrospector( objectMapper.getTypeFactory()); objectMapper.setAnnotationIntrospectors( - createPair(objectMapper.getSerializationConfig(), - jaxbAnnotationIntrospector), - createPair(objectMapper.getDeserializationConfig(), - jaxbAnnotationIntrospector)); + createPair(objectMapper.getSerializationConfig(), jaxbAnnotationIntrospector), + createPair(objectMapper.getDeserializationConfig(), jaxbAnnotationIntrospector)); } private AnnotationIntrospector createPair(MapperConfig config, JaxbAnnotationIntrospector jaxbAnnotationIntrospector) { - return AnnotationIntrospector.pair(config.getAnnotationIntrospector(), - jaxbAnnotationIntrospector); + return AnnotationIntrospector.pair(config.getAnnotationIntrospector(), jaxbAnnotationIntrospector); } } - private static final class ObjectMapperContextResolver - implements ContextResolver { + private static final class ObjectMapperContextResolver implements ContextResolver { private final ObjectMapper objectMapper; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java index d022639e52d..414ead5b7aa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,8 +81,7 @@ public final class DefaultJmsListenerContainerFactoryConfigurer { * @param factory the {@link DefaultJmsListenerContainerFactory} instance to configure * @param connectionFactory the {@link ConnectionFactory} to use */ - public void configure(DefaultJmsListenerContainerFactory factory, - ConnectionFactory connectionFactory) { + public void configure(DefaultJmsListenerContainerFactory factory, ConnectionFactory connectionFactory) { Assert.notNull(factory, "Factory must not be null"); Assert.notNull(connectionFactory, "ConnectionFactory must not be null"); factory.setConnectionFactory(connectionFactory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java index b7ba8866836..11a8b60e68d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java @@ -52,10 +52,9 @@ class JmsAnnotationDrivenConfiguration { private final JmsProperties properties; - JmsAnnotationDrivenConfiguration( - ObjectProvider destinationResolver, - ObjectProvider transactionManager, - ObjectProvider messageConverter, JmsProperties properties) { + JmsAnnotationDrivenConfiguration(ObjectProvider destinationResolver, + ObjectProvider transactionManager, ObjectProvider messageConverter, + JmsProperties properties) { this.destinationResolver = destinationResolver; this.transactionManager = transactionManager; this.messageConverter = messageConverter; @@ -77,8 +76,7 @@ class JmsAnnotationDrivenConfiguration { @ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnMissingBean(name = "jmsListenerContainerFactory") public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; @@ -86,8 +84,7 @@ class JmsAnnotationDrivenConfiguration { @Configuration(proxyBeanMethods = false) @EnableJms - @ConditionalOnMissingBean( - name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean(name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) protected static class EnableJmsConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java index 70d3a86226d..bb8c2c7e98d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java @@ -76,26 +76,21 @@ public class JmsAutoConfiguration { PropertyMapper map = PropertyMapper.get(); JmsTemplate template = new JmsTemplate(connectionFactory); template.setPubSubDomain(this.properties.isPubSubDomain()); - map.from(this.destinationResolver::getIfUnique).whenNonNull() - .to(template::setDestinationResolver); - map.from(this.messageConverter::getIfUnique).whenNonNull() - .to(template::setMessageConverter); + map.from(this.destinationResolver::getIfUnique).whenNonNull().to(template::setDestinationResolver); + map.from(this.messageConverter::getIfUnique).whenNonNull().to(template::setMessageConverter); mapTemplateProperties(this.properties.getTemplate(), template); return template; } private void mapTemplateProperties(Template properties, JmsTemplate template) { PropertyMapper map = PropertyMapper.get(); - map.from(properties::getDefaultDestination).whenNonNull() - .to(template::setDefaultDestinationName); - map.from(properties::getDeliveryDelay).whenNonNull().as(Duration::toMillis) - .to(template::setDeliveryDelay); + map.from(properties::getDefaultDestination).whenNonNull().to(template::setDefaultDestinationName); + map.from(properties::getDeliveryDelay).whenNonNull().as(Duration::toMillis).to(template::setDeliveryDelay); map.from(properties::determineQosEnabled).to(template::setExplicitQosEnabled); map.from(properties::getDeliveryMode).whenNonNull().as(DeliveryMode::getValue) .to(template::setDeliveryMode); map.from(properties::getPriority).whenNonNull().to(template::setPriority); - map.from(properties::getTimeToLive).whenNonNull().as(Duration::toMillis) - .to(template::setTimeToLive); + map.from(properties::getTimeToLive).whenNonNull().as(Duration::toMillis).to(template::setTimeToLive); map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) .to(template::setReceiveTimeout); } @@ -110,19 +105,15 @@ public class JmsAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnSingleCandidate(JmsTemplate.class) - public JmsMessagingTemplate jmsMessagingTemplate(JmsProperties properties, - JmsTemplate jmsTemplate) { - JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate( - jmsTemplate); + public JmsMessagingTemplate jmsMessagingTemplate(JmsProperties properties, JmsTemplate jmsTemplate) { + JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate(jmsTemplate); mapTemplateProperties(properties.getTemplate(), messagingTemplate); return messagingTemplate; } - private void mapTemplateProperties(Template properties, - JmsMessagingTemplate messagingTemplate) { + private void mapTemplateProperties(Template properties, JmsMessagingTemplate messagingTemplate) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(properties::getDefaultDestination) - .to(messagingTemplate::setDefaultDestinationName); + map.from(properties::getDefaultDestination).to(messagingTemplate::setDefaultDestinationName); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java index 624ec3d41ac..27ceec82fcf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ public class JmsPoolConnectionFactoryFactory { private final JmsPoolConnectionFactoryProperties properties; - public JmsPoolConnectionFactoryFactory( - JmsPoolConnectionFactoryProperties properties) { + public JmsPoolConnectionFactoryFactory(JmsPoolConnectionFactoryProperties properties) { this.properties = properties; } @@ -42,30 +41,25 @@ public class JmsPoolConnectionFactoryFactory { * @param connectionFactory the connection factory to wrap * @return a pooled connection factory */ - public JmsPoolConnectionFactory createPooledConnectionFactory( - ConnectionFactory connectionFactory) { + public JmsPoolConnectionFactory createPooledConnectionFactory(ConnectionFactory connectionFactory) { JmsPoolConnectionFactory pooledConnectionFactory = new JmsPoolConnectionFactory(); pooledConnectionFactory.setConnectionFactory(connectionFactory); - pooledConnectionFactory - .setBlockIfSessionPoolIsFull(this.properties.isBlockIfFull()); + pooledConnectionFactory.setBlockIfSessionPoolIsFull(this.properties.isBlockIfFull()); if (this.properties.getBlockIfFullTimeout() != null) { - pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout( - this.properties.getBlockIfFullTimeout().toMillis()); + pooledConnectionFactory + .setBlockIfSessionPoolIsFullTimeout(this.properties.getBlockIfFullTimeout().toMillis()); } if (this.properties.getIdleTimeout() != null) { - pooledConnectionFactory.setConnectionIdleTimeout( - (int) this.properties.getIdleTimeout().toMillis()); + pooledConnectionFactory.setConnectionIdleTimeout((int) this.properties.getIdleTimeout().toMillis()); } pooledConnectionFactory.setMaxConnections(this.properties.getMaxConnections()); - pooledConnectionFactory.setMaxSessionsPerConnection( - this.properties.getMaxSessionsPerConnection()); + pooledConnectionFactory.setMaxSessionsPerConnection(this.properties.getMaxSessionsPerConnection()); if (this.properties.getTimeBetweenExpirationCheck() != null) { - pooledConnectionFactory.setConnectionCheckInterval( - this.properties.getTimeBetweenExpirationCheck().toMillis()); + pooledConnectionFactory + .setConnectionCheckInterval(this.properties.getTimeBetweenExpirationCheck().toMillis()); } - pooledConnectionFactory - .setUseAnonymousProducers(this.properties.isUseAnonymousProducers()); + pooledConnectionFactory.setUseAnonymousProducers(this.properties.isUseAnonymousProducers()); return pooledConnectionFactory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java index 4fe1ebc50c9..4c329b7b750 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -190,8 +190,7 @@ public class JmsProperties { if (this.concurrency == null) { return (this.maxConcurrency != null) ? "1-" + this.maxConcurrency : null; } - return ((this.maxConcurrency != null) - ? this.concurrency + "-" + this.maxConcurrency + return ((this.maxConcurrency != null) ? this.concurrency + "-" + this.maxConcurrency : String.valueOf(this.concurrency)); } @@ -283,8 +282,7 @@ public class JmsProperties { if (this.qosEnabled != null) { return this.qosEnabled; } - return (getDeliveryMode() != null || getPriority() != null - || getTimeToLive() != null); + return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null); } public Boolean getQosEnabled() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java index 26bbb275813..73733af06cc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java @@ -52,23 +52,18 @@ import org.springframework.util.StringUtils; public class JndiConnectionFactoryAutoConfiguration { // Keep these in sync with the condition below - private static final String[] JNDI_LOCATIONS = { "java:/JmsXA", - "java:/XAConnectionFactory" }; + private static final String[] JNDI_LOCATIONS = { "java:/JmsXA", "java:/XAConnectionFactory" }; @Bean - public ConnectionFactory connectionFactory(JmsProperties properties) - throws NamingException { - JndiLocatorDelegate jndiLocatorDelegate = JndiLocatorDelegate - .createDefaultResourceRefLocator(); + public ConnectionFactory connectionFactory(JmsProperties properties) throws NamingException { + JndiLocatorDelegate jndiLocatorDelegate = JndiLocatorDelegate.createDefaultResourceRefLocator(); if (StringUtils.hasLength(properties.getJndiName())) { - return jndiLocatorDelegate.lookup(properties.getJndiName(), - ConnectionFactory.class); + return jndiLocatorDelegate.lookup(properties.getJndiName(), ConnectionFactory.class); } return findJndiConnectionFactory(jndiLocatorDelegate); } - private ConnectionFactory findJndiConnectionFactory( - JndiLocatorDelegate jndiLocatorDelegate) { + private ConnectionFactory findJndiConnectionFactory(JndiLocatorDelegate jndiLocatorDelegate) { for (String name : JNDI_LOCATIONS) { try { return jndiLocatorDelegate.lookup(name, ConnectionFactory.class); @@ -78,8 +73,7 @@ public class JndiConnectionFactoryAutoConfiguration { } } throw new IllegalStateException( - "Unable to find ConnectionFactory in JNDI locations " - + Arrays.asList(JNDI_LOCATIONS)); + "Unable to find ConnectionFactory in JNDI locations " + Arrays.asList(JNDI_LOCATIONS)); } /** diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java index c51566948a1..637dbabe492 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java @@ -47,8 +47,7 @@ import org.springframework.context.annotation.Import; @ConditionalOnClass({ ConnectionFactory.class, ActiveMQConnectionFactory.class }) @ConditionalOnMissingBean(ConnectionFactory.class) @EnableConfigurationProperties({ ActiveMQProperties.class, JmsProperties.class }) -@Import({ ActiveMQXAConnectionFactoryConfiguration.class, - ActiveMQConnectionFactoryConfiguration.class }) +@Import({ ActiveMQXAConnectionFactoryConfiguration.class, ActiveMQConnectionFactoryConfiguration.class }) public class ActiveMQAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java index 342ac862823..9db3930904b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java @@ -51,8 +51,8 @@ class ActiveMQConnectionFactoryConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CachingConnectionFactory.class) - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", + matchIfMissing = true) static class SimpleConnectionFactoryConfiguration { private final ActiveMQProperties properties; @@ -62,18 +62,16 @@ class ActiveMQConnectionFactoryConfiguration { SimpleConnectionFactoryConfiguration(ActiveMQProperties properties, ObjectProvider connectionFactoryCustomizers) { this.properties = properties; - this.connectionFactoryCustomizers = connectionFactoryCustomizers - .orderedStream().collect(Collectors.toList()); + this.connectionFactoryCustomizers = connectionFactoryCustomizers.orderedStream() + .collect(Collectors.toList()); } @Bean - @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", - havingValue = "true", matchIfMissing = true) - public CachingConnectionFactory cachingJmsConnectionFactory( - JmsProperties jmsProperties) { + @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", + matchIfMissing = true) + public CachingConnectionFactory cachingJmsConnectionFactory(JmsProperties jmsProperties) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); - CachingConnectionFactory connectionFactory = new CachingConnectionFactory( - createConnectionFactory()); + CachingConnectionFactory connectionFactory = new CachingConnectionFactory(createConnectionFactory()); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); @@ -81,16 +79,14 @@ class ActiveMQConnectionFactoryConfiguration { } @Bean - @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", - havingValue = "false") + @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "false") public ActiveMQConnectionFactory jmsConnectionFactory() { return createConnectionFactory(); } private ActiveMQConnectionFactory createConnectionFactory() { - return new ActiveMQConnectionFactoryFactory(this.properties, - this.connectionFactoryCustomizers) - .createConnectionFactory(ActiveMQConnectionFactory.class); + return new ActiveMQConnectionFactoryFactory(this.properties, this.connectionFactoryCustomizers) + .createConnectionFactory(ActiveMQConnectionFactory.class); } } @@ -100,13 +96,11 @@ class ActiveMQConnectionFactoryConfiguration { static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "true", matchIfMissing = false) - public JmsPoolConnectionFactory pooledJmsConnectionFactory( - ActiveMQProperties properties, + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "true", + matchIfMissing = false) + public JmsPoolConnectionFactory pooledJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider factoryCustomizers) { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory( - properties, + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) .createConnectionFactory(ActiveMQConnectionFactory.class); return new JmsPoolConnectionFactoryFactory(properties.getPool()) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java index d5d462f3fd0..b24d1080df9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,23 +48,19 @@ class ActiveMQConnectionFactoryFactory { List factoryCustomizers) { Assert.notNull(properties, "Properties must not be null"); this.properties = properties; - this.factoryCustomizers = (factoryCustomizers != null) ? factoryCustomizers - : Collections.emptyList(); + this.factoryCustomizers = (factoryCustomizers != null) ? factoryCustomizers : Collections.emptyList(); } - public T createConnectionFactory( - Class factoryClass) { + public T createConnectionFactory(Class factoryClass) { try { return doCreateConnectionFactory(factoryClass); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to create " + "ActiveMQConnectionFactory", ex); + throw new IllegalStateException("Unable to create " + "ActiveMQConnectionFactory", ex); } } - private T doCreateConnectionFactory( - Class factoryClass) throws Exception { + private T doCreateConnectionFactory(Class factoryClass) throws Exception { T factory = createConnectionFactoryInstance(factoryClass); if (this.properties.getCloseTimeout() != null) { factory.setCloseTimeout((int) this.properties.getCloseTimeout().toMillis()); @@ -84,15 +80,14 @@ class ActiveMQConnectionFactoryFactory { return factory; } - private T createConnectionFactoryInstance( - Class factoryClass) throws InstantiationException, IllegalAccessException, - InvocationTargetException, NoSuchMethodException { + private T createConnectionFactoryInstance(Class factoryClass) + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String brokerUrl = determineBrokerUrl(); String user = this.properties.getUser(); String password = this.properties.getPassword(); if (StringUtils.hasLength(user) && StringUtils.hasLength(password)) { - return factoryClass.getConstructor(String.class, String.class, String.class) - .newInstance(user, password, brokerUrl); + return factoryClass.getConstructor(String.class, String.class, String.class).newInstance(user, password, + brokerUrl); } return factoryClass.getConstructor(String.class).newInstance(brokerUrl); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java index 07e0f362c23..7e9dc6be66f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java @@ -50,20 +50,18 @@ class ActiveMQXAConnectionFactoryConfiguration { @Primary @Bean(name = { "jmsConnectionFactory", "xaJmsConnectionFactory" }) public ConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, - ObjectProvider factoryCustomizers, - XAConnectionFactoryWrapper wrapper) throws Exception { - ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory( - properties, + ObjectProvider factoryCustomizers, XAConnectionFactoryWrapper wrapper) + throws Exception { + ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) .createConnectionFactory(ActiveMQXAConnectionFactory.class); return wrapper.wrapConnectionFactory(connectionFactory); } @Bean - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "false", matchIfMissing = true) - public ActiveMQConnectionFactory nonXaJmsConnectionFactory( - ActiveMQProperties properties, + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", + matchIfMissing = true) + public ActiveMQConnectionFactory nonXaJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider factoryCustomizers) { return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java index c664ce2466f..712a310df03 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java @@ -49,8 +49,7 @@ import org.springframework.context.annotation.Import; @ConditionalOnClass({ ConnectionFactory.class, ActiveMQConnectionFactory.class }) @ConditionalOnMissingBean(ConnectionFactory.class) @EnableConfigurationProperties({ ArtemisProperties.class, JmsProperties.class }) -@Import({ ArtemisEmbeddedServerConfiguration.class, - ArtemisXAConnectionFactoryConfiguration.class, +@Import({ ArtemisEmbeddedServerConfiguration.class, ArtemisXAConnectionFactoryConfiguration.class, ArtemisConnectionFactoryConfiguration.class }) public class ArtemisAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java index f16dd4eee37..8c59c6efc20 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java @@ -45,28 +45,25 @@ class ArtemisConnectionFactoryConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CachingConnectionFactory.class) - @ConditionalOnProperty(prefix = "spring.artemis.pool", name = "enabled", - havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.artemis.pool", name = "enabled", havingValue = "false", + matchIfMissing = true) static class SimpleConnectionFactoryConfiguration { private final ArtemisProperties properties; private final ListableBeanFactory beanFactory; - SimpleConnectionFactoryConfiguration(ArtemisProperties properties, - ListableBeanFactory beanFactory) { + SimpleConnectionFactoryConfiguration(ArtemisProperties properties, ListableBeanFactory beanFactory) { this.properties = properties; this.beanFactory = beanFactory; } @Bean - @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", - havingValue = "true", matchIfMissing = true) - public CachingConnectionFactory cachingJmsConnectionFactory( - JmsProperties jmsProperties) { + @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", + matchIfMissing = true) + public CachingConnectionFactory cachingJmsConnectionFactory(JmsProperties jmsProperties) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); - CachingConnectionFactory connectionFactory = new CachingConnectionFactory( - createConnectionFactory()); + CachingConnectionFactory connectionFactory = new CachingConnectionFactory(createConnectionFactory()); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); @@ -74,8 +71,7 @@ class ArtemisConnectionFactoryConfiguration { } @Bean - @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", - havingValue = "false") + @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "false") public ActiveMQConnectionFactory jmsConnectionFactory() { return createConnectionFactory(); } @@ -92,13 +88,12 @@ class ArtemisConnectionFactoryConfiguration { static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") - @ConditionalOnProperty(prefix = "spring.artemis.pool", name = "enabled", - havingValue = "true", matchIfMissing = false) - public JmsPoolConnectionFactory pooledJmsConnectionFactory( - ListableBeanFactory beanFactory, ArtemisProperties properties) { - ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory( - beanFactory, properties) - .createConnectionFactory(ActiveMQConnectionFactory.class); + @ConditionalOnProperty(prefix = "spring.artemis.pool", name = "enabled", havingValue = "true", + matchIfMissing = false) + public JmsPoolConnectionFactory pooledJmsConnectionFactory(ListableBeanFactory beanFactory, + ArtemisProperties properties) { + ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties) + .createConnectionFactory(ActiveMQConnectionFactory.class); return new JmsPoolConnectionFactoryFactory(properties.getPool()) .createPooledConnectionFactory(connectionFactory); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java index 0bcbb0aab9d..069856ccfce 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,23 +49,20 @@ class ArtemisConnectionFactoryFactory { private final ListableBeanFactory beanFactory; - ArtemisConnectionFactoryFactory(ListableBeanFactory beanFactory, - ArtemisProperties properties) { + ArtemisConnectionFactoryFactory(ListableBeanFactory beanFactory, ArtemisProperties properties) { Assert.notNull(beanFactory, "BeanFactory must not be null"); Assert.notNull(properties, "Properties must not be null"); this.beanFactory = beanFactory; this.properties = properties; } - public T createConnectionFactory( - Class factoryClass) { + public T createConnectionFactory(Class factoryClass) { try { startEmbeddedJms(); return doCreateConnectionFactory(factoryClass); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to create " + "ActiveMQConnectionFactory", ex); + throw new IllegalStateException("Unable to create " + "ActiveMQConnectionFactory", ex); } } @@ -80,8 +77,7 @@ class ArtemisConnectionFactoryFactory { } } - private T doCreateConnectionFactory( - Class factoryClass) throws Exception { + private T doCreateConnectionFactory(Class factoryClass) throws Exception { ArtemisMode mode = this.properties.getMode(); if (mode == null) { mode = deduceMode(); @@ -97,42 +93,35 @@ class ArtemisConnectionFactoryFactory { * @return the mode */ private ArtemisMode deduceMode() { - if (this.properties.getEmbedded().isEnabled() - && ClassUtils.isPresent(EMBEDDED_JMS_CLASS, null)) { + if (this.properties.getEmbedded().isEnabled() && ClassUtils.isPresent(EMBEDDED_JMS_CLASS, null)) { return ArtemisMode.EMBEDDED; } return ArtemisMode.NATIVE; } - private T createEmbeddedConnectionFactory( - Class factoryClass) throws Exception { + private T createEmbeddedConnectionFactory(Class factoryClass) + throws Exception { try { TransportConfiguration transportConfiguration = new TransportConfiguration( - InVMConnectorFactory.class.getName(), - this.properties.getEmbedded().generateTransportParameters()); - ServerLocator serviceLocator = ActiveMQClient - .createServerLocatorWithoutHA(transportConfiguration); - return factoryClass.getConstructor(ServerLocator.class) - .newInstance(serviceLocator); + InVMConnectorFactory.class.getName(), this.properties.getEmbedded().generateTransportParameters()); + ServerLocator serviceLocator = ActiveMQClient.createServerLocatorWithoutHA(transportConfiguration); + return factoryClass.getConstructor(ServerLocator.class).newInstance(serviceLocator); } catch (NoClassDefFoundError ex) { throw new IllegalStateException("Unable to create InVM " - + "Artemis connection, ensure that artemis-jms-server.jar " - + "is in the classpath", ex); + + "Artemis connection, ensure that artemis-jms-server.jar " + "is in the classpath", ex); } } - private T createNativeConnectionFactory( - Class factoryClass) throws Exception { + private T createNativeConnectionFactory(Class factoryClass) + throws Exception { Map params = new HashMap<>(); params.put(TransportConstants.HOST_PROP_NAME, this.properties.getHost()); params.put(TransportConstants.PORT_PROP_NAME, this.properties.getPort()); TransportConfiguration transportConfiguration = new TransportConfiguration( NettyConnectorFactory.class.getName(), params); - Constructor constructor = factoryClass.getConstructor(boolean.class, - TransportConfiguration[].class); - T connectionFactory = constructor.newInstance(false, - new TransportConfiguration[] { transportConfiguration }); + Constructor constructor = factoryClass.getConstructor(boolean.class, TransportConfiguration[].class); + T connectionFactory = constructor.newInstance(false, new TransportConfiguration[] { transportConfiguration }); String user = this.properties.getUser(); if (StringUtils.hasText(user)) { connectionFactory.setUser(user); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java index b668a1e8881..0438acfa3e3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ import org.apache.commons.logging.LogFactory; */ class ArtemisEmbeddedConfigurationFactory { - private static final Log logger = LogFactory - .getLog(ArtemisEmbeddedConfigurationFactory.class); + private static final Log logger = LogFactory.getLog(ArtemisEmbeddedConfigurationFactory.class); private final ArtemisProperties.Embedded properties; @@ -61,29 +60,24 @@ class ArtemisEmbeddedConfigurationFactory { configuration.setBindingsDirectory(dataDir + "/bindings"); configuration.setPagingDirectory(dataDir + "/paging"); } - TransportConfiguration transportConfiguration = new TransportConfiguration( - InVMAcceptorFactory.class.getName(), + TransportConfiguration transportConfiguration = new TransportConfiguration(InVMAcceptorFactory.class.getName(), this.properties.generateTransportParameters()); configuration.getAcceptorConfigurations().add(transportConfiguration); if (this.properties.isDefaultClusterPassword()) { - logger.debug("Using default Artemis cluster password: " - + this.properties.getClusterPassword()); + logger.debug("Using default Artemis cluster password: " + this.properties.getClusterPassword()); } configuration.setClusterPassword(this.properties.getClusterPassword()); configuration.addAddressConfiguration(createAddressConfiguration("DLQ")); configuration.addAddressConfiguration(createAddressConfiguration("ExpiryQueue")); configuration.addAddressesSetting("#", - new AddressSettings() - .setDeadLetterAddress(SimpleString.toSimpleString("DLQ")) + new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("DLQ")) .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue"))); return configuration; } private CoreAddressConfiguration createAddressConfiguration(String name) { - return new CoreAddressConfiguration().setName(name) - .addRoutingType(RoutingType.ANYCAST) - .addQueueConfiguration(new CoreQueueConfiguration().setName(name) - .setRoutingType(RoutingType.ANYCAST).setAddress(name)); + return new CoreAddressConfiguration().setName(name).addRoutingType(RoutingType.ANYCAST).addQueueConfiguration( + new CoreQueueConfiguration().setName(name).setRoutingType(RoutingType.ANYCAST).setAddress(name)); } private String getDataDir() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java index daaa1a904fe..1bc3d020386 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java @@ -43,8 +43,8 @@ import org.springframework.context.annotation.Configuration; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(EmbeddedJMS.class) -@ConditionalOnProperty(prefix = "spring.artemis.embedded", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.artemis.embedded", name = "enabled", havingValue = "true", + matchIfMissing = true) class ArtemisEmbeddedServerConfiguration { private final ArtemisProperties properties; @@ -56,19 +56,16 @@ class ArtemisEmbeddedServerConfiguration { @Bean @ConditionalOnMissingBean public org.apache.activemq.artemis.core.config.Configuration artemisConfiguration() { - return new ArtemisEmbeddedConfigurationFactory(this.properties) - .createConfiguration(); + return new ArtemisEmbeddedConfigurationFactory(this.properties).createConfiguration(); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean - public EmbeddedJMS artemisServer( - org.apache.activemq.artemis.core.config.Configuration configuration, + public EmbeddedJMS artemisServer(org.apache.activemq.artemis.core.config.Configuration configuration, JMSConfiguration jmsConfiguration, ObjectProvider configurationCustomizers) { EmbeddedJMS server = new EmbeddedJMS(); - configurationCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(configuration)); + configurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration)); server.setConfiguration(configuration); server.setJmsConfiguration(jmsConfiguration); server.setRegistry(new ArtemisNoOpBindingRegistry()); @@ -77,8 +74,7 @@ class ArtemisEmbeddedServerConfiguration { @Bean @ConditionalOnMissingBean - public JMSConfiguration artemisJmsConfiguration( - ObjectProvider queuesConfiguration, + public JMSConfiguration artemisJmsConfiguration(ObjectProvider queuesConfiguration, ObjectProvider topicsConfiguration) { JMSConfiguration configuration = new JMSConfigurationImpl(); addAll(configuration.getQueueConfigurations(), queuesConfiguration); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java index f0520c812a0..565edce01d6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java @@ -45,17 +45,15 @@ class ArtemisXAConnectionFactoryConfiguration { @Primary @Bean(name = { "jmsConnectionFactory", "xaJmsConnectionFactory" }) - public ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, - ArtemisProperties properties, XAConnectionFactoryWrapper wrapper) - throws Exception { - return wrapper.wrapConnectionFactory( - new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQXAConnectionFactory.class)); + public ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties, + XAConnectionFactoryWrapper wrapper) throws Exception { + return wrapper.wrapConnectionFactory(new ArtemisConnectionFactoryFactory(beanFactory, properties) + .createConnectionFactory(ActiveMQXAConnectionFactory.class)); } @Bean - public ActiveMQXAConnectionFactory nonXaJmsConnectionFactory( - ListableBeanFactory beanFactory, ArtemisProperties properties) { + public ActiveMQXAConnectionFactory nonXaJmsConnectionFactory(ListableBeanFactory beanFactory, + ArtemisProperties properties) { return new ArtemisConnectionFactoryFactory(beanFactory, properties) .createConnectionFactory(ActiveMQXAConnectionFactory.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java index c3b6967844b..713883c7db0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java @@ -62,15 +62,12 @@ public class JmxAutoConfiguration { @Bean @Primary - @ConditionalOnMissingBean(value = MBeanExporter.class, - search = SearchStrategy.CURRENT) - public AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy, - BeanFactory beanFactory) { + @ConditionalOnMissingBean(value = MBeanExporter.class, search = SearchStrategy.CURRENT) + public AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy, BeanFactory beanFactory) { AnnotationMBeanExporter exporter = new AnnotationMBeanExporter(); exporter.setRegistrationPolicy(RegistrationPolicy.FAIL_ON_EXISTING); exporter.setNamingStrategy(namingStrategy); - String serverBean = this.environment.getProperty("spring.jmx.server", - "mbeanServer"); + String serverBean = this.environment.getProperty("spring.jmx.server", "mbeanServer"); if (StringUtils.hasLength(serverBean)) { exporter.setServer(beanFactory.getBean(serverBean, MBeanServer.class)); } @@ -78,17 +75,14 @@ public class JmxAutoConfiguration { } @Bean - @ConditionalOnMissingBean(value = ObjectNamingStrategy.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ObjectNamingStrategy.class, search = SearchStrategy.CURRENT) public ParentAwareNamingStrategy objectNamingStrategy() { - ParentAwareNamingStrategy namingStrategy = new ParentAwareNamingStrategy( - new AnnotationJmxAttributeSource()); + ParentAwareNamingStrategy namingStrategy = new ParentAwareNamingStrategy(new AnnotationJmxAttributeSource()); String defaultDomain = this.environment.getProperty("spring.jmx.default-domain"); if (StringUtils.hasLength(defaultDomain)) { namingStrategy.setDefaultDomain(defaultDomain); } - boolean uniqueNames = this.environment.getProperty("spring.jmx.unique-names", - Boolean.class, false); + boolean uniqueNames = this.environment.getProperty("spring.jmx.unique-names", Boolean.class, false); namingStrategy.setEnsureUniqueRuntimeObjectNames(uniqueNames); return namingStrategy; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java index db873de9b3d..1b5115debb2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.springframework.util.ObjectUtils; * @author Dave Syer * @since 1.1.1 */ -public class ParentAwareNamingStrategy extends MetadataNamingStrategy - implements ApplicationContextAware { +public class ParentAwareNamingStrategy extends MetadataNamingStrategy implements ApplicationContextAware { private ApplicationContext applicationContext; @@ -51,14 +50,12 @@ public class ParentAwareNamingStrategy extends MetadataNamingStrategy * Set if unique runtime object names should be ensured. * @param ensureUniqueRuntimeObjectNames {@code true} if unique names should ensured. */ - public void setEnsureUniqueRuntimeObjectNames( - boolean ensureUniqueRuntimeObjectNames) { + public void setEnsureUniqueRuntimeObjectNames(boolean ensureUniqueRuntimeObjectNames) { this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames; } @Override - public ObjectName getObjectName(Object managedBean, String beanKey) - throws MalformedObjectNameException { + public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException { ObjectName name = super.getObjectName(managedBean, beanKey); Hashtable properties = new Hashtable<>(); properties.putAll(name.getKeyPropertyList()); @@ -66,20 +63,17 @@ public class ParentAwareNamingStrategy extends MetadataNamingStrategy properties.put("identity", ObjectUtils.getIdentityHexString(managedBean)); } else if (parentContextContainsSameBean(this.applicationContext, beanKey)) { - properties.put("context", - ObjectUtils.getIdentityHexString(this.applicationContext)); + properties.put("context", ObjectUtils.getIdentityHexString(this.applicationContext)); } return ObjectNameManager.getInstance(name.getDomain(), properties); } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } - private boolean parentContextContainsSameBean(ApplicationContext context, - String beanKey) { + private boolean parentContextContainsSameBean(ApplicationContext context, String beanKey) { if (context.getParent() == null) { return false; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java index 2b4131b9774..327e66c744f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java @@ -60,22 +60,18 @@ import org.springframework.transaction.PlatformTransactionManager; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DSLContext.class) @ConditionalOnBean(DataSource.class) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class }) public class JooqAutoConfiguration { @Bean @ConditionalOnMissingBean - public DataSourceConnectionProvider dataSourceConnectionProvider( - DataSource dataSource) { - return new DataSourceConnectionProvider( - new TransactionAwareDataSourceProxy(dataSource)); + public DataSourceConnectionProvider dataSourceConnectionProvider(DataSource dataSource) { + return new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource)); } @Bean @ConditionalOnBean(PlatformTransactionManager.class) - public SpringTransactionProvider transactionProvider( - PlatformTransactionManager txManager) { + public SpringTransactionProvider transactionProvider(PlatformTransactionManager txManager) { return new SpringTransactionProvider(txManager); } @@ -97,12 +93,10 @@ public class JooqAutoConfiguration { @Bean @ConditionalOnMissingBean(org.jooq.Configuration.class) - public DefaultConfiguration jooqConfiguration(JooqProperties properties, - ConnectionProvider connectionProvider, DataSource dataSource, - ObjectProvider transactionProvider, + public DefaultConfiguration jooqConfiguration(JooqProperties properties, ConnectionProvider connectionProvider, + DataSource dataSource, ObjectProvider transactionProvider, ObjectProvider recordMapperProvider, - ObjectProvider recordUnmapperProvider, - ObjectProvider settings, + ObjectProvider recordUnmapperProvider, ObjectProvider settings, ObjectProvider recordListenerProviders, ObjectProvider executeListenerProviders, ObjectProvider visitListenerProviders, @@ -116,14 +110,11 @@ public class JooqAutoConfiguration { recordUnmapperProvider.ifAvailable(configuration::set); settings.ifAvailable(configuration::set); executorProvider.ifAvailable(configuration::set); - configuration.set(recordListenerProviders.orderedStream() - .toArray(RecordListenerProvider[]::new)); - configuration.set(executeListenerProviders.orderedStream() - .toArray(ExecuteListenerProvider[]::new)); - configuration.set(visitListenerProviders.orderedStream() - .toArray(VisitListenerProvider[]::new)); - configuration.setTransactionListenerProvider(transactionListenerProviders - .orderedStream().toArray(TransactionListenerProvider[]::new)); + configuration.set(recordListenerProviders.orderedStream().toArray(RecordListenerProvider[]::new)); + configuration.set(executeListenerProviders.orderedStream().toArray(ExecuteListenerProvider[]::new)); + configuration.set(visitListenerProviders.orderedStream().toArray(VisitListenerProvider[]::new)); + configuration.setTransactionListenerProvider( + transactionListenerProviders.orderedStream().toArray(TransactionListenerProvider[]::new)); return configuration; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java index 3aa2f38b828..075934c882b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,7 @@ public class JooqExceptionTranslator extends DefaultExecuteListener { * @param translator the exception translator * @param exception the exception */ - private void handle(ExecuteContext context, SQLExceptionTranslator translator, - SQLException exception) { + private void handle(ExecuteContext context, SQLExceptionTranslator translator, SQLException exception) { DataAccessException translated = translate(context, translator, exception); if (exception.getNextException() == null) { context.exception(translated); @@ -88,8 +87,8 @@ public class JooqExceptionTranslator extends DefaultExecuteListener { } } - private DataAccessException translate(ExecuteContext context, - SQLExceptionTranslator translator, SQLException exception) { + private DataAccessException translate(ExecuteContext context, SQLExceptionTranslator translator, + SQLException exception) { return translator.translate("jOOQ", context.sql(), exception); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java index 59640407d6b..fe73edd7cd5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ public class SpringTransactionProvider implements TransactionProvider { @Override public void begin(TransactionContext context) { - TransactionDefinition definition = new DefaultTransactionDefinition( - TransactionDefinition.PROPAGATION_NESTED); + TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_NESTED); TransactionStatus status = this.transactionManager.getTransaction(definition); context.transaction(new SpringTransaction(status)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfiguration.java index 97501f3e195..3a27d26d291 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfiguration.java @@ -34,9 +34,8 @@ import org.springframework.context.annotation.Configuration; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jsonb.class) -@ConditionalOnResource( - resources = { "classpath:META-INF/services/javax.json.bind.spi.JsonbProvider", - "classpath:META-INF/services/javax.json.spi.JsonProvider" }) +@ConditionalOnResource(resources = { "classpath:META-INF/services/javax.json.bind.spi.JsonbProvider", + "classpath:META-INF/services/javax.json.spi.JsonProvider" }) public class JsonbAutoConfiguration { @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java index 78d614f999a..9ff356ca9d6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java @@ -84,8 +84,7 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { * Set the {@link KafkaAwareTransactionManager} to use. * @param transactionManager the transaction manager */ - void setTransactionManager( - KafkaAwareTransactionManager transactionManager) { + void setTransactionManager(KafkaAwareTransactionManager transactionManager) { this.transactionManager = transactionManager; } @@ -118,8 +117,7 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { * Set the {@link AfterRollbackProcessor} to use. * @param afterRollbackProcessor the after rollback processor */ - void setAfterRollbackProcessor( - AfterRollbackProcessor afterRollbackProcessor) { + void setAfterRollbackProcessor(AfterRollbackProcessor afterRollbackProcessor) { this.afterRollbackProcessor = afterRollbackProcessor; } @@ -130,16 +128,14 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { * to configure * @param consumerFactory the {@link ConsumerFactory} to use */ - public void configure( - ConcurrentKafkaListenerContainerFactory listenerFactory, + public void configure(ConcurrentKafkaListenerContainerFactory listenerFactory, ConsumerFactory consumerFactory) { listenerFactory.setConsumerFactory(consumerFactory); configureListenerFactory(listenerFactory); configureContainer(listenerFactory.getContainerProperties()); } - private void configureListenerFactory( - ConcurrentKafkaListenerContainerFactory factory) { + private void configureListenerFactory(ConcurrentKafkaListenerContainerFactory factory) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Listener properties = this.properties.getListener(); map.from(properties::getConcurrency).to(factory::setConcurrency); @@ -162,13 +158,11 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { map.from(properties::getClientId).to(container::setClientId); map.from(properties::getAckCount).to(container::setAckCount); map.from(properties::getAckTime).as(Duration::toMillis).to(container::setAckTime); - map.from(properties::getPollTimeout).as(Duration::toMillis) - .to(container::setPollTimeout); + map.from(properties::getPollTimeout).as(Duration::toMillis).to(container::setPollTimeout); map.from(properties::getNoPollThreshold).to(container::setNoPollThreshold); - map.from(properties::getIdleEventInterval).as(Duration::toMillis) - .to(container::setIdleEventInterval); - map.from(properties::getMonitorInterval).as(Duration::getSeconds) - .as(Number::intValue).to(container::setMonitorInterval); + map.from(properties::getIdleEventInterval).as(Duration::toMillis).to(container::setIdleEventInterval); + map.from(properties::getMonitorInterval).as(Duration::getSeconds).as(Number::intValue) + .to(container::setMonitorInterval); map.from(properties::getLogContainerConfig).to(container::setLogContainerConfig); map.from(properties::isMissingTopicsFatal).to(container::setMissingTopicsFatal); map.from(this.transactionManager).to(container::setTransactionManager); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java index 89dca804422..d325192c87b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java @@ -71,14 +71,13 @@ class KafkaAnnotationDrivenConfiguration { ObjectProvider batchMessageConverter, ObjectProvider> kafkaTemplate, ObjectProvider> kafkaTransactionManager, - ObjectProvider rebalanceListener, - ObjectProvider errorHandler, + ObjectProvider rebalanceListener, ObjectProvider errorHandler, ObjectProvider batchErrorHandler, ObjectProvider> afterRollbackProcessor) { this.properties = properties; this.messageConverter = messageConverter.getIfUnique(); - this.batchMessageConverter = batchMessageConverter.getIfUnique( - () -> new BatchMessagingMessageConverter(this.messageConverter)); + this.batchMessageConverter = batchMessageConverter + .getIfUnique(() -> new BatchMessagingMessageConverter(this.messageConverter)); this.kafkaTemplate = kafkaTemplate.getIfUnique(); this.transactionManager = kafkaTransactionManager.getIfUnique(); this.rebalanceListener = rebalanceListener.getIfUnique(); @@ -92,8 +91,8 @@ class KafkaAnnotationDrivenConfiguration { public ConcurrentKafkaListenerContainerFactoryConfigurer kafkaListenerContainerFactoryConfigurer() { ConcurrentKafkaListenerContainerFactoryConfigurer configurer = new ConcurrentKafkaListenerContainerFactoryConfigurer(); configurer.setKafkaProperties(this.properties); - MessageConverter messageConverterToUse = (this.properties.getListener().getType() - .equals(Type.BATCH)) ? this.batchMessageConverter : this.messageConverter; + MessageConverter messageConverterToUse = (this.properties.getListener().getType().equals(Type.BATCH)) + ? this.batchMessageConverter : this.messageConverter; configurer.setMessageConverter(messageConverterToUse); configurer.setReplyTemplate(this.kafkaTemplate); configurer.setTransactionManager(this.transactionManager); @@ -116,8 +115,7 @@ class KafkaAnnotationDrivenConfiguration { @Configuration(proxyBeanMethods = false) @EnableKafka - @ConditionalOnMissingBean( - name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) protected static class EnableKafkaConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java index f95222c4ad8..d4a806cc258 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java @@ -52,8 +52,7 @@ import org.springframework.kafka.transaction.KafkaTransactionManager; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(KafkaTemplate.class) @EnableConfigurationProperties(KafkaProperties.class) -@Import({ KafkaAnnotationDrivenConfiguration.class, - KafkaStreamsAnnotationDrivenConfiguration.class }) +@Import({ KafkaAnnotationDrivenConfiguration.class, KafkaStreamsAnnotationDrivenConfiguration.class }) public class KafkaAutoConfiguration { private final KafkaProperties properties; @@ -64,12 +63,10 @@ public class KafkaAutoConfiguration { @Bean @ConditionalOnMissingBean(KafkaTemplate.class) - public KafkaTemplate kafkaTemplate( - ProducerFactory kafkaProducerFactory, + public KafkaTemplate kafkaTemplate(ProducerFactory kafkaProducerFactory, ProducerListener kafkaProducerListener, ObjectProvider messageConverter) { - KafkaTemplate kafkaTemplate = new KafkaTemplate<>( - kafkaProducerFactory); + KafkaTemplate kafkaTemplate = new KafkaTemplate<>(kafkaProducerFactory); messageConverter.ifUnique(kafkaTemplate::setMessageConverter); kafkaTemplate.setProducerListener(kafkaProducerListener); kafkaTemplate.setDefaultTopic(this.properties.getTemplate().getDefaultTopic()); @@ -85,8 +82,7 @@ public class KafkaAutoConfiguration { @Bean @ConditionalOnMissingBean(ConsumerFactory.class) public ConsumerFactory kafkaConsumerFactory() { - return new DefaultKafkaConsumerFactory<>( - this.properties.buildConsumerProperties()); + return new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()); } @Bean @@ -94,8 +90,7 @@ public class KafkaAutoConfiguration { public ProducerFactory kafkaProducerFactory() { DefaultKafkaProducerFactory factory = new DefaultKafkaProducerFactory<>( this.properties.buildProducerProperties()); - String transactionIdPrefix = this.properties.getProducer() - .getTransactionIdPrefix(); + String transactionIdPrefix = this.properties.getProducer().getTransactionIdPrefix(); if (transactionIdPrefix != null) { factory.setTransactionIdPrefix(transactionIdPrefix); } @@ -105,8 +100,7 @@ public class KafkaAutoConfiguration { @Bean @ConditionalOnProperty(name = "spring.kafka.producer.transaction-id-prefix") @ConditionalOnMissingBean - public KafkaTransactionManager kafkaTransactionManager( - ProducerFactory producerFactory) { + public KafkaTransactionManager kafkaTransactionManager(ProducerFactory producerFactory) { return new KafkaTransactionManager<>(producerFactory); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java index 1d51bc0c114..cc99740df4c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java @@ -60,8 +60,7 @@ public class KafkaProperties { * Comma-delimited list of host:port pairs to use for establishing the initial * connections to the Kafka cluster. Applies to all components unless overridden. */ - private List bootstrapServers = new ArrayList<>( - Collections.singletonList("localhost:9092")); + private List bootstrapServers = new ArrayList<>(Collections.singletonList("localhost:9092")); /** * ID to pass to the server when making requests. Used for server-side logging. @@ -145,8 +144,7 @@ public class KafkaProperties { private Map buildCommonProperties() { Map properties = new HashMap<>(); if (this.bootstrapServers != null) { - properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, - this.bootstrapServers); + properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, this.bootstrapServers); } if (this.clientId != null) { properties.put(CommonClientConfigs.CLIENT_ID_CONFIG, this.clientId); @@ -397,14 +395,10 @@ public class KafkaProperties { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getAutoCommitInterval).asInt(Duration::toMillis) .to(properties.in(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)); - map.from(this::getAutoOffsetReset) - .to(properties.in(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); - map.from(this::getBootstrapServers) - .to(properties.in(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)); - map.from(this::getClientId) - .to(properties.in(ConsumerConfig.CLIENT_ID_CONFIG)); - map.from(this::getEnableAutoCommit) - .to(properties.in(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)); + map.from(this::getAutoOffsetReset).to(properties.in(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); + map.from(this::getBootstrapServers).to(properties.in(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)); + map.from(this::getClientId).to(properties.in(ConsumerConfig.CLIENT_ID_CONFIG)); + map.from(this::getEnableAutoCommit).to(properties.in(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)); map.from(this::getFetchMaxWait).asInt(Duration::toMillis) .to(properties.in(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)); map.from(this::getFetchMinSize).asInt(DataSize::toBytes) @@ -412,12 +406,9 @@ public class KafkaProperties { map.from(this::getGroupId).to(properties.in(ConsumerConfig.GROUP_ID_CONFIG)); map.from(this::getHeartbeatInterval).asInt(Duration::toMillis) .to(properties.in(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)); - map.from(this::getKeyDeserializer) - .to(properties.in(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)); - map.from(this::getValueDeserializer) - .to(properties.in(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)); - map.from(this::getMaxPollRecords) - .to(properties.in(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)); + map.from(this::getKeyDeserializer).to(properties.in(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)); + map.from(this::getValueDeserializer).to(properties.in(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)); + map.from(this::getMaxPollRecords).to(properties.in(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)); return properties.with(this.ssl, this.properties); } @@ -578,21 +569,15 @@ public class KafkaProperties { Properties properties = new Properties(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getAcks).to(properties.in(ProducerConfig.ACKS_CONFIG)); - map.from(this::getBatchSize).asInt(DataSize::toBytes) - .to(properties.in(ProducerConfig.BATCH_SIZE_CONFIG)); - map.from(this::getBootstrapServers) - .to(properties.in(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); + map.from(this::getBatchSize).asInt(DataSize::toBytes).to(properties.in(ProducerConfig.BATCH_SIZE_CONFIG)); + map.from(this::getBootstrapServers).to(properties.in(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); map.from(this::getBufferMemory).as(DataSize::toBytes) .to(properties.in(ProducerConfig.BUFFER_MEMORY_CONFIG)); - map.from(this::getClientId) - .to(properties.in(ProducerConfig.CLIENT_ID_CONFIG)); - map.from(this::getCompressionType) - .to(properties.in(ProducerConfig.COMPRESSION_TYPE_CONFIG)); - map.from(this::getKeySerializer) - .to(properties.in(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)); + map.from(this::getClientId).to(properties.in(ProducerConfig.CLIENT_ID_CONFIG)); + map.from(this::getCompressionType).to(properties.in(ProducerConfig.COMPRESSION_TYPE_CONFIG)); + map.from(this::getKeySerializer).to(properties.in(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)); map.from(this::getRetries).to(properties.in(ProducerConfig.RETRIES_CONFIG)); - map.from(this::getValueSerializer) - .to(properties.in(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)); + map.from(this::getValueSerializer).to(properties.in(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)); return properties.with(this.ssl, this.properties); } @@ -644,8 +629,7 @@ public class KafkaProperties { public Map buildProperties() { Properties properties = new Properties(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(this::getClientId) - .to(properties.in(ProducerConfig.CLIENT_ID_CONFIG)); + map.from(this::getClientId).to(properties.in(ProducerConfig.CLIENT_ID_CONFIG)); return properties.with(this.ssl, this.properties); } @@ -768,12 +752,10 @@ public class KafkaProperties { Properties properties = new Properties(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getApplicationId).to(properties.in("application.id")); - map.from(this::getBootstrapServers) - .to(properties.in(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)); + map.from(this::getBootstrapServers).to(properties.in(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)); map.from(this::getCacheMaxSizeBuffering).asInt(DataSize::toBytes) .to(properties.in("cache.max.bytes.buffering")); - map.from(this::getClientId) - .to(properties.in(CommonClientConfigs.CLIENT_ID_CONFIG)); + map.from(this::getClientId).to(properties.in(CommonClientConfigs.CLIENT_ID_CONFIG)); map.from(this::getReplicationFactor).to(properties.in("replication.factor")); map.from(this::getStateDir).to(properties.in("state.dir")); return properties.with(this.ssl, this.properties); @@ -1086,20 +1068,15 @@ public class KafkaProperties { public Map buildProperties() { Properties properties = new Properties(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(this::getKeyPassword) - .to(properties.in(SslConfigs.SSL_KEY_PASSWORD_CONFIG)); + map.from(this::getKeyPassword).to(properties.in(SslConfigs.SSL_KEY_PASSWORD_CONFIG)); map.from(this::getKeyStoreLocation).as(this::resourceToPath) .to(properties.in(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)); - map.from(this::getKeyStorePassword) - .to(properties.in(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)); - map.from(this::getKeyStoreType) - .to(properties.in(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)); + map.from(this::getKeyStorePassword).to(properties.in(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)); + map.from(this::getKeyStoreType).to(properties.in(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)); map.from(this::getTrustStoreLocation).as(this::resourceToPath) .to(properties.in(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)); - map.from(this::getTrustStorePassword) - .to(properties.in(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)); - map.from(this::getTrustStoreType) - .to(properties.in(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)); + map.from(this::getTrustStorePassword).to(properties.in(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)); + map.from(this::getTrustStoreType).to(properties.in(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)); map.from(this::getProtocol).to(properties.in(SslConfigs.SSL_PROTOCOL_CONFIG)); return properties; } @@ -1109,8 +1086,7 @@ public class KafkaProperties { return resource.getFile().getAbsolutePath(); } catch (IOException ex) { - throw new IllegalStateException( - "Resource '" + resource + "' must be on a file system", ex); + throw new IllegalStateException("Resource '" + resource + "' must be on a file system", ex); } } @@ -1158,8 +1134,7 @@ public class KafkaProperties { return this.controlFlag; } - public void setControlFlag( - KafkaJaasLoginModuleInitializer.ControlFlag controlFlag) { + public void setControlFlag(KafkaJaasLoginModuleInitializer.ControlFlag controlFlag) { this.controlFlag = controlFlag; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaStreamsAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaStreamsAnnotationDrivenConfiguration.java index cfc25e2fada..9baba0686ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaStreamsAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaStreamsAnnotationDrivenConfiguration.java @@ -42,8 +42,7 @@ import org.springframework.kafka.config.StreamsBuilderFactoryBean; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(StreamsBuilder.class) -@ConditionalOnBean( - name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME) +@ConditionalOnBean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME) class KafkaStreamsAnnotationDrivenConfiguration { private final KafkaProperties properties; @@ -59,8 +58,7 @@ class KafkaStreamsAnnotationDrivenConfiguration { if (this.properties.getStreams().getApplicationId() == null) { String applicationName = environment.getProperty("spring.application.name"); if (applicationName == null) { - throw new InvalidConfigurationPropertyValueException( - "spring.kafka.streams.application-id", null, + throw new InvalidConfigurationPropertyValueException("spring.kafka.streams.application-id", null, "This property is mandatory and fallback 'spring.application.name' is not set either."); } streamsProperties.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationName); @@ -81,8 +79,7 @@ class KafkaStreamsAnnotationDrivenConfiguration { private final StreamsBuilderFactoryBean factoryBean; - KafkaStreamsFactoryBeanConfigurer(KafkaProperties properties, - StreamsBuilderFactoryBean factoryBean) { + KafkaStreamsFactoryBeanConfigurer(KafkaProperties properties, StreamsBuilderFactoryBean factoryBean) { this.properties = properties; this.factoryBean = factoryBean; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java index 95b7892a9af..ca8e4e98a5a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java @@ -44,16 +44,14 @@ public class LdapAutoConfiguration { @Bean @ConditionalOnMissingBean - public LdapContextSource ldapContextSource(LdapProperties properties, - Environment environment) { + public LdapContextSource ldapContextSource(LdapProperties properties, Environment environment) { LdapContextSource source = new LdapContextSource(); source.setUserDn(properties.getUsername()); source.setPassword(properties.getPassword()); source.setAnonymousReadOnly(properties.getAnonymousReadOnly()); source.setBase(properties.getBase()); source.setUrls(properties.determineUrls(environment)); - source.setBaseEnvironmentProperties( - Collections.unmodifiableMap(properties.getBaseEnvironment())); + source.setBaseEnvironmentProperties(Collections.unmodifiableMap(properties.getBaseEnvironment())); return source; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java index d537c21504b..18634cae039 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java @@ -89,8 +89,7 @@ public class EmbeddedLdapAutoConfiguration { @Bean @DependsOn("directoryServer") @ConditionalOnMissingBean - public LdapContextSource ldapContextSource(Environment environment, - LdapProperties properties) { + public LdapContextSource ldapContextSource(Environment environment, LdapProperties properties) { LdapContextSource source = new LdapContextSource(); if (hasCredentials(this.embeddedProperties.getCredential())) { source.setUserDn(this.embeddedProperties.getCredential().getUsername()); @@ -101,18 +100,16 @@ public class EmbeddedLdapAutoConfiguration { } @Bean - public InMemoryDirectoryServer directoryServer(ApplicationContext applicationContext) - throws LDAPException { + public InMemoryDirectoryServer directoryServer(ApplicationContext applicationContext) throws LDAPException { String[] baseDn = StringUtils.toStringArray(this.embeddedProperties.getBaseDn()); InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(baseDn); if (hasCredentials(this.embeddedProperties.getCredential())) { - config.addAdditionalBindCredentials( - this.embeddedProperties.getCredential().getUsername(), + config.addAdditionalBindCredentials(this.embeddedProperties.getCredential().getUsername(), this.embeddedProperties.getCredential().getPassword()); } setSchema(config); - InMemoryListenerConfig listenerConfig = InMemoryListenerConfig - .createLDAPConfig("LDAP", this.embeddedProperties.getPort()); + InMemoryListenerConfig listenerConfig = InMemoryListenerConfig.createLDAPConfig("LDAP", + this.embeddedProperties.getPort()); config.setListenerConfigs(listenerConfig); this.server = new InMemoryDirectoryServer(config); importLdif(applicationContext); @@ -139,14 +136,12 @@ public class EmbeddedLdapAutoConfiguration { config.setSchema(Schema.mergeSchemas(defaultSchema, schema)); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to load schema " + resource.getDescription(), ex); + throw new IllegalStateException("Unable to load schema " + resource.getDescription(), ex); } } private boolean hasCredentials(Credential credential) { - return StringUtils.hasText(credential.getUsername()) - && StringUtils.hasText(credential.getPassword()); + return StringUtils.hasText(credential.getUsername()) && StringUtils.hasText(credential.getPassword()); } private void importLdif(ApplicationContext applicationContext) throws LDAPException { @@ -168,8 +163,8 @@ public class EmbeddedLdapAutoConfiguration { private void setPortProperty(ApplicationContext context, int port) { if (context instanceof ConfigurableApplicationContext) { - MutablePropertySources sources = ((ConfigurableApplicationContext) context) - .getEnvironment().getPropertySources(); + MutablePropertySources sources = ((ConfigurableApplicationContext) context).getEnvironment() + .getPropertySources(); getLdapPorts(sources).put("local.ldap.port", port); } if (context.getParent() != null) { @@ -200,16 +195,13 @@ public class EmbeddedLdapAutoConfiguration { */ static class EmbeddedLdapCondition extends SpringBootCondition { - private static final Bindable> STRING_LIST = Bindable - .listOf(String.class); + private static final Bindable> STRING_LIST = Bindable.listOf(String.class); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Builder message = ConditionMessage.forCondition("Embedded LDAP"); Environment environment = context.getEnvironment(); - if (environment != null && !Binder.get(environment) - .bind("spring.ldap.embedded.base-dn", STRING_LIST) + if (environment != null && !Binder.get(environment).bind("spring.ldap.embedded.base-dn", STRING_LIST) .orElseGet(Collections::emptyList).isEmpty()) { return ConditionOutcome.match(message.because("Found base-dn property")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/DataSourceClosingSpringLiquibase.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/DataSourceClosingSpringLiquibase.java index 25d38731399..6aa2a09e1a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/DataSourceClosingSpringLiquibase.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/DataSourceClosingSpringLiquibase.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.util.ReflectionUtils; * @author Andy Wilkinson * @since 2.0.6 */ -public class DataSourceClosingSpringLiquibase extends SpringLiquibase - implements DisposableBean { +public class DataSourceClosingSpringLiquibase extends SpringLiquibase implements DisposableBean { private volatile boolean closeDataSourceOnceMigrated = true; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java index d97c566cd33..ee63171d9cc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java @@ -68,11 +68,9 @@ import org.springframework.util.Assert; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringLiquibase.class, DatabaseChange.class }) -@ConditionalOnProperty(prefix = "spring.liquibase", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.liquibase", name = "enabled", matchIfMissing = true) @Conditional(LiquibaseDataSourceCondition.class) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class LiquibaseAutoConfiguration { @Bean @@ -83,8 +81,7 @@ public class LiquibaseAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(SpringLiquibase.class) - @EnableConfigurationProperties({ DataSourceProperties.class, - LiquibaseProperties.class }) + @EnableConfigurationProperties({ DataSourceProperties.class, LiquibaseProperties.class }) @Import(LiquibaseJpaDependencyConfiguration.class) public static class LiquibaseConfiguration { @@ -92,8 +89,7 @@ public class LiquibaseAutoConfiguration { private final ResourceLoader resourceLoader; - public LiquibaseConfiguration(LiquibaseProperties properties, - ResourceLoader resourceLoader) { + public LiquibaseConfiguration(LiquibaseProperties properties, ResourceLoader resourceLoader) { this.properties = properties; this.resourceLoader = resourceLoader; } @@ -101,12 +97,9 @@ public class LiquibaseAutoConfiguration { @PostConstruct public void checkChangelogExists() { if (this.properties.isCheckChangeLogLocation()) { - Resource resource = this.resourceLoader - .getResource(this.properties.getChangeLog()); - Assert.state(resource.exists(), - () -> "Cannot find changelog location: " + resource - + " (please add changelog or check your Liquibase " - + "configuration)"); + Resource resource = this.resourceLoader.getResource(this.properties.getChangeLog()); + Assert.state(resource.exists(), () -> "Cannot find changelog location: " + resource + + " (please add changelog or check your Liquibase " + "configuration)"); } } @@ -114,18 +107,15 @@ public class LiquibaseAutoConfiguration { public SpringLiquibase liquibase(DataSourceProperties dataSourceProperties, ObjectProvider dataSource, @LiquibaseDataSource ObjectProvider liquibaseDataSource) { - SpringLiquibase liquibase = createSpringLiquibase( - liquibaseDataSource.getIfAvailable(), dataSource.getIfUnique(), - dataSourceProperties); + SpringLiquibase liquibase = createSpringLiquibase(liquibaseDataSource.getIfAvailable(), + dataSource.getIfUnique(), dataSourceProperties); liquibase.setChangeLog(this.properties.getChangeLog()); liquibase.setContexts(this.properties.getContexts()); liquibase.setDefaultSchema(this.properties.getDefaultSchema()); liquibase.setLiquibaseSchema(this.properties.getLiquibaseSchema()); liquibase.setLiquibaseTablespace(this.properties.getLiquibaseTablespace()); - liquibase.setDatabaseChangeLogTable( - this.properties.getDatabaseChangeLogTable()); - liquibase.setDatabaseChangeLogLockTable( - this.properties.getDatabaseChangeLogLockTable()); + liquibase.setDatabaseChangeLogTable(this.properties.getDatabaseChangeLogTable()); + liquibase.setDatabaseChangeLogLockTable(this.properties.getDatabaseChangeLogLockTable()); liquibase.setDropFirst(this.properties.isDropFirst()); liquibase.setShouldRun(this.properties.isEnabled()); liquibase.setLabels(this.properties.getLabels()); @@ -135,10 +125,9 @@ public class LiquibaseAutoConfiguration { return liquibase; } - private SpringLiquibase createSpringLiquibase(DataSource liquibaseDatasource, - DataSource dataSource, DataSourceProperties dataSourceProperties) { - DataSource liquibaseDataSource = getDataSource(liquibaseDatasource, - dataSource); + private SpringLiquibase createSpringLiquibase(DataSource liquibaseDatasource, DataSource dataSource, + DataSourceProperties dataSourceProperties) { + DataSource liquibaseDataSource = getDataSource(liquibaseDatasource, dataSource); if (liquibaseDataSource != null) { SpringLiquibase liquibase = new SpringLiquibase(); liquibase.setDataSource(liquibaseDataSource); @@ -149,8 +138,7 @@ public class LiquibaseAutoConfiguration { return liquibase; } - private DataSource getDataSource(DataSource liquibaseDataSource, - DataSource dataSource) { + private DataSource getDataSource(DataSource liquibaseDataSource, DataSource dataSource) { if (liquibaseDataSource != null) { return liquibaseDataSource; } @@ -160,20 +148,14 @@ public class LiquibaseAutoConfiguration { return null; } - private DataSource createNewDataSource( - DataSourceProperties dataSourceProperties) { - String url = getProperty(this.properties::getUrl, - dataSourceProperties::getUrl); - String user = getProperty(this.properties::getUser, - dataSourceProperties::getUsername); - String password = getProperty(this.properties::getPassword, - dataSourceProperties::getPassword); - return DataSourceBuilder.create().url(url).username(user).password(password) - .build(); + private DataSource createNewDataSource(DataSourceProperties dataSourceProperties) { + String url = getProperty(this.properties::getUrl, dataSourceProperties::getUrl); + String user = getProperty(this.properties::getUser, dataSourceProperties::getUsername); + String password = getProperty(this.properties::getPassword, dataSourceProperties::getPassword); + return DataSourceBuilder.create().url(url).username(user).password(password).build(); } - private String getProperty(Supplier property, - Supplier defaultValue) { + private String getProperty(Supplier property, Supplier defaultValue) { String value = property.get(); return (value != null) ? value : defaultValue.get(); } @@ -187,8 +169,7 @@ public class LiquibaseAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class LiquibaseJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class LiquibaseJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public LiquibaseJpaDependencyConfiguration() { super("liquibase"); @@ -203,8 +184,7 @@ public class LiquibaseAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(JdbcOperations.class) @ConditionalOnBean(JdbcOperations.class) - protected static class LiquibaseJdbcOperationsDependencyConfiguration - extends JdbcOperationsDependsOnPostProcessor { + protected static class LiquibaseJdbcOperationsDependencyConfiguration extends JdbcOperationsDependsOnPostProcessor { public LiquibaseJdbcOperationsDependencyConfiguration() { super("liquibase"); @@ -239,8 +219,7 @@ public class LiquibaseAutoConfiguration { } - @ConditionalOnProperty(prefix = "spring.liquibase", name = "url", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.liquibase", name = "url", matchIfMissing = false) private static final class LiquibaseUrlCondition { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java index b09990ceb2a..adb45861c44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @author Eddú Meléndez * @since 1.4.1 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java index f9246948bdc..a5ad86c64d3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,8 @@ class LiquibaseSchemaManagementProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { - return StreamSupport.stream(this.liquibaseInstances.spliterator(), false) - .map(SpringLiquibase::getDataSource).filter(dataSource::equals) - .findFirst().map((managedDataSource) -> SchemaManagement.MANAGED) + return StreamSupport.stream(this.liquibaseInstances.spliterator(), false).map(SpringLiquibase::getDataSource) + .filter(dataSource::equals).findFirst().map((managedDataSource) -> SchemaManagement.MANAGED) .orElse(SchemaManagement.UNMANAGED); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java index fa132bf6ab3..daecdeef727 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,7 @@ public class ConditionEvaluationReportLoggingListener } private boolean isInfoOrDebug(LogLevel logLevelForReport) { - return LogLevel.INFO.equals(logLevelForReport) - || LogLevel.DEBUG.equals(logLevelForReport); + return LogLevel.INFO.equals(logLevelForReport) || LogLevel.DEBUG.equals(logLevelForReport); } public LogLevel getLogLevelForReport() { @@ -80,26 +79,22 @@ public class ConditionEvaluationReportLoggingListener @Override public void initialize(ConfigurableApplicationContext applicationContext) { this.applicationContext = applicationContext; - applicationContext - .addApplicationListener(new ConditionEvaluationReportListener()); + applicationContext.addApplicationListener(new ConditionEvaluationReportListener()); if (applicationContext instanceof GenericApplicationContext) { // Get the report early in case the context fails to load - this.report = ConditionEvaluationReport - .get(this.applicationContext.getBeanFactory()); + this.report = ConditionEvaluationReport.get(this.applicationContext.getBeanFactory()); } } protected void onApplicationEvent(ApplicationEvent event) { ConfigurableApplicationContext initializerApplicationContext = this.applicationContext; if (event instanceof ContextRefreshedEvent) { - if (((ApplicationContextEvent) event) - .getApplicationContext() == initializerApplicationContext) { + if (((ApplicationContextEvent) event).getApplicationContext() == initializerApplicationContext) { logAutoConfigurationReport(); } } else if (event instanceof ApplicationFailedEvent - && ((ApplicationFailedEvent) event) - .getApplicationContext() == initializerApplicationContext) { + && ((ApplicationFailedEvent) event).getApplicationContext() == initializerApplicationContext) { logAutoConfigurationReport(true); } } @@ -111,12 +106,10 @@ public class ConditionEvaluationReportLoggingListener public void logAutoConfigurationReport(boolean isCrashReport) { if (this.report == null) { if (this.applicationContext == null) { - this.logger.info("Unable to provide the conditions report " - + "due to missing ApplicationContext"); + this.logger.info("Unable to provide the conditions report " + "due to missing ApplicationContext"); return; } - this.report = ConditionEvaluationReport - .get(this.applicationContext.getBeanFactory()); + this.report = ConditionEvaluationReport.get(this.applicationContext.getBeanFactory()); } if (!this.report.getConditionAndOutcomesBySource().isEmpty()) { if (this.getLogLevelForReport().equals(LogLevel.INFO)) { @@ -139,14 +132,11 @@ public class ConditionEvaluationReportLoggingListener } private void logMessage(String logLevel) { - this.logger.info( - String.format("%n%nError starting ApplicationContext. To display the " - + "conditions report re-run your application with '" + logLevel - + "' enabled.")); + this.logger.info(String.format("%n%nError starting ApplicationContext. To display the " + + "conditions report re-run your application with '" + logLevel + "' enabled.")); } - private class ConditionEvaluationReportListener - implements GenericApplicationListener { + private class ConditionEvaluationReportListener implements GenericApplicationListener { @Override public int getOrder() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java index e0303b7f162..802206cd9f8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class ConditionEvaluationReportMessage { this(report, "CONDITIONS EVALUATION REPORT"); } - public ConditionEvaluationReportMessage(ConditionEvaluationReport report, - String title) { + public ConditionEvaluationReportMessage(ConditionEvaluationReport report, String title) { this.message = getLogMessage(report, title); } @@ -63,8 +62,7 @@ public class ConditionEvaluationReportMessage { message.append(String.format("%s%n", separator)); message.append(String.format("%s%n", title)); message.append(String.format("%s%n%n%n", separator)); - Map shortOutcomes = orderByName( - report.getConditionAndOutcomesBySource()); + Map shortOutcomes = orderByName(report.getConditionAndOutcomesBySource()); logPositiveMatches(message, shortOutcomes); logNegativeMatches(message, shortOutcomes); logExclusions(report, message); @@ -73,36 +71,30 @@ public class ConditionEvaluationReportMessage { return message; } - private void logPositiveMatches(StringBuilder message, - Map shortOutcomes) { + private void logPositiveMatches(StringBuilder message, Map shortOutcomes) { message.append(String.format("Positive matches:%n")); message.append(String.format("-----------------%n")); - List> matched = shortOutcomes.entrySet() - .stream().filter((entry) -> entry.getValue().isFullMatch()) - .collect(Collectors.toList()); + List> matched = shortOutcomes.entrySet().stream() + .filter((entry) -> entry.getValue().isFullMatch()).collect(Collectors.toList()); if (matched.isEmpty()) { message.append(String.format("%n None%n")); } else { - matched.forEach((entry) -> addMatchLogMessage(message, entry.getKey(), - entry.getValue())); + matched.forEach((entry) -> addMatchLogMessage(message, entry.getKey(), entry.getValue())); } message.append(String.format("%n%n")); } - private void logNegativeMatches(StringBuilder message, - Map shortOutcomes) { + private void logNegativeMatches(StringBuilder message, Map shortOutcomes) { message.append(String.format("Negative matches:%n")); message.append(String.format("-----------------%n")); - List> nonMatched = shortOutcomes.entrySet() - .stream().filter((entry) -> !entry.getValue().isFullMatch()) - .collect(Collectors.toList()); + List> nonMatched = shortOutcomes.entrySet().stream() + .filter((entry) -> !entry.getValue().isFullMatch()).collect(Collectors.toList()); if (nonMatched.isEmpty()) { message.append(String.format("%n None%n")); } else { - nonMatched.forEach((entry) -> addNonMatchLogMessage(message, entry.getKey(), - entry.getValue())); + nonMatched.forEach((entry) -> addNonMatchLogMessage(message, entry.getKey(), entry.getValue())); } message.append(String.format("%n%n")); } @@ -121,8 +113,7 @@ public class ConditionEvaluationReportMessage { message.append(String.format("%n%n")); } - private void logUnconditionalClasses(ConditionEvaluationReport report, - StringBuilder message) { + private void logUnconditionalClasses(ConditionEvaluationReport report, StringBuilder message) { message.append(String.format("Unconditional classes:%n")); message.append(String.format("----------------------%n")); if (report.getUnconditionalClasses().isEmpty()) { @@ -135,8 +126,7 @@ public class ConditionEvaluationReportMessage { } } - private Map orderByName( - Map outcomes) { + private Map orderByName(Map outcomes) { MultiValueMap map = mapToFullyQualifiedNames(outcomes.keySet()); List shortNames = new ArrayList<>(map.keySet()); Collections.sort(shortNames); @@ -144,8 +134,8 @@ public class ConditionEvaluationReportMessage { for (String shortName : shortNames) { List fullyQualifiedNames = map.get(shortName); if (fullyQualifiedNames.size() > 1) { - fullyQualifiedNames.forEach((fullyQualifiedName) -> result - .put(fullyQualifiedName, outcomes.get(fullyQualifiedName))); + fullyQualifiedNames.forEach( + (fullyQualifiedName) -> result.put(fullyQualifiedName, outcomes.get(fullyQualifiedName))); } else { result.put(shortName, outcomes.get(fullyQualifiedNames.get(0))); @@ -156,13 +146,12 @@ public class ConditionEvaluationReportMessage { private MultiValueMap mapToFullyQualifiedNames(Set keySet) { LinkedMultiValueMap map = new LinkedMultiValueMap<>(); - keySet.forEach((fullyQualifiedName) -> map - .add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName)); + keySet.forEach( + (fullyQualifiedName) -> map.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName)); return map; } - private void addMatchLogMessage(StringBuilder message, String source, - ConditionAndOutcomes matches) { + private void addMatchLogMessage(StringBuilder message, String source, ConditionAndOutcomes matches) { message.append(String.format("%n %s matched:%n", source)); for (ConditionAndOutcome match : matches) { logConditionAndOutcome(message, " ", match); @@ -194,20 +183,17 @@ public class ConditionEvaluationReportMessage { } } - private void logConditionAndOutcome(StringBuilder message, String indent, - ConditionAndOutcome conditionAndOutcome) { + private void logConditionAndOutcome(StringBuilder message, String indent, ConditionAndOutcome conditionAndOutcome) { message.append(String.format("%s- ", indent)); String outcomeMessage = conditionAndOutcome.getOutcome().getMessage(); if (StringUtils.hasLength(outcomeMessage)) { message.append(outcomeMessage); } else { - message.append(conditionAndOutcome.getOutcome().isMatch() ? "matched" - : "did not match"); + message.append(conditionAndOutcome.getOutcome().isMatch() ? "matched" : "did not match"); } message.append(" ("); - message.append( - ClassUtils.getShortName(conditionAndOutcome.getCondition().getClass())); + message.append(ClassUtils.getShortName(conditionAndOutcome.getCondition().getClass())); message.append(String.format(")%n")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java index ce897184afa..b2828c3d9f4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java @@ -60,13 +60,10 @@ class MailSenderJndiConfiguration { public Session session() { String jndiName = this.properties.getJndiName(); try { - return JndiLocatorDelegate.createDefaultResourceRefLocator().lookup(jndiName, - Session.class); + return JndiLocatorDelegate.createDefaultResourceRefLocator().lookup(jndiName, Session.class); } catch (NamingException ex) { - throw new IllegalStateException( - String.format("Unable to find Session in JNDI location %s", jndiName), - ex); + throw new IllegalStateException(String.format("Unable to find Session in JNDI location %s", jndiName), ex); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java index a745620a833..11e4c778fb1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java @@ -44,12 +44,10 @@ import org.springframework.core.env.Environment; public class MongoAutoConfiguration { @Bean - @ConditionalOnMissingBean( - type = { "com.mongodb.MongoClient", "com.mongodb.client.MongoClient" }) - public MongoClient mongo(MongoProperties properties, - ObjectProvider options, Environment environment) { - return new MongoClientFactory(properties, environment) - .createMongoClient(options.getIfAvailable()); + @ConditionalOnMissingBean(type = { "com.mongodb.MongoClient", "com.mongodb.client.MongoClient" }) + public MongoClient mongo(MongoProperties properties, ObjectProvider options, + Environment environment) { + return new MongoClientFactory(properties, environment).createMongoClient(options.getIfAvailable()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactory.java index e52871350e0..0717a51d849 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,10 +81,8 @@ public class MongoClientFactory { if (options == null) { options = MongoClientOptions.builder().build(); } - String host = (this.properties.getHost() != null) ? this.properties.getHost() - : "localhost"; - return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), - options); + String host = (this.properties.getHost() != null) ? this.properties.getHost() : "localhost"; + return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), options); } private MongoClient createNetworkMongoClient(MongoClientOptions options) { @@ -99,8 +97,7 @@ public class MongoClientFactory { MongoCredential credentials = getCredentials(properties); String host = getValue(properties.getHost(), "localhost"); int port = getValue(properties.getPort(), MongoProperties.DEFAULT_PORT); - List seeds = Collections - .singletonList(new ServerAddress(host, port)); + List seeds = Collections.singletonList(new ServerAddress(host, port)); return (credentials != null) ? new MongoClient(seeds, credentials, options) : new MongoClient(seeds, options); } @@ -124,15 +121,13 @@ public class MongoClientFactory { return null; } String username = properties.getUsername(); - String database = getValue(properties.getAuthenticationDatabase(), - properties.getMongoClientDatabase()); + String database = getValue(properties.getAuthenticationDatabase(), properties.getMongoClientDatabase()); char[] password = properties.getPassword(); return MongoCredential.createCredential(username, database, password); } private boolean hasCustomCredentials() { - return this.properties.getUsername() != null - && this.properties.getPassword() != null; + return this.properties.getUsername() != null && this.properties.getPassword() != null; } private Builder builder(MongoClientOptions options) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java index 8d9f0ac03d4..da92a76654c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java @@ -53,12 +53,10 @@ public class MongoReactiveAutoConfiguration { @Bean @ConditionalOnMissingBean - public MongoClient reactiveStreamsMongoClient(MongoProperties properties, - Environment environment, + public MongoClient reactiveStreamsMongoClient(MongoProperties properties, Environment environment, ObjectProvider builderCustomizers, ObjectProvider settings) { - ReactiveMongoClientFactory factory = new ReactiveMongoClientFactory(properties, - environment, + ReactiveMongoClientFactory factory = new ReactiveMongoClientFactory(properties, environment, builderCustomizers.orderedStream().collect(Collectors.toList())); return factory.createMongoClient(settings.getIfAvailable()); } @@ -86,8 +84,7 @@ public class MongoReactiveAutoConfiguration { private volatile EventLoopGroup eventLoopGroup; - private NettyDriverMongoClientSettingsBuilderCustomizer( - ObjectProvider settings) { + private NettyDriverMongoClientSettingsBuilderCustomizer(ObjectProvider settings) { this.settings = settings; } @@ -96,8 +93,8 @@ public class MongoReactiveAutoConfiguration { if (!isStreamFactoryFactoryDefined(this.settings.getIfAvailable())) { NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); this.eventLoopGroup = eventLoopGroup; - builder.streamFactoryFactory(NettyStreamFactoryFactory.builder() - .eventLoopGroup(eventLoopGroup).build()); + builder.streamFactoryFactory( + NettyStreamFactoryFactory.builder().eventLoopGroup(eventLoopGroup).build()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactory.java index ef1131ab5e2..b0adc5fe9ef 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class ReactiveMongoClientFactory { List builderCustomizers) { this.properties = properties; this.environment = environment; - this.builderCustomizers = (builderCustomizers != null) ? builderCustomizers - : Collections.emptyList(); + this.builderCustomizers = (builderCustomizers != null) ? builderCustomizers : Collections.emptyList(); } /** @@ -78,13 +77,11 @@ public class ReactiveMongoClientFactory { return null; } - private MongoClient createEmbeddedMongoClient(MongoClientSettings settings, - int port) { + private MongoClient createEmbeddedMongoClient(MongoClientSettings settings, int port) { Builder builder = builder(settings); - String host = (this.properties.getHost() != null) ? this.properties.getHost() - : "localhost"; - builder.applyToClusterSettings((cluster) -> cluster - .hosts(Collections.singletonList(new ServerAddress(host, port)))); + String host = (this.properties.getHost() != null) ? this.properties.getHost() : "localhost"; + builder.applyToClusterSettings( + (cluster) -> cluster.hosts(Collections.singletonList(new ServerAddress(host, port)))); return createMongoClient(builder); } @@ -92,14 +89,13 @@ public class ReactiveMongoClientFactory { if (hasCustomAddress() || hasCustomCredentials()) { return createCredentialNetworkMongoClient(settings); } - ConnectionString connectionString = new ConnectionString( - this.properties.determineUri()); + ConnectionString connectionString = new ConnectionString(this.properties.determineUri()); return createMongoClient(createBuilder(settings, connectionString)); } private MongoClient createCredentialNetworkMongoClient(MongoClientSettings settings) { - Assert.state(this.properties.getUri() == null, "Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + Assert.state(this.properties.getUri() == null, + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); Builder builder = builder(settings); if (hasCustomCredentials()) { applyCredentials(builder); @@ -107,17 +103,15 @@ public class ReactiveMongoClientFactory { String host = getOrDefault(this.properties.getHost(), "localhost"); int port = getOrDefault(this.properties.getPort(), MongoProperties.DEFAULT_PORT); ServerAddress serverAddress = new ServerAddress(host, port); - builder.applyToClusterSettings( - (cluster) -> cluster.hosts(Collections.singletonList(serverAddress))); + builder.applyToClusterSettings((cluster) -> cluster.hosts(Collections.singletonList(serverAddress))); return createMongoClient(builder); } private void applyCredentials(Builder builder) { String database = (this.properties.getAuthenticationDatabase() != null) - ? this.properties.getAuthenticationDatabase() - : this.properties.getMongoClientDatabase(); - builder.credential((MongoCredential.createCredential( - this.properties.getUsername(), database, this.properties.getPassword()))); + ? this.properties.getAuthenticationDatabase() : this.properties.getMongoClientDatabase(); + builder.credential((MongoCredential.createCredential(this.properties.getUsername(), database, + this.properties.getPassword()))); } private T getOrDefault(T value, T defaultValue) { @@ -129,8 +123,7 @@ public class ReactiveMongoClientFactory { return MongoClients.create(builder.build()); } - private Builder createBuilder(MongoClientSettings settings, - ConnectionString connection) { + private Builder createBuilder(MongoClientSettings settings, ConnectionString connection) { return builder(settings).applyConnectionString(connection); } @@ -145,8 +138,7 @@ public class ReactiveMongoClientFactory { } private boolean hasCustomCredentials() { - return this.properties.getUsername() != null - && this.properties.getPassword() != null; + return this.properties.getUsername() != null && this.properties.getPassword() != null; } private Builder builder(MongoClientSettings settings) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java index db1998f7e2d..e92a3d0b293 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java @@ -87,20 +87,18 @@ public class EmbeddedMongoAutoConfiguration { private static final byte[] IP4_LOOPBACK_ADDRESS = { 127, 0, 0, 1 }; - private static final byte[] IP6_LOOPBACK_ADDRESS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 1 }; + private static final byte[] IP6_LOOPBACK_ADDRESS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; private final MongoProperties properties; - public EmbeddedMongoAutoConfiguration(MongoProperties properties, - EmbeddedMongoProperties embeddedProperties) { + public EmbeddedMongoAutoConfiguration(MongoProperties properties, EmbeddedMongoProperties embeddedProperties) { this.properties = properties; } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean - public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig, - IRuntimeConfig runtimeConfig, ApplicationContext context) throws IOException { + public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig, IRuntimeConfig runtimeConfig, + ApplicationContext context) throws IOException { Integer configuredPort = this.properties.getPort(); if (configuredPort == null || configuredPort == 0) { setEmbeddedPort(context, mongodConfig.net().getPort()); @@ -118,40 +116,34 @@ public class EmbeddedMongoAutoConfiguration { @Bean @ConditionalOnMissingBean - public IMongodConfig embeddedMongoConfiguration( - EmbeddedMongoProperties embeddedProperties) throws IOException { - MongodConfigBuilder builder = new MongodConfigBuilder() - .version(determineVersion(embeddedProperties)); + public IMongodConfig embeddedMongoConfiguration(EmbeddedMongoProperties embeddedProperties) throws IOException { + MongodConfigBuilder builder = new MongodConfigBuilder().version(determineVersion(embeddedProperties)); EmbeddedMongoProperties.Storage storage = embeddedProperties.getStorage(); if (storage != null) { String databaseDir = storage.getDatabaseDir(); String replSetName = storage.getReplSetName(); - int oplogSize = (storage.getOplogSize() != null) - ? (int) storage.getOplogSize().toMegabytes() : 0; + int oplogSize = (storage.getOplogSize() != null) ? (int) storage.getOplogSize().toMegabytes() : 0; builder.replication(new Storage(databaseDir, replSetName, oplogSize)); } Integer configuredPort = this.properties.getPort(); if (configuredPort != null && configuredPort > 0) { - builder.net(new Net(getHost().getHostAddress(), configuredPort, - Network.localhostIsIPv6())); + builder.net(new Net(getHost().getHostAddress(), configuredPort, Network.localhostIsIPv6())); } else { - builder.net(new Net(getHost().getHostAddress(), - Network.getFreeServerPort(getHost()), Network.localhostIsIPv6())); + builder.net(new Net(getHost().getHostAddress(), Network.getFreeServerPort(getHost()), + Network.localhostIsIPv6())); } return builder.build(); } - private IFeatureAwareVersion determineVersion( - EmbeddedMongoProperties embeddedProperties) { + private IFeatureAwareVersion determineVersion(EmbeddedMongoProperties embeddedProperties) { if (embeddedProperties.getFeatures() == null) { for (Version version : Version.values()) { if (version.asInDownloadPath().equals(embeddedProperties.getVersion())) { return version; } } - return Versions - .withFeatures(new GenericVersion(embeddedProperties.getVersion())); + return Versions.withFeatures(new GenericVersion(embeddedProperties.getVersion())); } return Versions.withFeatures(new GenericVersion(embeddedProperties.getVersion()), embeddedProperties.getFeatures().toArray(new Feature[0])); @@ -159,8 +151,7 @@ public class EmbeddedMongoAutoConfiguration { private InetAddress getHost() throws UnknownHostException { if (this.properties.getHost() == null) { - return InetAddress.getByAddress(Network.localhostIsIPv6() - ? IP6_LOOPBACK_ADDRESS : IP4_LOOPBACK_ADDRESS); + return InetAddress.getByAddress(Network.localhostIsIPv6() ? IP6_LOOPBACK_ADDRESS : IP4_LOOPBACK_ADDRESS); } return InetAddress.getByName(this.properties.getHost()); } @@ -171,8 +162,8 @@ public class EmbeddedMongoAutoConfiguration { private void setPortProperty(ApplicationContext currentContext, int port) { if (currentContext instanceof ConfigurableApplicationContext) { - MutablePropertySources sources = ((ConfigurableApplicationContext) currentContext) - .getEnvironment().getPropertySources(); + MutablePropertySources sources = ((ConfigurableApplicationContext) currentContext).getEnvironment() + .getPropertySources(); getMongoPorts(sources).put("local.mongo.port", port); } if (currentContext.getParent() != null) { @@ -198,16 +189,12 @@ public class EmbeddedMongoAutoConfiguration { @Bean public IRuntimeConfig embeddedMongoRuntimeConfig( ObjectProvider downloadConfigBuilderCustomizers) { - Logger logger = LoggerFactory - .getLogger(getClass().getPackage().getName() + ".EmbeddedMongo"); - ProcessOutput processOutput = new ProcessOutput( - Processors.logTo(logger, Slf4jLevel.INFO), - Processors.logTo(logger, Slf4jLevel.ERROR), Processors.named( - "[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG))); - return new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger) - .processOutput(processOutput) - .artifactStore(getArtifactStore(logger, - downloadConfigBuilderCustomizers.orderedStream())) + Logger logger = LoggerFactory.getLogger(getClass().getPackage().getName() + ".EmbeddedMongo"); + ProcessOutput processOutput = new ProcessOutput(Processors.logTo(logger, Slf4jLevel.INFO), + Processors.logTo(logger, Slf4jLevel.ERROR), + Processors.named("[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG))); + return new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger).processOutput(processOutput) + .artifactStore(getArtifactStore(logger, downloadConfigBuilderCustomizers.orderedStream())) .daemonProcess(false).build(); } @@ -216,11 +203,9 @@ public class EmbeddedMongoAutoConfiguration { DownloadConfigBuilder downloadConfigBuilder = new DownloadConfigBuilder() .defaultsForCommand(Command.MongoD); downloadConfigBuilder.progressListener(new Slf4jProgressListener(logger)); - downloadConfigBuilderCustomizers - .forEach((customizer) -> customizer.customize(downloadConfigBuilder)); + downloadConfigBuilderCustomizers.forEach((customizer) -> customizer.customize(downloadConfigBuilder)); IDownloadConfig downloadConfig = downloadConfigBuilder.build(); - return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD) - .download(downloadConfig); + return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD).download(downloadConfig); } } @@ -231,8 +216,7 @@ public class EmbeddedMongoAutoConfiguration { */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ MongoClient.class, MongoClientFactoryBean.class }) - protected static class EmbeddedMongoDependencyConfiguration - extends MongoClientDependsOnBeanFactoryPostProcessor { + protected static class EmbeddedMongoDependencyConfiguration extends MongoClientDependsOnBeanFactoryPostProcessor { public EmbeddedMongoDependencyConfiguration() { super("embeddedMongoServer"); @@ -245,8 +229,7 @@ public class EmbeddedMongoAutoConfiguration { * {@code embeddedMongoServer} bean. */ @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class, - ReactiveMongoClientFactoryBean.class }) + @ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class, ReactiveMongoClientFactoryBean.class }) protected static class EmbeddedReactiveMongoDependencyConfiguration extends ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java index c24bbddb197..5e947eb2d83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java @@ -54,8 +54,7 @@ public class MustacheAutoConfiguration { private final ApplicationContext applicationContext; - public MustacheAutoConfiguration(MustacheProperties mustache, - ApplicationContext applicationContext) { + public MustacheAutoConfiguration(MustacheProperties mustache, ApplicationContext applicationContext) { this.mustache = mustache; this.applicationContext = applicationContext; } @@ -66,8 +65,7 @@ public class MustacheAutoConfiguration { TemplateLocation location = new TemplateLocation(this.mustache.getPrefix()); if (!location.exists(this.applicationContext)) { logger.warn("Cannot find template location: " + location - + " (please add some templates, check your Mustache " - + "configuration, or set spring.mustache." + + " (please add some templates, check your Mustache " + "configuration, or set spring.mustache." + "check-template-location=false)"); } } @@ -75,10 +73,8 @@ public class MustacheAutoConfiguration { @Bean @ConditionalOnMissingBean - public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader, - Environment environment) { - return Mustache.compiler().withLoader(mustacheTemplateLoader) - .withCollector(collector(environment)); + public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader, Environment environment) { + return Mustache.compiler().withLoader(mustacheTemplateLoader).withCollector(collector(environment)); } private Collector collector(Environment environment) { @@ -90,8 +86,8 @@ public class MustacheAutoConfiguration { @Bean @ConditionalOnMissingBean(TemplateLoader.class) public MustacheResourceTemplateLoader mustacheTemplateLoader() { - MustacheResourceTemplateLoader loader = new MustacheResourceTemplateLoader( - this.mustache.getPrefix(), this.mustache.getSuffix()); + MustacheResourceTemplateLoader loader = new MustacheResourceTemplateLoader(this.mustache.getPrefix(), + this.mustache.getSuffix()); loader.setCharset(this.mustache.getCharsetName()); return loader; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java index 5d4ff697775..0a58f4341de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.core.env.Environment; * @author Madhura Bhave * @since 1.2.2 */ -public class MustacheEnvironmentCollector extends DefaultCollector - implements EnvironmentAware { +public class MustacheEnvironmentCollector extends DefaultCollector implements EnvironmentAware { private ConfigurableEnvironment environment; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheReactiveWebConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheReactiveWebConfiguration.java index f2c3f98a54e..f2cde14a293 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheReactiveWebConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheReactiveWebConfiguration.java @@ -32,8 +32,7 @@ class MustacheReactiveWebConfiguration { @Bean @ConditionalOnMissingBean - public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler, - MustacheProperties mustache) { + public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler, MustacheProperties mustache) { MustacheViewResolver resolver = new MustacheViewResolver(mustacheCompiler); resolver.setPrefix(mustache.getPrefix()); resolver.setSuffix(mustache.getSuffix()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java index 528341fe12f..9c2702cccb7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.core.io.ResourceLoader; * @see Mustache * @see Resource */ -public class MustacheResourceTemplateLoader - implements TemplateLoader, ResourceLoaderAware { +public class MustacheResourceTemplateLoader implements TemplateLoader, ResourceLoaderAware { private String prefix = ""; @@ -77,8 +76,7 @@ public class MustacheResourceTemplateLoader @Override public Reader getTemplate(String name) throws Exception { - return new InputStreamReader(this.resourceLoader - .getResource(this.prefix + name + this.suffix).getInputStream(), + return new InputStreamReader(this.resourceLoader.getResource(this.prefix + name + this.suffix).getInputStream(), this.charSet); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheServletWebConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheServletWebConfiguration.java index 8f138c96946..ec958418ad9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheServletWebConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheServletWebConfiguration.java @@ -32,8 +32,7 @@ class MustacheServletWebConfiguration { @Bean @ConditionalOnMissingBean - public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler, - MustacheProperties mustache) { + public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler, MustacheProperties mustache) { MustacheViewResolver resolver = new MustacheViewResolver(mustacheCompiler); mustache.applyToMvcViewResolver(resolver); resolver.setCharset(mustache.getCharsetName()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java index 7025ca4929a..c12f4d3319b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,17 +29,14 @@ import org.springframework.util.ClassUtils; * @author Madhura Bhave * @since 1.2.2 */ -public class MustacheTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { +public class MustacheTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { if (ClassUtils.isPresent("com.samskivert.mustache.Template", classLoader)) { - String prefix = environment.getProperty("spring.mustache.prefix", - MustacheProperties.DEFAULT_PREFIX); - String suffix = environment.getProperty("spring.mustache.suffix", - MustacheProperties.DEFAULT_SUFFIX); + String prefix = environment.getProperty("spring.mustache.prefix", MustacheProperties.DEFAULT_PREFIX); + String suffix = environment.getProperty("spring.mustache.suffix", MustacheProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } return false; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java index f1753dacc55..22791cd316b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { private HibernateProperties hibernateProperties; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof LocalContainerEntityManagerFactoryBean) { LocalContainerEntityManagerFactoryBean factory = (LocalContainerEntityManagerFactoryBean) bean; factory.setJpaVendorAdapter(new DataSourceSchemaCreatedPublisher(factory)); @@ -70,8 +69,7 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { // Normally this will be the right DataSource this.dataSource = (DataSource) bean; @@ -94,27 +92,23 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { private void publishEventIfRequired(EntityManagerFactory entityManagerFactory) { DataSource dataSource = findDataSource(entityManagerFactory); if (dataSource != null && isInitializingDatabase(dataSource)) { - this.applicationContext - .publishEvent(new DataSourceSchemaCreatedEvent(dataSource)); + this.applicationContext.publishEvent(new DataSourceSchemaCreatedEvent(dataSource)); } } private DataSource findDataSource(EntityManagerFactory entityManagerFactory) { - Object dataSource = entityManagerFactory.getProperties() - .get("javax.persistence.nonJtaDataSource"); - return (dataSource instanceof DataSource) ? (DataSource) dataSource - : this.dataSource; + Object dataSource = entityManagerFactory.getProperties().get("javax.persistence.nonJtaDataSource"); + return (dataSource instanceof DataSource) ? (DataSource) dataSource : this.dataSource; } private boolean isInitializingDatabase(DataSource dataSource) { if (this.jpaProperties == null || this.hibernateProperties == null) { return true; // better safe than sorry } - Supplier defaultDdlAuto = () -> (EmbeddedDatabaseConnection - .isEmbedded(dataSource) ? "create-drop" : "none"); - Map hibernate = this.hibernateProperties - .determineHibernateProperties(this.jpaProperties.getProperties(), - new HibernateSettings().ddlAuto(defaultDdlAuto)); + Supplier defaultDdlAuto = () -> (EmbeddedDatabaseConnection.isEmbedded(dataSource) ? "create-drop" + : "none"); + Map hibernate = this.hibernateProperties.determineHibernateProperties( + this.jpaProperties.getProperties(), new HibernateSettings().ddlAuto(defaultDdlAuto)); if (hibernate.containsKey("hibernate.hbm2ddl.auto")) { return true; } @@ -152,8 +146,7 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { private final LocalContainerEntityManagerFactoryBean factory; - private DataSourceSchemaCreatedPublisher( - LocalContainerEntityManagerFactoryBean factory) { + private DataSourceSchemaCreatedPublisher(LocalContainerEntityManagerFactoryBean factory) { this.delegate = factory.getJpaVendorAdapter(); this.factory = factory; } @@ -198,8 +191,7 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { this.delegate.postProcessEntityManagerFactory(emf); AsyncTaskExecutor bootstrapExecutor = this.factory.getBootstrapExecutor(); if (bootstrapExecutor != null) { - bootstrapExecutor.execute(() -> DataSourceInitializedPublisher.this - .publishEventIfRequired(emf)); + bootstrapExecutor.execute(() -> DataSourceInitializedPublisher.this.publishEventIfRequired(emf)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java index df825a5e795..139e3b3e0f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,8 @@ class HibernateDefaultDdlAutoProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { return StreamSupport.stream(this.providers.spliterator(), false) - .map((provider) -> provider.getSchemaManagement(dataSource)) - .filter(SchemaManagement.MANAGED::equals).findFirst() - .orElse(SchemaManagement.UNMANAGED); + .map((provider) -> provider.getSchemaManagement(dataSource)).filter(SchemaManagement.MANAGED::equals) + .findFirst().orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java index b3ec8f2a315..3a71b5cd9c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java @@ -59,23 +59,19 @@ public class HibernateJpaAutoConfiguration { @Order(Ordered.HIGHEST_PRECEDENCE + 20) static class HibernateEntityManagerCondition extends SpringBootCondition { - private static final String[] CLASS_NAMES = { - "org.hibernate.ejb.HibernateEntityManager", + private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("HibernateEntityManager"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("HibernateEntityManager"); for (String className : CLASS_NAMES) { if (ClassUtils.isPresent(className, context.getClassLoader())) { - return ConditionOutcome - .match(message.found("class").items(Style.QUOTE, className)); + return ConditionOutcome.match(message.found("class").items(Style.QUOTE, className)); } } - return ConditionOutcome.noMatch(message.didNotFind("class", "classes") - .items(Style.QUOTE, Arrays.asList(CLASS_NAMES))); + return ConditionOutcome + .noMatch(message.didNotFind("class", "classes").items(Style.QUOTE, Arrays.asList(CLASS_NAMES))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java index 12e9d7d205f..dce5bbd1d37 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java @@ -87,8 +87,7 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { private final List hibernatePropertiesCustomizers; HibernateJpaConfiguration(DataSource dataSource, JpaProperties jpaProperties, - ConfigurableListableBeanFactory beanFactory, - ObjectProvider jtaTransactionManager, + ConfigurableListableBeanFactory beanFactory, ObjectProvider jtaTransactionManager, HibernateProperties hibernateProperties, ObjectProvider> metadataProviders, ObjectProvider providers, @@ -98,31 +97,25 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { super(dataSource, jpaProperties, jtaTransactionManager); this.hibernateProperties = hibernateProperties; this.defaultDdlAutoProvider = new HibernateDefaultDdlAutoProvider(providers); - this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider( - metadataProviders.getIfAvailable()); + this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(metadataProviders.getIfAvailable()); this.hibernatePropertiesCustomizers = determineHibernatePropertiesCustomizers( - physicalNamingStrategy.getIfAvailable(), - implicitNamingStrategy.getIfAvailable(), beanFactory, - hibernatePropertiesCustomizers.orderedStream() - .collect(Collectors.toList())); + physicalNamingStrategy.getIfAvailable(), implicitNamingStrategy.getIfAvailable(), beanFactory, + hibernatePropertiesCustomizers.orderedStream().collect(Collectors.toList())); } private List determineHibernatePropertiesCustomizers( - PhysicalNamingStrategy physicalNamingStrategy, - ImplicitNamingStrategy implicitNamingStrategy, + PhysicalNamingStrategy physicalNamingStrategy, ImplicitNamingStrategy implicitNamingStrategy, ConfigurableListableBeanFactory beanFactory, List hibernatePropertiesCustomizers) { List customizers = new ArrayList<>(); - if (ClassUtils.isPresent( - "org.hibernate.resource.beans.container.spi.BeanContainer", + if (ClassUtils.isPresent("org.hibernate.resource.beans.container.spi.BeanContainer", getClass().getClassLoader())) { - customizers - .add((properties) -> properties.put(AvailableSettings.BEAN_CONTAINER, - new SpringBeanContainer(beanFactory))); + customizers.add((properties) -> properties.put(AvailableSettings.BEAN_CONTAINER, + new SpringBeanContainer(beanFactory))); } if (physicalNamingStrategy != null || implicitNamingStrategy != null) { - customizers.add(new NamingStrategiesHibernatePropertiesCustomizer( - physicalNamingStrategy, implicitNamingStrategy)); + customizers.add( + new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); } customizers.addAll(hibernatePropertiesCustomizers); return customizers; @@ -135,13 +128,10 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { @Override protected Map getVendorProperties() { - Supplier defaultDdlMode = () -> this.defaultDdlAutoProvider - .getDefaultDdlAuto(getDataSource()); - return new LinkedHashMap<>(this.hibernateProperties.determineHibernateProperties( - getProperties().getProperties(), - new HibernateSettings().ddlAuto(defaultDdlMode) - .hibernatePropertiesCustomizers( - this.hibernatePropertiesCustomizers))); + Supplier defaultDdlMode = () -> this.defaultDdlAutoProvider.getDefaultDdlAuto(getDataSource()); + return new LinkedHashMap<>(this.hibernateProperties + .determineHibernateProperties(getProperties().getProperties(), new HibernateSettings() + .ddlAuto(defaultDdlMode).hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); } @Override @@ -155,8 +145,7 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { } } - private void configureJtaPlatform(Map vendorProperties) - throws LinkageError { + private void configureJtaPlatform(Map vendorProperties) throws LinkageError { JtaTransactionManager jtaTransactionManager = getJtaTransactionManager(); // Make sure Hibernate doesn't attempt to auto-detect a JTA platform if (jtaTransactionManager == null) { @@ -169,38 +158,32 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { } } - private void configureProviderDisablesAutocommit( - Map vendorProperties) { + private void configureProviderDisablesAutocommit(Map vendorProperties) { if (isDataSourceAutoCommitDisabled() && !isJta()) { vendorProperties.put(PROVIDER_DISABLES_AUTOCOMMIT, "true"); } } private boolean isDataSourceAutoCommitDisabled() { - DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider - .getDataSourcePoolMetadata(getDataSource()); - return poolMetadata != null - && Boolean.FALSE.equals(poolMetadata.getDefaultAutoCommit()); + DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider.getDataSourcePoolMetadata(getDataSource()); + return poolMetadata != null && Boolean.FALSE.equals(poolMetadata.getDefaultAutoCommit()); } private boolean runningOnWebSphere() { - return ClassUtils.isPresent( - "com.ibm.websphere.jtaextensions.ExtendedJTATransaction", + return ClassUtils.isPresent("com.ibm.websphere.jtaextensions.ExtendedJTATransaction", getClass().getClassLoader()); } private void configureSpringJtaPlatform(Map vendorProperties, JtaTransactionManager jtaTransactionManager) { try { - vendorProperties.put(JTA_PLATFORM, - new SpringJtaPlatform(jtaTransactionManager)); + vendorProperties.put(JTA_PLATFORM, new SpringJtaPlatform(jtaTransactionManager)); } catch (LinkageError ex) { // NoClassDefFoundError can happen if Hibernate 4.2 is used and some // containers (e.g. JBoss EAP 6) wrap it in the superclass LinkageError if (!isUsingJndi()) { - throw new IllegalStateException("Unable to set Hibernate JTA " - + "platform, are you using the correct " + throw new IllegalStateException("Unable to set Hibernate JTA " + "platform, are you using the correct " + "version of Hibernate?", ex); } // Assume that Hibernate will use JNDI @@ -228,19 +211,17 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { // Continue searching } } - throw new IllegalStateException("No available JtaPlatform candidates amongst " - + Arrays.toString(NO_JTA_PLATFORM_CLASSES)); + throw new IllegalStateException( + "No available JtaPlatform candidates amongst " + Arrays.toString(NO_JTA_PLATFORM_CLASSES)); } - private static class NamingStrategiesHibernatePropertiesCustomizer - implements HibernatePropertiesCustomizer { + private static class NamingStrategiesHibernatePropertiesCustomizer implements HibernatePropertiesCustomizer { private final PhysicalNamingStrategy physicalNamingStrategy; private final ImplicitNamingStrategy implicitNamingStrategy; - NamingStrategiesHibernatePropertiesCustomizer( - PhysicalNamingStrategy physicalNamingStrategy, + NamingStrategiesHibernatePropertiesCustomizer(PhysicalNamingStrategy physicalNamingStrategy, ImplicitNamingStrategy implicitNamingStrategy) { this.physicalNamingStrategy = physicalNamingStrategy; this.implicitNamingStrategy = implicitNamingStrategy; @@ -249,12 +230,10 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { @Override public void customize(Map hibernateProperties) { if (this.physicalNamingStrategy != null) { - hibernateProperties.put("hibernate.physical_naming_strategy", - this.physicalNamingStrategy); + hibernateProperties.put("hibernate.physical_naming_strategy", this.physicalNamingStrategy); } if (this.implicitNamingStrategy != null) { - hibernateProperties.put("hibernate.implicit_naming_strategy", - this.implicitNamingStrategy); + hibernateProperties.put("hibernate.implicit_naming_strategy", this.implicitNamingStrategy); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateProperties.java index 7d0757c28c7..208c9baa492 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,15 +87,14 @@ public class HibernateProperties { * @param settings the settings to apply when determining the configuration properties * @return the Hibernate properties to use */ - public Map determineHibernateProperties( - Map jpaProperties, HibernateSettings settings) { + public Map determineHibernateProperties(Map jpaProperties, + HibernateSettings settings) { Assert.notNull(jpaProperties, "JpaProperties must not be null"); Assert.notNull(settings, "Settings must not be null"); return getAdditionalProperties(jpaProperties, settings); } - private Map getAdditionalProperties(Map existing, - HibernateSettings settings) { + private Map getAdditionalProperties(Map existing, HibernateSettings settings) { Map result = new HashMap<>(existing); applyNewIdGeneratorMappings(result); applyScanner(result); @@ -107,8 +106,7 @@ public class HibernateProperties { else { result.remove(AvailableSettings.HBM2DDL_AUTO); } - Collection customizers = settings - .getHibernatePropertiesCustomizers(); + Collection customizers = settings.getHibernatePropertiesCustomizers(); if (!ObjectUtils.isEmpty(customizers)) { customizers.forEach((customizer) -> customizer.customize(result)); } @@ -117,8 +115,7 @@ public class HibernateProperties { private void applyNewIdGeneratorMappings(Map result) { if (this.useNewIdGeneratorMappings != null) { - result.put(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, - this.useNewIdGeneratorMappings.toString()); + result.put(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, this.useNewIdGeneratorMappings.toString()); } else if (!result.containsKey(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS)) { result.put(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); @@ -126,14 +123,12 @@ public class HibernateProperties { } private void applyScanner(Map result) { - if (!result.containsKey(AvailableSettings.SCANNER) - && ClassUtils.isPresent(DISABLED_SCANNER_CLASS, null)) { + if (!result.containsKey(AvailableSettings.SCANNER) && ClassUtils.isPresent(DISABLED_SCANNER_CLASS, null)) { result.put(AvailableSettings.SCANNER, DISABLED_SCANNER_CLASS); } } - private String determineDdlAuto(Map existing, - Supplier defaultDdlAuto) { + private String determineDdlAuto(Map existing, Supplier defaultDdlAuto) { String ddlAuto = existing.get(AvailableSettings.HBM2DDL_AUTO); if (ddlAuto != null) { return ddlAuto; @@ -170,14 +165,14 @@ public class HibernateProperties { } private void applyNamingStrategies(Map properties) { - applyNamingStrategy(properties, AvailableSettings.IMPLICIT_NAMING_STRATEGY, - this.implicitStrategy, SpringImplicitNamingStrategy.class.getName()); - applyNamingStrategy(properties, AvailableSettings.PHYSICAL_NAMING_STRATEGY, - this.physicalStrategy, SpringPhysicalNamingStrategy.class.getName()); + applyNamingStrategy(properties, AvailableSettings.IMPLICIT_NAMING_STRATEGY, this.implicitStrategy, + SpringImplicitNamingStrategy.class.getName()); + applyNamingStrategy(properties, AvailableSettings.PHYSICAL_NAMING_STRATEGY, this.physicalStrategy, + SpringPhysicalNamingStrategy.class.getName()); } - private void applyNamingStrategy(Map properties, String key, - Object strategy, Object defaultStrategy) { + private void applyNamingStrategy(Map properties, String key, Object strategy, + Object defaultStrategy) { if (strategy != null) { properties.put(key, strategy); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateSettings.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateSettings.java index 4e2b9727264..d4e37e88224 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateSettings.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class HibernateSettings { public HibernateSettings hibernatePropertiesCustomizers( Collection hibernatePropertiesCustomizers) { - this.hibernatePropertiesCustomizers = new ArrayList<>( - hibernatePropertiesCustomizers); + this.hibernatePropertiesCustomizers = new ArrayList<>(hibernatePropertiesCustomizers); return this; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java index 1e7ec78e9aa..86842938755 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java @@ -95,8 +95,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { public PlatformTransactionManager transactionManager( ObjectProvider transactionManagerCustomizers) { JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManagerCustomizers - .ifAvailable((customizers) -> customizers.customize(transactionManager)); + transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager)); return transactionManager; } @@ -117,29 +116,23 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Bean @ConditionalOnMissingBean - public EntityManagerFactoryBuilder entityManagerFactoryBuilder( - JpaVendorAdapter jpaVendorAdapter, + public EntityManagerFactoryBuilder entityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, ObjectProvider persistenceUnitManager, ObjectProvider customizers) { - EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder( - jpaVendorAdapter, this.properties.getProperties(), - persistenceUnitManager.getIfAvailable()); - customizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(jpaVendorAdapter, + this.properties.getProperties(), persistenceUnitManager.getIfAvailable()); + customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Primary - @ConditionalOnMissingBean({ LocalContainerEntityManagerFactoryBean.class, - EntityManagerFactory.class }) - public LocalContainerEntityManagerFactoryBean entityManagerFactory( - EntityManagerFactoryBuilder factoryBuilder) { + @ConditionalOnMissingBean({ LocalContainerEntityManagerFactoryBean.class, EntityManagerFactory.class }) + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) { Map vendorProperties = getVendorProperties(); customizeVendorProperties(vendorProperties); - return factoryBuilder.dataSource(this.dataSource).packages(getPackagesToScan()) - .properties(vendorProperties).mappingResources(getMappingResources()) - .jta(isJta()).build(); + return factoryBuilder.dataSource(this.dataSource).packages(getPackagesToScan()).properties(vendorProperties) + .mappingResources(getMappingResources()).jta(isJta()).build(); } protected abstract AbstractJpaVendorAdapter createJpaVendorAdapter(); @@ -155,8 +148,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { } protected String[] getPackagesToScan() { - List packages = EntityScanPackages.get(this.beanFactory) - .getPackageNames(); + List packages = EntityScanPackages.get(this.beanFactory).getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(this.beanFactory)) { packages = AutoConfigurationPackages.get(this.beanFactory); } @@ -165,8 +157,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { private String[] getMappingResources() { List mappingResources = this.properties.getMappingResources(); - return (!ObjectUtils.isEmpty(mappingResources) - ? StringUtils.toStringArray(mappingResources) : null); + return (!ObjectUtils.isEmpty(mappingResources) ? StringUtils.toStringArray(mappingResources) : null); } /** @@ -209,11 +200,9 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass(WebMvcConfigurer.class) - @ConditionalOnMissingBean({ OpenEntityManagerInViewInterceptor.class, - OpenEntityManagerInViewFilter.class }) + @ConditionalOnMissingBean({ OpenEntityManagerInViewInterceptor.class, OpenEntityManagerInViewFilter.class }) @ConditionalOnMissingFilterBean(OpenEntityManagerInViewFilter.class) - @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", havingValue = "true", matchIfMissing = true) protected static class JpaWebConfiguration { private static final Log logger = LogFactory.getLog(JpaWebConfiguration.class); @@ -229,8 +218,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { if (this.jpaProperties.getOpenInView() == null) { logger.warn("spring.jpa.open-in-view is enabled by default. " + "Therefore, database queries may be performed during view " - + "rendering. Explicitly configure " - + "spring.jpa.open-in-view to disable this warning"); + + "rendering. Explicitly configure " + "spring.jpa.open-in-view to disable this warning"); } return new OpenEntityManagerInViewInterceptor(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.java index 92a706ec855..e25e23c539c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.java @@ -53,19 +53,16 @@ import org.springframework.transaction.PlatformTransactionManager; * @since 2.0.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ Scheduler.class, SchedulerFactoryBean.class, - PlatformTransactionManager.class }) +@ConditionalOnClass({ Scheduler.class, SchedulerFactoryBean.class, PlatformTransactionManager.class }) @EnableConfigurationProperties(QuartzProperties.class) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class QuartzAutoConfiguration { @Bean @ConditionalOnMissingBean public SchedulerFactoryBean quartzScheduler(QuartzProperties properties, - ObjectProvider customizers, - ObjectProvider jobDetails, Map calendars, - ObjectProvider triggers, ApplicationContext applicationContext) { + ObjectProvider customizers, ObjectProvider jobDetails, + Map calendars, ObjectProvider triggers, ApplicationContext applicationContext) { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); SpringBeanJobFactory jobFactory = new SpringBeanJobFactory(); jobFactory.setApplicationContext(applicationContext); @@ -74,23 +71,16 @@ public class QuartzAutoConfiguration { schedulerFactoryBean.setSchedulerName(properties.getSchedulerName()); } schedulerFactoryBean.setAutoStartup(properties.isAutoStartup()); - schedulerFactoryBean - .setStartupDelay((int) properties.getStartupDelay().getSeconds()); - schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown( - properties.isWaitForJobsToCompleteOnShutdown()); - schedulerFactoryBean - .setOverwriteExistingJobs(properties.isOverwriteExistingJobs()); + schedulerFactoryBean.setStartupDelay((int) properties.getStartupDelay().getSeconds()); + schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown(properties.isWaitForJobsToCompleteOnShutdown()); + schedulerFactoryBean.setOverwriteExistingJobs(properties.isOverwriteExistingJobs()); if (!properties.getProperties().isEmpty()) { - schedulerFactoryBean - .setQuartzProperties(asProperties(properties.getProperties())); + schedulerFactoryBean.setQuartzProperties(asProperties(properties.getProperties())); } - schedulerFactoryBean - .setJobDetails(jobDetails.orderedStream().toArray(JobDetail[]::new)); + schedulerFactoryBean.setJobDetails(jobDetails.orderedStream().toArray(JobDetail[]::new)); schedulerFactoryBean.setCalendars(calendars); - schedulerFactoryBean - .setTriggers(triggers.orderedStream().toArray(Trigger[]::new)); - customizers.orderedStream() - .forEach((customizer) -> customizer.customize(schedulerFactoryBean)); + schedulerFactoryBean.setTriggers(triggers.orderedStream().toArray(Trigger[]::new)); + customizers.orderedStream().forEach((customizer) -> customizer.customize(schedulerFactoryBean)); return schedulerFactoryBean; } @@ -106,17 +96,14 @@ public class QuartzAutoConfiguration { @Bean @Order(0) - public SchedulerFactoryBeanCustomizer dataSourceCustomizer( - QuartzProperties properties, DataSource dataSource, + public SchedulerFactoryBeanCustomizer dataSourceCustomizer(QuartzProperties properties, DataSource dataSource, @QuartzDataSource ObjectProvider quartzDataSource, ObjectProvider transactionManager) { return (schedulerFactoryBean) -> { if (properties.getJobStoreType() == JobStoreType.JDBC) { - DataSource dataSourceToUse = getDataSource(dataSource, - quartzDataSource); + DataSource dataSourceToUse = getDataSource(dataSource, quartzDataSource); schedulerFactoryBean.setDataSource(dataSourceToUse); - PlatformTransactionManager txManager = transactionManager - .getIfUnique(); + PlatformTransactionManager txManager = transactionManager.getIfUnique(); if (txManager != null) { schedulerFactoryBean.setTransactionManager(txManager); } @@ -124,21 +111,18 @@ public class QuartzAutoConfiguration { }; } - private DataSource getDataSource(DataSource dataSource, - ObjectProvider quartzDataSource) { + private DataSource getDataSource(DataSource dataSource, ObjectProvider quartzDataSource) { DataSource dataSourceIfAvailable = quartzDataSource.getIfAvailable(); return (dataSourceIfAvailable != null) ? dataSourceIfAvailable : dataSource; } @Bean @ConditionalOnMissingBean - public QuartzDataSourceInitializer quartzDataSourceInitializer( - DataSource dataSource, - @QuartzDataSource ObjectProvider quartzDataSource, - ResourceLoader resourceLoader, QuartzProperties properties) { + public QuartzDataSourceInitializer quartzDataSourceInitializer(DataSource dataSource, + @QuartzDataSource ObjectProvider quartzDataSource, ResourceLoader resourceLoader, + QuartzProperties properties) { DataSource dataSourceToUse = getDataSource(dataSource, quartzDataSource); - return new QuartzDataSourceInitializer(dataSourceToUse, resourceLoader, - properties); + return new QuartzDataSourceInitializer(dataSourceToUse, resourceLoader, properties); } @Bean @@ -150,8 +134,7 @@ public class QuartzAutoConfiguration { extends AbstractDependsOnBeanFactoryPostProcessor { DataSourceInitializerSchedulerDependencyPostProcessor() { - super(Scheduler.class, SchedulerFactoryBean.class, - "quartzDataSourceInitializer"); + super(Scheduler.class, SchedulerFactoryBean.class, "quartzDataSourceInitializer"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSource.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSource.java index 1191a1d8d5b..e703bd49e4d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSource.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @author Madhura Bhave * @since 2.0.2 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializer.java index 763d320b27b..8d62e7b8b64 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ public class QuartzDataSourceInitializer extends AbstractDataSourceInitializer { private final QuartzProperties properties; - public QuartzDataSourceInitializer(DataSource dataSource, - ResourceLoader resourceLoader, QuartzProperties properties) { + public QuartzDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader, + QuartzProperties properties) { super(dataSource, resourceLoader); Assert.notNull(properties, "QuartzProperties must not be null"); this.properties = properties; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzProperties.java index 618a72f3614..15bc597978d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,8 +108,7 @@ public class QuartzProperties { return this.waitForJobsToCompleteOnShutdown; } - public void setWaitForJobsToCompleteOnShutdown( - boolean waitForJobsToCompleteOnShutdown) { + public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) { this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfiguration.java index 297b8d83ac2..b4b85643d3c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfiguration.java @@ -40,8 +40,7 @@ import org.springframework.web.util.pattern.PathPatternRouteMatcher; * @since 2.2.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ RSocketRequester.class, RSocketFactory.class, - TcpServerTransport.class }) +@ConditionalOnClass({ RSocketRequester.class, RSocketFactory.class, TcpServerTransport.class }) @AutoConfigureAfter(RSocketStrategiesAutoConfiguration.class) public class RSocketMessagingAutoConfiguration { @@ -49,8 +48,7 @@ public class RSocketMessagingAutoConfiguration { @Bean @ConditionalOnMissingBean - public MessageHandlerAcceptor messageHandlerAcceptor( - RSocketStrategies rSocketStrategies) { + public MessageHandlerAcceptor messageHandlerAcceptor(RSocketStrategies rSocketStrategies) { MessageHandlerAcceptor acceptor = new MessageHandlerAcceptor(); acceptor.setRSocketStrategies(rSocketStrategies); if (ClassUtils.isPresent(PATHPATTERN_ROUTEMATCHER_CLASS, null)) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfiguration.java index fae2f4285f8..c43dd11352f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfiguration.java @@ -41,16 +41,14 @@ import org.springframework.messaging.rsocket.RSocketStrategies; * @since 2.2.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ RSocketRequester.class, RSocketFactory.class, HttpServer.class, - TcpServerTransport.class }) +@ConditionalOnClass({ RSocketRequester.class, RSocketFactory.class, HttpServer.class, TcpServerTransport.class }) @AutoConfigureAfter(RSocketStrategiesAutoConfiguration.class) public class RSocketRequesterAutoConfiguration { @Bean @Scope("prototype") @ConditionalOnMissingBean - public RSocketRequester.Builder rsocketRequesterBuilder( - RSocketStrategies strategies) { + public RSocketRequester.Builder rsocketRequesterBuilder(RSocketStrategies strategies) { return RSocketRequester.builder().rsocketStrategies(strategies); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java index 43d9ecff6a0..a9107f13abf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java @@ -56,8 +56,7 @@ import org.springframework.messaging.rsocket.RSocketStrategies; * @since 2.2.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ RSocketFactory.class, RSocketStrategies.class, HttpServer.class, - TcpServerTransport.class }) +@ConditionalOnClass({ RSocketFactory.class, RSocketStrategies.class, HttpServer.class, TcpServerTransport.class }) @ConditionalOnBean(MessageHandlerAcceptor.class) @AutoConfigureAfter(RSocketStrategiesAutoConfiguration.class) @EnableConfigurationProperties(RSocketProperties.class) @@ -68,11 +67,10 @@ public class RSocketServerAutoConfiguration { static class WebFluxServerAutoConfiguration { @Bean - public RSocketWebSocketNettyRouteProvider rSocketWebsocketRouteProvider( - RSocketProperties properties, + public RSocketWebSocketNettyRouteProvider rSocketWebsocketRouteProvider(RSocketProperties properties, MessageHandlerAcceptor messageHandlerAcceptor) { - return new RSocketWebSocketNettyRouteProvider( - properties.getServer().getMappingPath(), messageHandlerAcceptor); + return new RSocketWebSocketNettyRouteProvider(properties.getServer().getMappingPath(), + messageHandlerAcceptor); } } @@ -90,21 +88,18 @@ public class RSocketServerAutoConfiguration { @Bean @ConditionalOnMissingBean public RSocketServerFactory rSocketServerFactory(RSocketProperties properties, - ReactorResourceFactory resourceFactory, - ObjectProvider customizers) { + ReactorResourceFactory resourceFactory, ObjectProvider customizers) { NettyRSocketServerFactory factory = new NettyRSocketServerFactory(); factory.setResourceFactory(resourceFactory); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties.getServer().getAddress()).to(factory::setAddress); map.from(properties.getServer().getPort()).to(factory::setPort); - factory.setServerCustomizers( - customizers.orderedStream().collect(Collectors.toList())); + factory.setServerCustomizers(customizers.orderedStream().collect(Collectors.toList())); return factory; } @Bean - public RSocketServerBootstrap rSocketServerBootstrap( - RSocketServerFactory rSocketServerFactory, + public RSocketServerBootstrap rSocketServerBootstrap(RSocketServerFactory rSocketServerFactory, SocketAcceptor socketAcceptor) { return new RSocketServerBootstrap(rSocketServerFactory, socketAcceptor); } @@ -122,8 +117,7 @@ public class RSocketServerAutoConfiguration { } - @ConditionalOnProperty(prefix = "spring.rsocket.server", name = "port", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.rsocket.server", name = "port", matchIfMissing = true) static class HasNoPortConfigured { } @@ -133,8 +127,7 @@ public class RSocketServerAutoConfiguration { } - @ConditionalOnProperty(prefix = "spring.rsocket.server", name = "transport", - havingValue = "websocket") + @ConditionalOnProperty(prefix = "spring.rsocket.server", name = "transport", havingValue = "websocket") static class HasWebsocketTransportConfigured { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfiguration.java index 0d5d91f1def..11fa39c5a20 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfiguration.java @@ -51,23 +51,19 @@ import org.springframework.messaging.rsocket.RSocketStrategies; * @since 2.2.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ RSocketFactory.class, RSocketStrategies.class, - PooledByteBufAllocator.class }) +@ConditionalOnClass({ RSocketFactory.class, RSocketStrategies.class, PooledByteBufAllocator.class }) @AutoConfigureAfter(JacksonAutoConfiguration.class) public class RSocketStrategiesAutoConfiguration { @Bean @ConditionalOnMissingBean - public RSocketStrategies rSocketStrategies( - ObjectProvider customizers) { + public RSocketStrategies rSocketStrategies(ObjectProvider customizers) { RSocketStrategies.Builder builder = RSocketStrategies.builder(); builder.reactiveAdapterStrategy(ReactiveAdapterRegistry.getSharedInstance()); - customizers.orderedStream() - .forEach((customizer) -> customizer.customize(builder)); + customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); builder.decoder(StringDecoder.textPlainOnly()); builder.encoder(CharSequenceEncoder.textPlainOnly()); - builder.dataBufferFactory( - new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)); + builder.dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)); return builder.build(); } @@ -80,8 +76,7 @@ public class RSocketStrategiesAutoConfiguration { @Bean @Order(0) @ConditionalOnBean(Jackson2ObjectMapperBuilder.class) - public RSocketStrategiesCustomizer jacksonCborStrategyCustomizer( - Jackson2ObjectMapperBuilder builder) { + public RSocketStrategiesCustomizer jacksonCborStrategyCustomizer(Jackson2ObjectMapperBuilder builder) { return (strategy) -> { ObjectMapper objectMapper = builder.factory(new CBORFactory()).build(); strategy.decoder(new Jackson2CborDecoder(objectMapper, SUPPORTED_TYPES)); @@ -101,8 +96,7 @@ public class RSocketStrategiesAutoConfiguration { @Bean @Order(1) @ConditionalOnBean(ObjectMapper.class) - public RSocketStrategiesCustomizer jacksonJsonStrategyCustomizer( - ObjectMapper objectMapper) { + public RSocketStrategiesCustomizer jacksonJsonStrategyCustomizer(ObjectMapper objectMapper) { return (strategy) -> { strategy.decoder(new Jackson2JsonDecoder(objectMapper, SUPPORTED_TYPES)); strategy.encoder(new Jackson2JsonEncoder(objectMapper, SUPPORTED_TYPES)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProvider.java index c094cc145d8..df29a7928a4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProvider.java @@ -35,18 +35,16 @@ class RSocketWebSocketNettyRouteProvider implements NettyRouteProvider { private final MessageHandlerAcceptor messageHandlerAcceptor; - RSocketWebSocketNettyRouteProvider(String mappingPath, - MessageHandlerAcceptor messageHandlerAcceptor) { + RSocketWebSocketNettyRouteProvider(String mappingPath, MessageHandlerAcceptor messageHandlerAcceptor) { this.mappingPath = mappingPath; this.messageHandlerAcceptor = messageHandlerAcceptor; } @Override public HttpServerRoutes apply(HttpServerRoutes httpServerRoutes) { - ServerTransport.ConnectionAcceptor acceptor = RSocketFactory.receive() - .acceptor(this.messageHandlerAcceptor).toConnectionAcceptor(); - return httpServerRoutes.ws(this.mappingPath, - WebsocketRouteTransport.newHandler(acceptor)); + ServerTransport.ConnectionAcceptor acceptor = RSocketFactory.receive().acceptor(this.messageHandlerAcceptor) + .toConnectionAcceptor(); + return httpServerRoutes.ws(this.mappingPath, WebsocketRouteTransport.newHandler(acceptor)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java index 2235a05178d..6b26d93192b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,7 @@ public class SecurityProperties { * other filters registered with the container). There is no connection between this * and the {@code @Order} on a WebSecurityConfigurer. */ - public static final int DEFAULT_FILTER_ORDER = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 100; + public static final int DEFAULT_FILTER_ORDER = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100; private final Filter filter = new Filter(); @@ -83,8 +82,8 @@ public class SecurityProperties { /** * Security filter chain dispatcher types. */ - private Set dispatcherTypes = new HashSet<>(Arrays.asList( - DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); + private Set dispatcherTypes = new HashSet<>( + Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); public int getOrder() { return this.order; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java index f10f4f83a1c..b5f60c223e4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,25 +42,19 @@ public class ClientsConfiguredCondition extends SpringBootCondition { .mapOf(String.class, OAuth2ClientProperties.Registration.class); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("OAuth2 Clients Configured Condition"); - Map registrations = getRegistrations( - context.getEnvironment()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth2 Clients Configured Condition"); + Map registrations = getRegistrations(context.getEnvironment()); if (!registrations.isEmpty()) { - return ConditionOutcome.match(message - .foundExactly("registered clients " + registrations.values().stream() - .map(OAuth2ClientProperties.Registration::getClientId) - .collect(Collectors.joining(", ")))); + return ConditionOutcome.match(message.foundExactly("registered clients " + registrations.values().stream() + .map(OAuth2ClientProperties.Registration::getClientId).collect(Collectors.joining(", ")))); } return ConditionOutcome.noMatch(message.notAvailable("registered clients")); } - private Map getRegistrations( - Environment environment) { - return Binder.get(environment).bind("spring.security.oauth2.client.registration", - STRING_REGISTRATION_MAP).orElse(Collections.emptyMap()); + private Map getRegistrations(Environment environment) { + return Binder.get(environment).bind("spring.security.oauth2.client.registration", STRING_REGISTRATION_MAP) + .orElse(Collections.emptyMap()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java index 80cba9bff05..13feae1b360 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { private OAuth2ClientPropertiesRegistrationAdapter() { } - public static Map getClientRegistrations( - OAuth2ClientProperties properties) { + public static Map getClientRegistrations(OAuth2ClientProperties properties) { Map clientRegistrations = new HashMap<>(); properties.getRegistration().forEach((key, value) -> clientRegistrations.put(key, getClientRegistration(key, value, properties.getProvider()))); @@ -56,18 +55,15 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { } private static ClientRegistration getClientRegistration(String registrationId, - OAuth2ClientProperties.Registration properties, - Map providers) { - Builder builder = getBuilderFromIssuerIfPossible(registrationId, - properties.getProvider(), providers); + OAuth2ClientProperties.Registration properties, Map providers) { + Builder builder = getBuilderFromIssuerIfPossible(registrationId, properties.getProvider(), providers); if (builder == null) { builder = getBuilder(registrationId, properties.getProvider(), providers); } PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties::getClientId).to(builder::clientId); map.from(properties::getClientSecret).to(builder::clientSecret); - map.from(properties::getClientAuthenticationMethod) - .as(ClientAuthenticationMethod::new) + map.from(properties::getClientAuthenticationMethod).as(ClientAuthenticationMethod::new) .to(builder::clientAuthenticationMethod); map.from(properties::getAuthorizationGrantType).as(AuthorizationGrantType::new) .to(builder::authorizationGrantType); @@ -77,16 +73,14 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { return builder.build(); } - private static Builder getBuilderFromIssuerIfPossible(String registrationId, - String configuredProviderId, Map providers) { - String providerId = (configuredProviderId != null) ? configuredProviderId - : registrationId; + private static Builder getBuilderFromIssuerIfPossible(String registrationId, String configuredProviderId, + Map providers) { + String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId; if (providers.containsKey(providerId)) { Provider provider = providers.get(providerId); String issuer = provider.getIssuerUri(); if (issuer != null) { - Builder builder = ClientRegistrations.fromOidcIssuerLocation(issuer) - .registrationId(registrationId); + Builder builder = ClientRegistrations.fromOidcIssuerLocation(issuer).registrationId(registrationId); return getBuilder(builder, provider); } } @@ -95,12 +89,10 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { private static Builder getBuilder(String registrationId, String configuredProviderId, Map providers) { - String providerId = (configuredProviderId != null) ? configuredProviderId - : registrationId; + String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId; CommonOAuth2Provider provider = getCommonProvider(providerId); if (provider == null && !providers.containsKey(providerId)) { - throw new IllegalStateException( - getErrorMessage(configuredProviderId, registrationId)); + throw new IllegalStateException(getErrorMessage(configuredProviderId, registrationId)); } Builder builder = (provider != null) ? provider.getBuilder(registrationId) : ClientRegistration.withRegistrationId(registrationId); @@ -110,12 +102,9 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { return builder; } - private static String getErrorMessage(String configuredProviderId, - String registrationId) { - return ((configuredProviderId != null) - ? "Unknown provider ID '" + configuredProviderId + "'" - : "Provider ID must be specified for client registration '" - + registrationId + "'"); + private static String getErrorMessage(String configuredProviderId, String registrationId) { + return ((configuredProviderId != null) ? "Unknown provider ID '" + configuredProviderId + "'" + : "Provider ID must be specified for client registration '" + registrationId + "'"); } private static Builder getBuilder(Builder builder, Provider provider) { @@ -132,8 +121,7 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { private static CommonOAuth2Provider getCommonProvider(String providerId) { try { - return ApplicationConversionService.getSharedInstance().convert(providerId, - CommonOAuth2Provider.class); + return ApplicationConversionService.getSharedInstance().convert(providerId, CommonOAuth2Provider.class); } catch (ConversionException ex) { return null; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfiguration.java index 99553579efb..427acca3079 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfiguration.java @@ -64,8 +64,7 @@ public class ReactiveOAuth2ClientAutoConfiguration { public InMemoryReactiveClientRegistrationRepository clientRegistrationRepository( OAuth2ClientProperties properties) { List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties).values()); + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values()); return new InMemoryReactiveClientRegistrationRepository(registrations); } @@ -74,8 +73,7 @@ public class ReactiveOAuth2ClientAutoConfiguration { @ConditionalOnMissingBean public ReactiveOAuth2AuthorizedClientService authorizedClientService( ReactiveClientRegistrationRepository clientRegistrationRepository) { - return new InMemoryReactiveOAuth2AuthorizedClientService( - clientRegistrationRepository); + return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); } @Bean @@ -83,8 +81,7 @@ public class ReactiveOAuth2ClientAutoConfiguration { @ConditionalOnMissingBean public ServerOAuth2AuthorizedClientRepository authorizedClientRepository( ReactiveOAuth2AuthorizedClientService authorizedClientService) { - return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository( - authorizedClientService); + return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService); } static class NonServletApplicationCondition extends NoneNestedConditions { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientAutoConfiguration.java index 98ee53af4c7..00c71796121 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientAutoConfiguration.java @@ -37,8 +37,7 @@ import org.springframework.security.oauth2.client.registration.ClientRegistratio @AutoConfigureBefore(SecurityAutoConfiguration.class) @ConditionalOnClass({ EnableWebSecurity.class, ClientRegistration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -@Import({ OAuth2ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class }) +@Import({ OAuth2ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class }) public class OAuth2ClientAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.java index c725ce9bd26..740052d7f1d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.java @@ -44,11 +44,9 @@ class OAuth2ClientRegistrationRepositoryConfiguration { @Bean @ConditionalOnMissingBean(ClientRegistrationRepository.class) - public InMemoryClientRegistrationRepository clientRegistrationRepository( - OAuth2ClientProperties properties) { + public InMemoryClientRegistrationRepository clientRegistrationRepository(OAuth2ClientProperties properties) { List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties).values()); + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values()); return new InMemoryClientRegistrationRepository(registrations); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.java index 46ccd8bde0d..b46a92c4886 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.java @@ -50,8 +50,7 @@ class OAuth2WebSecurityConfiguration { @ConditionalOnMissingBean public OAuth2AuthorizedClientRepository authorizedClientRepository( OAuth2AuthorizedClientService authorizedClientService) { - return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository( - authorizedClientService); + return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService); } @Configuration(proxyBeanMethods = false) @@ -60,8 +59,7 @@ class OAuth2WebSecurityConfiguration { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().oauth2Login() - .and().oauth2Client(); + http.authorizeRequests().anyRequest().authenticated().and().oauth2Login().and().oauth2Client(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/IssuerUriCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/IssuerUriCondition.java index 55ff8a780fd..fa8be7d4dd0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/IssuerUriCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/IssuerUriCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,22 +33,16 @@ import org.springframework.util.StringUtils; public class IssuerUriCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("OpenID Connect Issuer URI Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OpenID Connect Issuer URI Condition"); Environment environment = context.getEnvironment(); - String issuerUri = environment - .getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri"); - String jwkSetUri = environment - .getProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri"); + String issuerUri = environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri"); + String jwkSetUri = environment.getProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri"); if (!StringUtils.hasText(issuerUri)) { - return ConditionOutcome - .noMatch(message.didNotFind("issuer-uri property").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("issuer-uri property").atAll()); } if (StringUtils.hasText(jwkSetUri)) { - return ConditionOutcome - .noMatch(message.found("jwk-set-uri property").items(jwkSetUri)); + return ConditionOutcome.noMatch(message.found("jwk-set-uri property").items(jwkSetUri)); } return ConditionOutcome.match(message.foundExactly("issuer-uri property")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java index e96fb98cf59..9f282187fc2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java @@ -33,31 +33,23 @@ import org.springframework.util.StringUtils; public class KeyValueCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Public Key Value Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Public Key Value Condition"); Environment environment = context.getEnvironment(); - String publicKeyLocation = environment.getProperty( - "spring.security.oauth2.resourceserver.jwt.public-key-location"); + String publicKeyLocation = environment + .getProperty("spring.security.oauth2.resourceserver.jwt.public-key-location"); if (!StringUtils.hasText(publicKeyLocation)) { - return ConditionOutcome - .noMatch(message.didNotFind("public-key-location property").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("public-key-location property").atAll()); } - String issuerUri = environment - .getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri"); - String jwkSetUri = environment - .getProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri"); + String issuerUri = environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri"); + String jwkSetUri = environment.getProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri"); if (StringUtils.hasText(jwkSetUri)) { - return ConditionOutcome - .noMatch(message.found("jwk-set-uri property").items(jwkSetUri)); + return ConditionOutcome.noMatch(message.found("jwk-set-uri property").items(jwkSetUri)); } if (StringUtils.hasText(issuerUri)) { - return ConditionOutcome - .noMatch(message.found("issuer-uri property").items(issuerUri)); + return ConditionOutcome.noMatch(message.found("issuer-uri property").items(issuerUri)); } - return ConditionOutcome - .match(message.foundExactly("public key location property")); + return ConditionOutcome.match(message.foundExactly("public key location property")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerProperties.java index e3f2ebc20b0..29e574f1c86 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerProperties.java @@ -99,8 +99,8 @@ public class OAuth2ResourceServerProperties { String key = "spring.security.oauth2.resourceserver.public-key-location"; Assert.notNull(this.publicKeyLocation, "PublicKeyLocation must not be null"); if (!this.publicKeyLocation.exists()) { - throw new InvalidConfigurationPropertyValueException(key, - this.publicKeyLocation, "Public key location does not exist"); + throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation, + "Public key location does not exist"); } try (InputStream inputStream = this.publicKeyLocation.getInputStream()) { return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfiguration.java index ef6ea89057d..9d492cd0b52 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfiguration.java @@ -38,8 +38,7 @@ import org.springframework.security.oauth2.server.resource.BearerTokenAuthentica @Configuration(proxyBeanMethods = false) @AutoConfigureBefore(ReactiveSecurityAutoConfiguration.class) @EnableConfigurationProperties(OAuth2ResourceServerProperties.class) -@ConditionalOnClass({ EnableWebFluxSecurity.class, BearerTokenAuthenticationToken.class, - ReactiveJwtDecoder.class }) +@ConditionalOnClass({ EnableWebFluxSecurity.class, BearerTokenAuthenticationToken.class, ReactiveJwtDecoder.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @Import({ ReactiveOAuth2ResourceServerJwkConfiguration.class, ReactiveOAuth2ResourceServerWebSecurityConfiguration.class }) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java index 2b1c5a138e6..424db3fa884 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java @@ -44,8 +44,7 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { private final OAuth2ResourceServerProperties.Jwt properties; - ReactiveOAuth2ResourceServerJwkConfiguration( - OAuth2ResourceServerProperties properties) { + ReactiveOAuth2ResourceServerJwkConfiguration(OAuth2ResourceServerProperties properties) { this.properties = properties.getJwt(); } @@ -61,14 +60,12 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { @ConditionalOnMissingBean public NimbusReactiveJwtDecoder jwtDecoderByPublicKeyValue() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") - .generatePublic(new X509EncodedKeySpec( - getKeySpec(this.properties.readPublicKey()))); + .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); return NimbusReactiveJwtDecoder.withPublicKey(publicKey).build(); } private byte[] getKeySpec(String keyValue) { - keyValue = keyValue.replace("-----BEGIN PUBLIC KEY-----", "") - .replace("-----END PUBLIC KEY-----", ""); + keyValue = keyValue.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", ""); return Base64.getMimeDecoder().decode(keyValue); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerWebSecurityConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerWebSecurityConfiguration.java index 7f5191b8788..05c2c769446 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerWebSecurityConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerWebSecurityConfiguration.java @@ -35,10 +35,9 @@ class ReactiveOAuth2ResourceServerWebSecurityConfiguration { @Bean @ConditionalOnMissingBean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, - ReactiveJwtDecoder jwtDecoder) { - http.authorizeExchange().anyExchange().authenticated().and() - .oauth2ResourceServer().jwt().jwtDecoder(jwtDecoder); + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ReactiveJwtDecoder jwtDecoder) { + http.authorizeExchange().anyExchange().authenticated().and().oauth2ResourceServer().jwt() + .jwtDecoder(jwtDecoder); return http.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfiguration.java index a2768fb8d92..be425669628 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfiguration.java @@ -38,8 +38,7 @@ import org.springframework.security.oauth2.server.resource.authentication.JwtAut @EnableConfigurationProperties(OAuth2ResourceServerProperties.class) @ConditionalOnClass({ JwtAuthenticationToken.class, JwtDecoder.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -@Import({ OAuth2ResourceServerJwtConfiguration.class, - OAuth2ResourceServerWebSecurityConfiguration.class }) +@Import({ OAuth2ResourceServerJwtConfiguration.class, OAuth2ResourceServerWebSecurityConfiguration.class }) public class OAuth2ResourceServerAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java index e4bd7c03ab4..ece7b6ca138 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java @@ -54,8 +54,7 @@ class OAuth2ResourceServerJwtConfiguration { @ConditionalOnMissingBean public JwtDecoder jwtDecoderByJwkKeySetUri() { return NimbusJwtDecoder.withJwkSetUri(this.properties.getJwkSetUri()) - .jwsAlgorithm(SignatureAlgorithm.from(this.properties.getJwsAlgorithm())) - .build(); + .jwsAlgorithm(SignatureAlgorithm.from(this.properties.getJwsAlgorithm())).build(); } @Bean @@ -63,14 +62,12 @@ class OAuth2ResourceServerJwtConfiguration { @ConditionalOnMissingBean public JwtDecoder jwtDecoderByPublicKeyValue() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") - .generatePublic(new X509EncodedKeySpec( - getKeySpec(this.properties.readPublicKey()))); + .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); return NimbusJwtDecoder.withPublicKey(publicKey).build(); } private byte[] getKeySpec(String keyValue) { - keyValue = keyValue.replace("-----BEGIN PUBLIC KEY-----", "") - .replace("-----END PUBLIC KEY-----", ""); + keyValue = keyValue.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", ""); return Base64.getMimeDecoder().decode(keyValue); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerWebSecurityConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerWebSecurityConfiguration.java index be54d966038..68cc9eab2c6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerWebSecurityConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerWebSecurityConfiguration.java @@ -37,8 +37,7 @@ class OAuth2ResourceServerWebSecurityConfiguration { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and() - .oauth2ResourceServer().jwt(); + http.authorizeRequests().anyRequest().authenticated().and().oauth2ResourceServer().jwt(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfiguration.java index e31dbc54c3e..7701ac67df4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfiguration.java @@ -42,8 +42,7 @@ import org.springframework.web.reactive.config.WebFluxConfigurer; */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(SecurityProperties.class) -@ConditionalOnClass({ Flux.class, EnableWebFluxSecurity.class, WebFilterChainProxy.class, - WebFluxConfigurer.class }) +@ConditionalOnClass({ Flux.class, EnableWebFluxSecurity.class, WebFilterChainProxy.class, WebFluxConfigurer.class }) public class ReactiveSecurityAutoConfiguration { @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java index 0b86f899536..6bc17451fad 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java @@ -47,41 +47,33 @@ import org.springframework.util.StringUtils; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ ReactiveAuthenticationManager.class }) -@ConditionalOnMissingBean({ ReactiveAuthenticationManager.class, - ReactiveUserDetailsService.class }) +@ConditionalOnMissingBean({ ReactiveAuthenticationManager.class, ReactiveUserDetailsService.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) public class ReactiveUserDetailsServiceAutoConfiguration { private static final String NOOP_PASSWORD_PREFIX = "{noop}"; - private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern - .compile("^\\{.+}.*$"); + private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern.compile("^\\{.+}.*$"); - private static final Log logger = LogFactory - .getLog(ReactiveUserDetailsServiceAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(ReactiveUserDetailsServiceAutoConfiguration.class); @Bean - public MapReactiveUserDetailsService reactiveUserDetailsService( - SecurityProperties properties, + public MapReactiveUserDetailsService reactiveUserDetailsService(SecurityProperties properties, ObjectProvider passwordEncoder) { SecurityProperties.User user = properties.getUser(); - UserDetails userDetails = getUserDetails(user, - getOrDeducePassword(user, passwordEncoder.getIfAvailable())); + UserDetails userDetails = getUserDetails(user, getOrDeducePassword(user, passwordEncoder.getIfAvailable())); return new MapReactiveUserDetailsService(userDetails); } private UserDetails getUserDetails(SecurityProperties.User user, String password) { List roles = user.getRoles(); - return User.withUsername(user.getName()).password(password) - .roles(StringUtils.toStringArray(roles)).build(); + return User.withUsername(user.getName()).password(password).roles(StringUtils.toStringArray(roles)).build(); } - private String getOrDeducePassword(SecurityProperties.User user, - PasswordEncoder encoder) { + private String getOrDeducePassword(SecurityProperties.User user, PasswordEncoder encoder) { String password = user.getPassword(); if (user.isPasswordGenerated()) { - logger.info(String.format("%n%nUsing generated security password: %s%n", - user.getPassword())); + logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword())); } if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) { return password; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequest.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequest.java index 055c39dcc69..04f9baa1123 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequest.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,7 @@ public final class StaticResourceRequest { * @param rest additional locations to include * @return the configured {@link ServerWebExchangeMatcher} */ - public StaticResourceServerWebExchange at(StaticResourceLocation first, - StaticResourceLocation... rest) { + public StaticResourceServerWebExchange at(StaticResourceLocation first, StaticResourceLocation... rest) { return at(EnumSet.of(first, rest)); } @@ -92,8 +91,7 @@ public final class StaticResourceRequest { * The server web exchange matcher used to match against resource * {@link StaticResourceLocation locations}. */ - public static final class StaticResourceServerWebExchange - implements ServerWebExchangeMatcher { + public static final class StaticResourceServerWebExchange implements ServerWebExchangeMatcher { private final Set locations; @@ -108,8 +106,7 @@ public final class StaticResourceRequest { * @param rest additional locations to exclude * @return a new {@link StaticResourceServerWebExchange} */ - public StaticResourceServerWebExchange excluding(StaticResourceLocation first, - StaticResourceLocation... rest) { + public StaticResourceServerWebExchange excluding(StaticResourceLocation first, StaticResourceLocation... rest) { return excluding(EnumSet.of(first, rest)); } @@ -119,8 +116,7 @@ public final class StaticResourceRequest { * @param locations the locations to exclude * @return a new {@link StaticResourceServerWebExchange} */ - public StaticResourceServerWebExchange excluding( - Set locations) { + public StaticResourceServerWebExchange excluding(Set locations) { Assert.notNull(locations, "Locations must not be null"); Set subset = new LinkedHashSet<>(this.locations); subset.removeAll(locations); @@ -128,8 +124,7 @@ public final class StaticResourceRequest { } private List getDelegateMatchers() { - return getPatterns().map(PathPatternParserServerWebExchangeMatcher::new) - .collect(Collectors.toList()); + return getPatterns().map(PathPatternParserServerWebExchangeMatcher::new).collect(Collectors.toList()); } private Stream getPatterns() { @@ -138,8 +133,7 @@ public final class StaticResourceRequest { @Override public Mono matches(ServerWebExchange exchange) { - OrServerWebExchangeMatcher matcher = new OrServerWebExchangeMatcher( - getDelegateMatchers()); + OrServerWebExchangeMatcher matcher = new OrServerWebExchangeMatcher(getDelegateMatchers()); return matcher.matches(exchange); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/JerseyRequestMatcherProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/JerseyRequestMatcherProvider.java index 5a0c49e8f7f..9be169f6256 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/JerseyRequestMatcherProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/JerseyRequestMatcherProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class JerseyRequestMatcherProvider implements RequestMatcherProvider { @Override public RequestMatcher getRequestMatcher(String pattern) { - return new AntPathRequestMatcher( - this.jerseyApplicationPath.getRelativePath(pattern)); + return new AntPathRequestMatcher(this.jerseyApplicationPath.getRelativePath(pattern)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/PathRequest.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/PathRequest.java index 2e837a09c61..1dee5f9ee57 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/PathRequest.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/PathRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,7 @@ public final class PathRequest { /** * The request matcher used to match against h2 console path. */ - public static final class H2ConsoleRequestMatcher - extends ApplicationContextRequestMatcher { + public static final class H2ConsoleRequestMatcher extends ApplicationContextRequestMatcher { private volatile RequestMatcher delegate; @@ -72,13 +71,11 @@ public final class PathRequest { @Override protected void initialized(Supplier h2ConsoleProperties) { - this.delegate = new AntPathRequestMatcher( - h2ConsoleProperties.get().getPath() + "/**"); + this.delegate = new AntPathRequestMatcher(h2ConsoleProperties.get().getPath() + "/**"); } @Override - protected boolean matches(HttpServletRequest request, - Supplier context) { + protected boolean matches(HttpServletRequest request, Supplier context) { return this.delegate.matches(request); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.java index da6c5136be5..28788c2693f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.java @@ -45,8 +45,7 @@ public class SecurityAutoConfiguration { @Bean @ConditionalOnMissingBean(AuthenticationEventPublisher.class) - public DefaultAuthenticationEventPublisher authenticationEventPublisher( - ApplicationEventPublisher publisher) { + public DefaultAuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher) { return new DefaultAuthenticationEventPublisher(publisher); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java index 0d05bdb81fe..8b34c4a6ff0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.security.web.context.AbstractSecurityWebApplicationIn @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(SecurityProperties.class) -@ConditionalOnClass({ AbstractSecurityWebApplicationInitializer.class, - SessionCreationPolicy.class }) +@ConditionalOnClass({ AbstractSecurityWebApplicationInitializer.class, SessionCreationPolicy.class }) @AutoConfigureAfter(SecurityAutoConfiguration.class) public class SecurityFilterAutoConfiguration { @@ -68,14 +67,13 @@ public class SecurityFilterAutoConfiguration { return registration; } - private EnumSet getDispatcherTypes( - SecurityProperties securityProperties) { + private EnumSet getDispatcherTypes(SecurityProperties securityProperties) { if (securityProperties.getFilter().getDispatcherTypes() == null) { return null; } return securityProperties.getFilter().getDispatcherTypes().stream() - .map((type) -> DispatcherType.valueOf(type.name())).collect(Collectors - .collectingAndThen(Collectors.toSet(), EnumSet::copyOf)); + .map((type) -> DispatcherType.valueOf(type.name())) + .collect(Collectors.collectingAndThen(Collectors.toSet(), EnumSet::copyOf)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfiguration.java index e1b2e163838..9535eb1310a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfiguration.java @@ -46,8 +46,7 @@ public class SecurityRequestMatcherProviderAutoConfiguration { @Bean @ConditionalOnClass(DispatcherServlet.class) - public RequestMatcherProvider requestMatcherProvider( - HandlerMappingIntrospector introspector) { + public RequestMatcherProvider requestMatcherProvider(HandlerMappingIntrospector introspector) { return new MvcRequestMatcherProvider(introspector); } @@ -60,8 +59,7 @@ public class SecurityRequestMatcherProviderAutoConfiguration { public static class JerseyRequestMatcherConfiguration { @Bean - public RequestMatcherProvider requestMatcherProvider( - JerseyApplicationPath applicationPath) { + public RequestMatcherProvider requestMatcherProvider(JerseyApplicationPath applicationPath) { return new JerseyRequestMatcherProvider(applicationPath); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java index 0c2defe3e0c..b37deb1dd0f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,7 @@ public final class StaticResourceRequest { * @param rest additional locations to include * @return the configured {@link RequestMatcher} */ - public StaticResourceRequestMatcher at(StaticResourceLocation first, - StaticResourceLocation... rest) { + public StaticResourceRequestMatcher at(StaticResourceLocation first, StaticResourceLocation... rest) { return at(EnumSet.of(first, rest)); } @@ -114,8 +113,7 @@ public final class StaticResourceRequest { * @param rest additional locations to exclude * @return a new {@link StaticResourceRequestMatcher} */ - public StaticResourceRequestMatcher excluding(StaticResourceLocation first, - StaticResourceLocation... rest) { + public StaticResourceRequestMatcher excluding(StaticResourceLocation first, StaticResourceLocation... rest) { return excluding(EnumSet.of(first, rest)); } @@ -125,8 +123,7 @@ public final class StaticResourceRequest { * @param locations the locations to exclude * @return a new {@link StaticResourceRequestMatcher} */ - public StaticResourceRequestMatcher excluding( - Set locations) { + public StaticResourceRequestMatcher excluding(Set locations) { Assert.notNull(locations, "Locations must not be null"); Set subset = new LinkedHashSet<>(this.locations); subset.removeAll(locations); @@ -134,16 +131,12 @@ public final class StaticResourceRequest { } @Override - protected void initialized( - Supplier dispatcherServletPath) { - this.delegate = new OrRequestMatcher( - getDelegateMatchers(dispatcherServletPath.get())); + protected void initialized(Supplier dispatcherServletPath) { + this.delegate = new OrRequestMatcher(getDelegateMatchers(dispatcherServletPath.get())); } - private List getDelegateMatchers( - DispatcherServletPath dispatcherServletPath) { - return getPatterns(dispatcherServletPath).map(AntPathRequestMatcher::new) - .collect(Collectors.toList()); + private List getDelegateMatchers(DispatcherServletPath dispatcherServletPath) { + return getPatterns(dispatcherServletPath).map(AntPathRequestMatcher::new).collect(Collectors.toList()); } private Stream getPatterns(DispatcherServletPath dispatcherServletPath) { @@ -152,8 +145,7 @@ public final class StaticResourceRequest { } @Override - protected boolean matches(HttpServletRequest request, - Supplier context) { + protected boolean matches(HttpServletRequest request, Supplier context) { return this.delegate.matches(request); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java index d395cc6ca31..b3f264a22d1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java @@ -54,38 +54,32 @@ import org.springframework.util.StringUtils; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(AuthenticationManager.class) @ConditionalOnBean(ObjectPostProcessor.class) -@ConditionalOnMissingBean({ AuthenticationManager.class, AuthenticationProvider.class, - UserDetailsService.class }) +@ConditionalOnMissingBean({ AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class }) public class UserDetailsServiceAutoConfiguration { private static final String NOOP_PASSWORD_PREFIX = "{noop}"; - private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern - .compile("^\\{.+}.*$"); + private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern.compile("^\\{.+}.*$"); - private static final Log logger = LogFactory - .getLog(UserDetailsServiceAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(UserDetailsServiceAutoConfiguration.class); @Bean @ConditionalOnMissingBean( type = "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository") @Lazy - public InMemoryUserDetailsManager inMemoryUserDetailsManager( - SecurityProperties properties, + public InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties, ObjectProvider passwordEncoder) { SecurityProperties.User user = properties.getUser(); List roles = user.getRoles(); - return new InMemoryUserDetailsManager(User.withUsername(user.getName()) - .password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) - .roles(StringUtils.toStringArray(roles)).build()); + return new InMemoryUserDetailsManager( + User.withUsername(user.getName()).password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) + .roles(StringUtils.toStringArray(roles)).build()); } - private String getOrDeducePassword(SecurityProperties.User user, - PasswordEncoder encoder) { + private String getOrDeducePassword(SecurityProperties.User user, PasswordEncoder encoder) { String password = user.getPassword(); if (user.isPasswordGenerated()) { - logger.info(String.format("%n%nUsing generated security password: %s%n", - user.getPassword())); + logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword())); } if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) { return password; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java index e90691ee5ea..bd187be5c89 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java @@ -47,10 +47,8 @@ public class SendGridAutoConfiguration { @ConditionalOnMissingBean public SendGrid sendGrid(SendGridProperties properties) { if (properties.isProxyConfigured()) { - HttpHost proxy = new HttpHost(properties.getProxy().getHost(), - properties.getProxy().getPort()); - return new SendGrid(properties.getApiKey(), - new Client(HttpClientBuilder.create().setProxy(proxy).build())); + HttpHost proxy = new HttpHost(properties.getProxy().getHost(), properties.getProxy().getPort()); + return new SendGrid(properties.getApiKey(), new Client(HttpClientBuilder.create().setProxy(proxy).build())); } return new SendGrid(properties.getApiKey()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java index 8d2ae4f59aa..705978a46a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java @@ -55,8 +55,7 @@ public class SendGridProperties { } public boolean isProxyConfigured() { - return this.proxy != null && this.proxy.getHost() != null - && this.proxy.getPort() != null; + return this.proxy != null && this.proxy.getHost() != null && this.proxy.getPort() != null; } public static class Proxy { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java index 46ff6fa2bb4..ac072ced3a1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,10 +44,8 @@ abstract class AbstractSessionCondition extends SpringBootCondition { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Session Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Session Condition"); Environment environment = context.getEnvironment(); StoreType required = SessionStoreMappings.getType(this.webApplicationType, ((AnnotationMetadata) metadata).getClassName()); @@ -60,12 +58,10 @@ abstract class AbstractSessionCondition extends SpringBootCondition { return binder.bind("spring.session.store-type", StoreType.class) .map((t) -> new ConditionOutcome(t == required, message.found("spring.session.store-type property").items(t))) - .orElse(ConditionOutcome.noMatch(message - .didNotFind("spring.session.store-type property").atAll())); + .orElse(ConditionOutcome.noMatch(message.didNotFind("spring.session.store-type property").atAll())); } catch (BindException ex) { - return ConditionOutcome.noMatch( - message.found("invalid spring.session.store-type property").atAll()); + return ConditionOutcome.noMatch(message.found("invalid spring.session.store-type property").atAll()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java index 3821063a428..feecd7b0e13 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java @@ -48,8 +48,7 @@ import org.springframework.session.hazelcast.config.annotation.web.http.Hazelcas class HazelcastSessionConfiguration { @Configuration - public static class SpringBootHazelcastHttpSessionConfiguration - extends HazelcastHttpSessionConfiguration { + public static class SpringBootHazelcastHttpSessionConfiguration extends HazelcastHttpSessionConfiguration { @Autowired public void customize(SessionProperties sessionProperties, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java index 349b94bf9b0..7904f845a1c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java @@ -51,20 +51,16 @@ class JdbcSessionConfiguration { @Bean @ConditionalOnMissingBean - public JdbcSessionDataSourceInitializer jdbcSessionDataSourceInitializer( - DataSource dataSource, ResourceLoader resourceLoader, - JdbcSessionProperties properties) { - return new JdbcSessionDataSourceInitializer(dataSource, resourceLoader, - properties); + public JdbcSessionDataSourceInitializer jdbcSessionDataSourceInitializer(DataSource dataSource, + ResourceLoader resourceLoader, JdbcSessionProperties properties) { + return new JdbcSessionDataSourceInitializer(dataSource, resourceLoader, properties); } @Configuration - public static class SpringBootJdbcHttpSessionConfiguration - extends JdbcHttpSessionConfiguration { + public static class SpringBootJdbcHttpSessionConfiguration extends JdbcHttpSessionConfiguration { @Autowired - public void customize(SessionProperties sessionProperties, - JdbcSessionProperties jdbcSessionProperties) { + public void customize(SessionProperties sessionProperties, JdbcSessionProperties jdbcSessionProperties) { Duration timeout = sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceInitializer.java index e54aa5e25d9..4dd4c9f2d8d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ public class JdbcSessionDataSourceInitializer extends AbstractDataSourceInitiali private final JdbcSessionProperties properties; - public JdbcSessionDataSourceInitializer(DataSource dataSource, - ResourceLoader resourceLoader, JdbcSessionProperties properties) { + public JdbcSessionDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader, + JdbcSessionProperties properties) { super(dataSource, resourceLoader); Assert.notNull(properties, "JdbcSessionProperties must not be null"); this.properties = properties; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java index 67d9592e16d..6660b240444 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java @@ -36,8 +36,7 @@ import org.springframework.session.data.mongo.config.annotation.web.reactive.Rea * @author Andy Wilkinson */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ ReactiveMongoOperations.class, - ReactiveMongoOperationsSessionRepository.class }) +@ConditionalOnClass({ ReactiveMongoOperations.class, ReactiveMongoOperationsSessionRepository.class }) @ConditionalOnMissingBean(ReactiveSessionRepository.class) @ConditionalOnBean(ReactiveMongoOperations.class) @Conditional(ReactiveSessionCondition.class) @@ -45,12 +44,10 @@ import org.springframework.session.data.mongo.config.annotation.web.reactive.Rea class MongoReactiveSessionConfiguration { @Configuration - static class SpringBootReactiveMongoWebSessionConfiguration - extends ReactiveMongoWebSessionConfiguration { + static class SpringBootReactiveMongoWebSessionConfiguration extends ReactiveMongoWebSessionConfiguration { @Autowired - public void customize(SessionProperties sessionProperties, - MongoSessionProperties mongoSessionProperties) { + public void customize(SessionProperties sessionProperties, MongoSessionProperties mongoSessionProperties) { Duration timeout = sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java index 9da78ffaeee..c90f6eafc8d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java @@ -45,12 +45,10 @@ import org.springframework.session.data.mongo.config.annotation.web.http.MongoHt class MongoSessionConfiguration { @Configuration - public static class SpringBootMongoHttpSessionConfiguration - extends MongoHttpSessionConfiguration { + public static class SpringBootMongoHttpSessionConfiguration extends MongoHttpSessionConfiguration { @Autowired - public void customize(SessionProperties sessionProperties, - MongoSessionProperties mongoSessionProperties) { + public void customize(SessionProperties sessionProperties, MongoSessionProperties mongoSessionProperties) { Duration timeout = sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryException.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryException.java index a45bd6f1cad..775869adb63 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryException.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ public class NonUniqueSessionRepositoryException extends RuntimeException { public NonUniqueSessionRepositoryException(List> availableCandidates) { super("Multiple session repository candidates are available, set the " + "'spring.session.store-type' property accordingly"); - this.availableCandidates = (!ObjectUtils.isEmpty(availableCandidates) - ? availableCandidates : Collections.emptyList()); + this.availableCandidates = (!ObjectUtils.isEmpty(availableCandidates) ? availableCandidates + : Collections.emptyList()); } public List> getAvailableCandidates() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java index c33fac1c423..3446d52d346 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,24 +24,22 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Stephane Nicoll */ -class NonUniqueSessionRepositoryFailureAnalyzer - extends AbstractFailureAnalyzer { +class NonUniqueSessionRepositoryFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - NonUniqueSessionRepositoryException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, NonUniqueSessionRepositoryException cause) { StringBuilder message = new StringBuilder(); - message.append(String.format("Multiple Spring Session store implementations are " - + "available on the classpath:%n")); + message.append( + String.format("Multiple Spring Session store implementations are " + "available on the classpath:%n")); for (Class candidate : cause.getAvailableCandidates()) { message.append(String.format(" - %s%n", candidate.getName())); } StringBuilder action = new StringBuilder(); action.append(String.format("Consider any of the following:%n")); - action.append(String.format(" - Define the `spring.session.store-type` " - + "property to the store you want to use%n")); - action.append(String.format(" - Review your classpath and remove the unwanted " - + "store implementation(s)%n")); + action.append(String + .format(" - Define the `spring.session.store-type` " + "property to the store you want to use%n")); + action.append( + String.format(" - Review your classpath and remove the unwanted " + "store implementation(s)%n")); return new FailureAnalysis(message.toString(), action.toString(), cause); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java index ab26f979bdc..95076df2add 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java @@ -36,8 +36,7 @@ import org.springframework.session.data.redis.config.annotation.web.server.Redis * @author Andy Wilkinson */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ ReactiveRedisConnectionFactory.class, - ReactiveRedisOperationsSessionRepository.class }) +@ConditionalOnClass({ ReactiveRedisConnectionFactory.class, ReactiveRedisOperationsSessionRepository.class }) @ConditionalOnMissingBean(ReactiveSessionRepository.class) @ConditionalOnBean(ReactiveRedisConnectionFactory.class) @Conditional(ReactiveSessionCondition.class) @@ -45,12 +44,10 @@ import org.springframework.session.data.redis.config.annotation.web.server.Redis class RedisReactiveSessionConfiguration { @Configuration - static class SpringBootRedisWebSessionConfiguration - extends RedisWebSessionConfiguration { + static class SpringBootRedisWebSessionConfiguration extends RedisWebSessionConfiguration { @Autowired - public void customize(SessionProperties sessionProperties, - RedisSessionProperties redisSessionProperties) { + public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties) { Duration timeout = sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java index 94e5f941542..78282c76cd8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java @@ -49,12 +49,10 @@ import org.springframework.session.data.redis.config.annotation.web.http.RedisHt class RedisSessionConfiguration { @Configuration - public static class SpringBootRedisHttpSessionConfiguration - extends RedisHttpSessionConfiguration { + public static class SpringBootRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration { @Autowired - public void customize(SessionProperties sessionProperties, - RedisSessionProperties redisSessionProperties) { + public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties) { Duration timeout = sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java index 1d309fb5acf..c766828de84 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java @@ -78,9 +78,8 @@ import org.springframework.util.ClassUtils; @ConditionalOnWebApplication @EnableConfigurationProperties({ ServerProperties.class, SessionProperties.class }) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, HazelcastAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, RedisAutoConfiguration.class, - RedisReactiveAutoConfiguration.class }) + JdbcTemplateAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class }) @AutoConfigureBefore(HttpHandlerAutoConfiguration.class) public class SessionAutoConfiguration { @@ -88,14 +87,12 @@ public class SessionAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) - @Import({ ServletSessionRepositoryValidator.class, - SessionRepositoryFilterConfiguration.class }) + @Import({ ServletSessionRepositoryValidator.class, SessionRepositoryFilterConfiguration.class }) static class ServletSessionConfiguration { @Bean @Conditional(DefaultCookieSerializerCondition.class) - public DefaultCookieSerializer cookieSerializer( - ServerProperties serverProperties) { + public DefaultCookieSerializer cookieSerializer(ServerProperties serverProperties) { Cookie cookie = serverProperties.getServlet().getSession().getCookie(); DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); @@ -104,12 +101,9 @@ public class SessionAutoConfiguration { map.from(cookie::getPath).to(cookieSerializer::setCookiePath); map.from(cookie::getHttpOnly).to(cookieSerializer::setUseHttpOnlyCookie); map.from(cookie::getSecure).to(cookieSerializer::setUseSecureCookie); - map.from(cookie::getMaxAge).to((maxAge) -> cookieSerializer - .setCookieMaxAge((int) maxAge.getSeconds())); - if (ClassUtils.isPresent(REMEMBER_ME_SERVICES_CLASS, - getClass().getClassLoader())) { - new RememberMeServicesCookieSerializerCustomizer() - .apply(cookieSerializer); + map.from(cookie::getMaxAge).to((maxAge) -> cookieSerializer.setCookieMaxAge((int) maxAge.getSeconds())); + if (ClassUtils.isPresent(REMEMBER_ME_SERVICES_CLASS, getClass().getClassLoader())) { + new RememberMeServicesCookieSerializerCustomizer().apply(cookieSerializer); } return cookieSerializer; } @@ -146,8 +140,7 @@ public class SessionAutoConfiguration { static class RememberMeServicesCookieSerializerCustomizer { public void apply(DefaultCookieSerializer cookieSerializer) { - cookieSerializer.setRememberMeRequestAttribute( - SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); + cookieSerializer.setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); } } @@ -184,8 +177,7 @@ public class SessionAutoConfiguration { protected final String[] selectImports(WebApplicationType webApplicationType) { return Arrays.stream(StoreType.values()) - .map((type) -> SessionStoreMappings - .getConfigurationClass(webApplicationType, type)) + .map((type) -> SessionStoreMappings.getConfigurationClass(webApplicationType, type)) .toArray(String[]::new); } @@ -195,8 +187,7 @@ public class SessionAutoConfiguration { * {@link ImportSelector} to add {@link StoreType} configuration classes for reactive * web applications. */ - static class ReactiveSessionConfigurationImportSelector - extends SessionConfigurationImportSelector { + static class ReactiveSessionConfigurationImportSelector extends SessionConfigurationImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { @@ -209,8 +200,7 @@ public class SessionAutoConfiguration { * {@link ImportSelector} to add {@link StoreType} configuration classes for Servlet * web applications. */ - static class ServletSessionConfigurationImportSelector - extends SessionConfigurationImportSelector { + static class ServletSessionConfigurationImportSelector extends SessionConfigurationImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { @@ -231,8 +221,7 @@ public class SessionAutoConfiguration { private final SessionProperties sessionProperties; - AbstractSessionRepositoryImplementationValidator( - ApplicationContext applicationContext, + AbstractSessionRepositoryImplementationValidator(ApplicationContext applicationContext, SessionProperties sessionProperties, List candidates) { this.classLoader = applicationContext.getClassLoader(); this.sessionProperties = sessionProperties; @@ -272,14 +261,13 @@ public class SessionAutoConfiguration { static class ServletSessionRepositoryImplementationValidator extends AbstractSessionRepositoryImplementationValidator { - ServletSessionRepositoryImplementationValidator( - ApplicationContext applicationContext, + ServletSessionRepositoryImplementationValidator(ApplicationContext applicationContext, SessionProperties sessionProperties) { - super(applicationContext, sessionProperties, Arrays.asList( - "org.springframework.session.hazelcast.HazelcastSessionRepository", - "org.springframework.session.jdbc.JdbcOperationsSessionRepository", - "org.springframework.session.data.mongo.MongoOperationsSessionRepository", - "org.springframework.session.data.redis.RedisOperationsSessionRepository")); + super(applicationContext, sessionProperties, + Arrays.asList("org.springframework.session.hazelcast.HazelcastSessionRepository", + "org.springframework.session.jdbc.JdbcOperationsSessionRepository", + "org.springframework.session.data.mongo.MongoOperationsSessionRepository", + "org.springframework.session.data.redis.RedisOperationsSessionRepository")); } } @@ -291,12 +279,11 @@ public class SessionAutoConfiguration { static class ReactiveSessionRepositoryImplementationValidator extends AbstractSessionRepositoryImplementationValidator { - ReactiveSessionRepositoryImplementationValidator( - ApplicationContext applicationContext, + ReactiveSessionRepositoryImplementationValidator(ApplicationContext applicationContext, SessionProperties sessionProperties) { - super(applicationContext, sessionProperties, Arrays.asList( - "org.springframework.session.data.redis.ReactiveRedisOperationsSessionRepository", - "org.springframework.session.data.mongo.ReactiveMongoOperationsSessionRepository")); + super(applicationContext, sessionProperties, + Arrays.asList("org.springframework.session.data.redis.ReactiveRedisOperationsSessionRepository", + "org.springframework.session.data.mongo.ReactiveMongoOperationsSessionRepository")); } } @@ -319,8 +306,7 @@ public class SessionAutoConfiguration { @PostConstruct public void checkSessionRepository() { StoreType storeType = this.sessionProperties.getStoreType(); - if (storeType != StoreType.NONE - && this.sessionRepositoryProvider.getIfAvailable() == null + if (storeType != StoreType.NONE && this.sessionRepositoryProvider.getIfAvailable() == null && storeType != null) { throw new SessionRepositoryUnavailableException( "No session repository could be auto-configured, check your " @@ -336,8 +322,7 @@ public class SessionAutoConfiguration { * Bean used to validate that a {@link SessionRepository} exists and provide a * meaningful message if that's not the case. */ - static class ServletSessionRepositoryValidator - extends AbstractSessionRepositoryValidator { + static class ServletSessionRepositoryValidator extends AbstractSessionRepositoryValidator { ServletSessionRepositoryValidator(SessionProperties sessionProperties, ObjectProvider> sessionRepositoryProvider) { @@ -350,8 +335,7 @@ public class SessionAutoConfiguration { * Bean used to validate that a {@link ReactiveSessionRepository} exists and provide a * meaningful message if that's not the case. */ - static class ReactiveSessionRepositoryValidator - extends AbstractSessionRepositoryValidator { + static class ReactiveSessionRepositoryValidator extends AbstractSessionRepositoryValidator { ReactiveSessionRepositoryValidator(SessionProperties sessionProperties, ObjectProvider> sessionRepositoryProvider) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java index be4374c703c..d35986f4ae8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java @@ -113,8 +113,8 @@ public class SessionProperties { /** * Session repository filter dispatcher types. */ - private Set filterDispatcherTypes = new HashSet<>(Arrays.asList( - DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); + private Set filterDispatcherTypes = new HashSet<>( + Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); public int getFilterOrder() { return this.filterOrder; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java index a6cc5120b68..9e85a3625eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java @@ -41,22 +41,19 @@ class SessionRepositoryFilterConfiguration { @Bean public FilterRegistrationBean> sessionRepositoryFilterRegistration( SessionProperties sessionProperties, SessionRepositoryFilter filter) { - FilterRegistrationBean> registration = new FilterRegistrationBean<>( - filter); + FilterRegistrationBean> registration = new FilterRegistrationBean<>(filter); registration.setDispatcherTypes(getDispatcherTypes(sessionProperties)); registration.setOrder(sessionProperties.getServlet().getFilterOrder()); return registration; } - private EnumSet getDispatcherTypes( - SessionProperties sessionProperties) { + private EnumSet getDispatcherTypes(SessionProperties sessionProperties) { SessionProperties.Servlet servletProperties = sessionProperties.getServlet(); if (servletProperties.getFilterDispatcherTypes() == null) { return null; } - return servletProperties.getFilterDispatcherTypes().stream() - .map((type) -> DispatcherType.valueOf(type.name())).collect(Collectors - .collectingAndThen(Collectors.toSet(), EnumSet::copyOf)); + return servletProperties.getFilterDispatcherTypes().stream().map((type) -> DispatcherType.valueOf(type.name())) + .collect(Collectors.collectingAndThen(Collectors.toSet(), EnumSet::copyOf)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java index 74fa8339737..6d391a00e68 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,39 +36,32 @@ final class SessionStoreMappings { static { Map mappings = new EnumMap<>(StoreType.class); - mappings.put(StoreType.REDIS, new Configurations(RedisSessionConfiguration.class, - RedisReactiveSessionConfiguration.class)); + mappings.put(StoreType.REDIS, + new Configurations(RedisSessionConfiguration.class, RedisReactiveSessionConfiguration.class)); mappings.put(StoreType.MONGODB, - new Configurations(MongoSessionConfiguration.class, - MongoReactiveSessionConfiguration.class)); - mappings.put(StoreType.JDBC, - new Configurations(JdbcSessionConfiguration.class, null)); - mappings.put(StoreType.HAZELCAST, - new Configurations(HazelcastSessionConfiguration.class, null)); - mappings.put(StoreType.NONE, new Configurations(NoOpSessionConfiguration.class, - NoOpReactiveSessionConfiguration.class)); + new Configurations(MongoSessionConfiguration.class, MongoReactiveSessionConfiguration.class)); + mappings.put(StoreType.JDBC, new Configurations(JdbcSessionConfiguration.class, null)); + mappings.put(StoreType.HAZELCAST, new Configurations(HazelcastSessionConfiguration.class, null)); + mappings.put(StoreType.NONE, + new Configurations(NoOpSessionConfiguration.class, NoOpReactiveSessionConfiguration.class)); MAPPINGS = Collections.unmodifiableMap(mappings); } private SessionStoreMappings() { } - public static String getConfigurationClass(WebApplicationType webApplicationType, - StoreType sessionStoreType) { + public static String getConfigurationClass(WebApplicationType webApplicationType, StoreType sessionStoreType) { Configurations configurations = MAPPINGS.get(sessionStoreType); - Assert.state(configurations != null, - () -> "Unknown session store type " + sessionStoreType); + Assert.state(configurations != null, () -> "Unknown session store type " + sessionStoreType); return configurations.getConfiguration(webApplicationType); } - public static StoreType getType(WebApplicationType webApplicationType, - String configurationClass) { + public static StoreType getType(WebApplicationType webApplicationType, String configurationClass) { return MAPPINGS.entrySet().stream() .filter((entry) -> ObjectUtils.nullSafeEquals(configurationClass, entry.getValue().getConfiguration(webApplicationType))) .map(Map.Entry::getKey).findFirst() - .orElseThrow(() -> new IllegalStateException( - "Unknown configuration class " + configurationClass)); + .orElseThrow(() -> new IllegalStateException("Unknown configuration class " + configurationClass)); } private static class Configurations { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/solr/SolrAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/solr/SolrAutoConfiguration.java index b66304e5950..cda7f766d50 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/solr/SolrAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/solr/SolrAutoConfiguration.java @@ -46,8 +46,7 @@ public class SolrAutoConfiguration { @ConditionalOnMissingBean public SolrClient solrClient(SolrProperties properties) { if (StringUtils.hasText(properties.getZkHost())) { - return new CloudSolrClient.Builder(Arrays.asList(properties.getZkHost()), - Optional.empty()).build(); + return new CloudSolrClient.Builder(Arrays.asList(properties.getZkHost()), Optional.empty()).build(); } return new HttpSolrClient.Builder(properties.getHost()).build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfiguration.java index cd6316de921..4282aac7c5b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfiguration.java @@ -48,10 +48,8 @@ import org.springframework.scheduling.config.TaskManagementConfigUtils; public class TaskSchedulingAutoConfiguration { @Bean - @ConditionalOnBean( - name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME) - @ConditionalOnMissingBean({ SchedulingConfigurer.class, TaskScheduler.class, - ScheduledExecutorService.class }) + @ConditionalOnBean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean({ SchedulingConfigurer.class, TaskScheduler.class, ScheduledExecutorService.class }) public ThreadPoolTaskScheduler taskScheduler(TaskSchedulerBuilder builder) { return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java index cae2eebfa5d..d152a393f6b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java @@ -28,8 +28,7 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver; * @author Andy Wilkinson * @since 1.1.0 */ -public abstract class AbstractTemplateViewResolverProperties - extends AbstractViewResolverProperties { +public abstract class AbstractTemplateViewResolverProperties extends AbstractViewResolverProperties { /** * Prefix that gets prepended to view names when building a URL. @@ -76,8 +75,7 @@ public abstract class AbstractTemplateViewResolverProperties */ private boolean allowSessionOverride = false; - protected AbstractTemplateViewResolverProperties(String defaultPrefix, - String defaultSuffix) { + protected AbstractTemplateViewResolverProperties(String defaultPrefix, String defaultSuffix) { this.prefix = defaultPrefix; this.suffix = defaultSuffix; } @@ -154,8 +152,7 @@ public abstract class AbstractTemplateViewResolverProperties */ public void applyToMvcViewResolver(Object viewResolver) { Assert.isInstanceOf(AbstractTemplateViewResolver.class, viewResolver, - "ViewResolver is not an instance of AbstractTemplateViewResolver :" - + viewResolver); + "ViewResolver is not an instance of AbstractTemplateViewResolver :" + viewResolver); AbstractTemplateViewResolver resolver = (AbstractTemplateViewResolver) viewResolver; resolver.setPrefix(getPrefix()); resolver.setSuffix(getSuffix()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java index fd181b68303..6c4182888ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.util.ClassUtils; * @author Madhura Bhave * @since 1.4.6 */ -public abstract class PathBasedTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { +public abstract class PathBasedTemplateAvailabilityProvider implements TemplateAvailabilityProvider { private final String className; @@ -43,20 +42,18 @@ public abstract class PathBasedTemplateAvailabilityProvider @SuppressWarnings("unchecked") public PathBasedTemplateAvailabilityProvider(String className, - Class propertiesClass, - String propertyPrefix) { + Class propertiesClass, String propertyPrefix) { this.className = className; this.propertiesClass = (Class) propertiesClass; this.propertyPrefix = propertyPrefix; } @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { if (ClassUtils.isPresent(this.className, classLoader)) { Binder binder = Binder.get(environment); - TemplateAvailabilityProperties properties = binder - .bind(this.propertyPrefix, this.propertiesClass) + TemplateAvailabilityProperties properties = binder.bind(this.propertyPrefix, this.propertiesClass) .orElseCreate(this.propertiesClass); return isTemplateAvailable(view, resourceLoader, properties); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java index 01b50303200..4f7ecb6f605 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public interface TemplateAvailabilityProvider { * @param resourceLoader the resource loader * @return if the template is available */ - boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader); + boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java index 1c7dffe3520..460dae4e639 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class TemplateAvailabilityProviders { /** * Resolved template views, returning already cached instances without a global lock. */ - private final Map resolved = new ConcurrentHashMap<>( - CACHE_LIMIT); + private final Map resolved = new ConcurrentHashMap<>(CACHE_LIMIT); /** * Map from view name resolve template view, synchronized when accessed. @@ -60,8 +59,7 @@ public class TemplateAvailabilityProviders { CACHE_LIMIT, 0.75f, true) { @Override - protected boolean removeEldestEntry( - Map.Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { if (size() > CACHE_LIMIT) { TemplateAvailabilityProviders.this.resolved.remove(eldest.getKey()); return true; @@ -85,16 +83,14 @@ public class TemplateAvailabilityProviders { */ public TemplateAvailabilityProviders(ClassLoader classLoader) { Assert.notNull(classLoader, "ClassLoader must not be null"); - this.providers = SpringFactoriesLoader - .loadFactories(TemplateAvailabilityProvider.class, classLoader); + this.providers = SpringFactoriesLoader.loadFactories(TemplateAvailabilityProvider.class, classLoader); } /** * Create a new {@link TemplateAvailabilityProviders} instance. * @param providers the underlying providers */ - protected TemplateAvailabilityProviders( - Collection providers) { + protected TemplateAvailabilityProviders(Collection providers) { Assert.notNull(providers, "Providers must not be null"); this.providers = new ArrayList<>(providers); } @@ -113,11 +109,10 @@ public class TemplateAvailabilityProviders { * @param applicationContext the application context * @return a {@link TemplateAvailabilityProvider} or null */ - public TemplateAvailabilityProvider getProvider(String view, - ApplicationContext applicationContext) { + public TemplateAvailabilityProvider getProvider(String view, ApplicationContext applicationContext) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); - return getProvider(view, applicationContext.getEnvironment(), - applicationContext.getClassLoader(), applicationContext); + return getProvider(view, applicationContext.getEnvironment(), applicationContext.getClassLoader(), + applicationContext); } /** @@ -128,14 +123,13 @@ public class TemplateAvailabilityProviders { * @param resourceLoader the resource loader * @return a {@link TemplateAvailabilityProvider} or null */ - public TemplateAvailabilityProvider getProvider(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public TemplateAvailabilityProvider getProvider(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { Assert.notNull(view, "View must not be null"); Assert.notNull(environment, "Environment must not be null"); Assert.notNull(classLoader, "ClassLoader must not be null"); Assert.notNull(resourceLoader, "ResourceLoader must not be null"); - Boolean useCache = environment.getProperty("spring.template.provider.cache", - Boolean.class, true); + Boolean useCache = environment.getProperty("spring.template.provider.cache", Boolean.class, true); if (!useCache) { return findProvider(view, environment, classLoader, resourceLoader); } @@ -151,24 +145,21 @@ public class TemplateAvailabilityProviders { return (provider != NONE) ? provider : null; } - private TemplateAvailabilityProvider findProvider(String view, - Environment environment, ClassLoader classLoader, + private TemplateAvailabilityProvider findProvider(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { for (TemplateAvailabilityProvider candidate : this.providers) { - if (candidate.isTemplateAvailable(view, environment, classLoader, - resourceLoader)) { + if (candidate.isTemplateAvailable(view, environment, classLoader, resourceLoader)) { return candidate; } } return null; } - private static class NoTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { + private static class NoTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { return false; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java index b12a8a96c42..bb5fd8df5a9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java @@ -84,15 +84,13 @@ public class ThymeleafAutoConfiguration { @ConditionalOnMissingBean(name = "defaultTemplateResolver") static class DefaultTemplateResolverConfiguration { - private static final Log logger = LogFactory - .getLog(DefaultTemplateResolverConfiguration.class); + private static final Log logger = LogFactory.getLog(DefaultTemplateResolverConfiguration.class); private final ThymeleafProperties properties; private final ApplicationContext applicationContext; - DefaultTemplateResolverConfiguration(ThymeleafProperties properties, - ApplicationContext applicationContext) { + DefaultTemplateResolverConfiguration(ThymeleafProperties properties, ApplicationContext applicationContext) { this.properties = properties; this.applicationContext = applicationContext; } @@ -101,11 +99,9 @@ public class ThymeleafAutoConfiguration { public void checkTemplateLocationExists() { boolean checkTemplateLocation = this.properties.isCheckTemplateLocation(); if (checkTemplateLocation) { - TemplateLocation location = new TemplateLocation( - this.properties.getPrefix()); + TemplateLocation location = new TemplateLocation(this.properties.getPrefix()); if (!location.exists(this.applicationContext)) { - logger.warn("Cannot find template location: " + location - + " (please add some templates or check " + logger.warn("Cannot find template location: " + location + " (please add some templates or check " + "your Thymeleaf configuration)"); } } @@ -138,12 +134,10 @@ public class ThymeleafAutoConfiguration { @Bean @ConditionalOnMissingBean public SpringTemplateEngine templateEngine(ThymeleafProperties properties, - ObjectProvider templateResolvers, - ObjectProvider dialects) { + ObjectProvider templateResolvers, ObjectProvider dialects) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler()); - engine.setRenderHiddenMarkersBeforeCheckboxes( - properties.isRenderHiddenMarkersBeforeCheckboxes()); + engine.setRenderHiddenMarkersBeforeCheckboxes(properties.isRenderHiddenMarkersBeforeCheckboxes()); templateResolvers.orderedStream().forEach(engine::addTemplateResolver); dialects.orderedStream().forEach(engine::addDialect); return engine; @@ -171,14 +165,13 @@ public class ThymeleafAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "thymeleafViewResolver") - public ThymeleafViewResolver thymeleafViewResolver( - ThymeleafProperties properties, SpringTemplateEngine templateEngine) { + public ThymeleafViewResolver thymeleafViewResolver(ThymeleafProperties properties, + SpringTemplateEngine templateEngine) { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine); resolver.setCharacterEncoding(properties.getEncoding().name()); resolver.setContentType( - appendCharset(properties.getServlet().getContentType(), - resolver.getCharacterEncoding())); + appendCharset(properties.getServlet().getContentType(), resolver.getCharacterEncoding())); resolver.setProducePartialOutputWhileProcessing( properties.getServlet().isProducePartialOutputWhileProcessing()); resolver.setExcludedViewNames(properties.getExcludedViewNames()); @@ -212,12 +205,10 @@ public class ThymeleafAutoConfiguration { @Bean @ConditionalOnMissingBean(ISpringWebFluxTemplateEngine.class) public SpringWebFluxTemplateEngine templateEngine(ThymeleafProperties properties, - ObjectProvider templateResolvers, - ObjectProvider dialects) { + ObjectProvider templateResolvers, ObjectProvider dialects) { SpringWebFluxTemplateEngine engine = new SpringWebFluxTemplateEngine(); engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler()); - engine.setRenderHiddenMarkersBeforeCheckboxes( - properties.isRenderHiddenMarkersBeforeCheckboxes()); + engine.setRenderHiddenMarkersBeforeCheckboxes(properties.isRenderHiddenMarkersBeforeCheckboxes()); templateResolvers.orderedStream().forEach(engine::addTemplateResolver); dialects.orderedStream().forEach(engine::addDialect); return engine; @@ -232,8 +223,7 @@ public class ThymeleafAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "thymeleafReactiveViewResolver") - public ThymeleafReactiveViewResolver thymeleafViewResolver( - ISpringWebFluxTemplateEngine templateEngine, + public ThymeleafReactiveViewResolver thymeleafViewResolver(ISpringWebFluxTemplateEngine templateEngine, ThymeleafProperties properties) { ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver(); resolver.setTemplateEngine(templateEngine); @@ -245,24 +235,20 @@ public class ThymeleafAutoConfiguration { return resolver; } - private void mapProperties(ThymeleafProperties properties, - ThymeleafReactiveViewResolver resolver) { + private void mapProperties(ThymeleafProperties properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getEncoding).to(resolver::setDefaultCharset); resolver.setExcludedViewNames(properties.getExcludedViewNames()); resolver.setViewNames(properties.getViewNames()); } - private void mapReactiveProperties(Reactive properties, - ThymeleafReactiveViewResolver resolver) { + private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); - map.from(properties::getMediaTypes).whenNonNull() - .to(resolver::setSupportedMediaTypes); - map.from(properties::getMaxChunkSize).asInt(DataSize::toBytes) - .when((size) -> size > 0).to(resolver::setResponseMaxChunkSizeBytes); + map.from(properties::getMediaTypes).whenNonNull().to(resolver::setSupportedMediaTypes); + map.from(properties::getMaxChunkSize).asInt(DataSize::toBytes).when((size) -> size > 0) + .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); - map.from(properties::getChunkedModeViewNames) - .to(resolver::setChunkedModeViewNames); + map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafProperties.java index 44952932e6e..a42430d0859 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -216,8 +216,7 @@ public class ThymeleafProperties { return this.renderHiddenMarkersBeforeCheckboxes; } - public void setRenderHiddenMarkersBeforeCheckboxes( - boolean renderHiddenMarkersBeforeCheckboxes) { + public void setRenderHiddenMarkersBeforeCheckboxes(boolean renderHiddenMarkersBeforeCheckboxes) { this.renderHiddenMarkersBeforeCheckboxes = renderHiddenMarkersBeforeCheckboxes; } @@ -254,8 +253,7 @@ public class ThymeleafProperties { return this.producePartialOutputWhileProcessing; } - public void setProducePartialOutputWhileProcessing( - boolean producePartialOutputWhileProcessing) { + public void setProducePartialOutputWhileProcessing(boolean producePartialOutputWhileProcessing) { this.producePartialOutputWhileProcessing = producePartialOutputWhileProcessing; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java index 1f7595e13e4..4c5a7267c2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,18 +29,14 @@ import org.springframework.util.ClassUtils; * @author Madhura Bhave * @since 1.1.0 */ -public class ThymeleafTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { +public class ThymeleafTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { - if (ClassUtils.isPresent("org.thymeleaf.spring5.SpringTemplateEngine", - classLoader)) { - String prefix = environment.getProperty("spring.thymeleaf.prefix", - ThymeleafProperties.DEFAULT_PREFIX); - String suffix = environment.getProperty("spring.thymeleaf.suffix", - ThymeleafProperties.DEFAULT_SUFFIX); + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { + if (ClassUtils.isPresent("org.thymeleaf.spring5.SpringTemplateEngine", classLoader)) { + String prefix = environment.getProperty("spring.thymeleaf.prefix", ThymeleafProperties.DEFAULT_PREFIX); + String suffix = environment.getProperty("spring.thymeleaf.suffix", ThymeleafProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } return false; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java index 2541ee0502e..12257d7f3e6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java @@ -47,8 +47,7 @@ import org.springframework.transaction.support.TransactionTemplate; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(PlatformTransactionManager.class) @AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - Neo4jDataAutoConfiguration.class }) + DataSourceTransactionManagerAutoConfiguration.class, Neo4jDataAutoConfiguration.class }) @EnableConfigurationProperties(TransactionProperties.class) public class TransactionAutoConfiguration { @@ -56,8 +55,7 @@ public class TransactionAutoConfiguration { @ConditionalOnMissingBean public TransactionManagerCustomizers platformTransactionManagerCustomizers( ObjectProvider> customizers) { - return new TransactionManagerCustomizers( - customizers.orderedStream().collect(Collectors.toList())); + return new TransactionManagerCustomizers(customizers.orderedStream().collect(Collectors.toList())); } @Configuration(proxyBeanMethods = false) @@ -66,8 +64,7 @@ public class TransactionAutoConfiguration { @Bean @ConditionalOnMissingBean - public TransactionTemplate transactionTemplate( - PlatformTransactionManager transactionManager) { + public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) { return new TransactionTemplate(transactionManager); } @@ -80,16 +77,16 @@ public class TransactionAutoConfiguration { @Configuration(proxyBeanMethods = false) @EnableTransactionManagement(proxyTargetClass = false) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "false", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", + matchIfMissing = false) public static class JdkDynamicAutoProxyConfiguration { } @Configuration(proxyBeanMethods = false) @EnableTransactionManagement(proxyTargetClass = true) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", + matchIfMissing = true) public static class CglibAutoProxyConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java index 89780ec78fd..4e9b8926743 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,17 +34,13 @@ public class TransactionManagerCustomizers { private final List> customizers; - public TransactionManagerCustomizers( - Collection> customizers) { - this.customizers = (customizers != null) ? new ArrayList<>(customizers) - : Collections.emptyList(); + public TransactionManagerCustomizers(Collection> customizers) { + this.customizers = (customizers != null) ? new ArrayList<>(customizers) : Collections.emptyList(); } @SuppressWarnings("unchecked") public void customize(PlatformTransactionManager transactionManager) { - LambdaSafe - .callbacks(PlatformTransactionManagerCustomizer.class, this.customizers, - transactionManager) + LambdaSafe.callbacks(PlatformTransactionManagerCustomizer.class, this.customizers, transactionManager) .withLogger(TransactionManagerCustomizers.class) .invoke((customizer) -> customizer.customize(transactionManager)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java index 3aae05da5b9..d48200a06f3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.transaction.support.AbstractPlatformTransactionManage * @since 1.5.0 */ @ConfigurationProperties(prefix = "spring.transaction") -public class TransactionProperties implements - PlatformTransactionManagerCustomizer { +public class TransactionProperties implements PlatformTransactionManagerCustomizer { /** * Default transaction timeout. If a duration suffix is not specified, seconds will be diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java index 75f1fe6fbc3..32b28cca277 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java @@ -63,15 +63,13 @@ class AtomikosJtaConfiguration { @Bean(initMethod = "init", destroyMethod = "shutdownWait") @ConditionalOnMissingBean(UserTransactionService.class) - public UserTransactionServiceImp userTransactionService( - AtomikosProperties atomikosProperties, JtaProperties jtaProperties) { + public UserTransactionServiceImp userTransactionService(AtomikosProperties atomikosProperties, + JtaProperties jtaProperties) { Properties properties = new Properties(); if (StringUtils.hasText(jtaProperties.getTransactionManagerId())) { - properties.setProperty("com.atomikos.icatch.tm_unique_name", - jtaProperties.getTransactionManagerId()); + properties.setProperty("com.atomikos.icatch.tm_unique_name", jtaProperties.getTransactionManagerId()); } - properties.setProperty("com.atomikos.icatch.log_base_dir", - getLogBaseDir(jtaProperties)); + properties.setProperty("com.atomikos.icatch.log_base_dir", getLogBaseDir(jtaProperties)); properties.putAll(atomikosProperties.asProperties()); return new UserTransactionServiceImp(properties); } @@ -86,8 +84,8 @@ class AtomikosJtaConfiguration { @Bean(initMethod = "init", destroyMethod = "close") @ConditionalOnMissingBean - public UserTransactionManager atomikosTransactionManager( - UserTransactionService userTransactionService) throws Exception { + public UserTransactionManager atomikosTransactionManager(UserTransactionService userTransactionService) + throws Exception { UserTransactionManager manager = new UserTransactionManager(); manager.setStartupTransactionService(false); manager.setForceShutdown(true); @@ -110,10 +108,8 @@ class AtomikosJtaConfiguration { public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager, ObjectProvider transactionManagerCustomizers) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - userTransaction, transactionManager); - transactionManagerCustomizers.ifAvailable( - (customizers) -> customizers.customize(jtaTransactionManager)); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, transactionManager); + transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(jtaTransactionManager)); return jtaTransactionManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java index 72a82ecd7bd..8ca08d5531a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java @@ -84,8 +84,7 @@ class BitronixJtaConfiguration { @Bean @ConditionalOnMissingBean(TransactionManager.class) - public BitronixTransactionManager bitronixTransactionManager( - bitronix.tm.Configuration configuration) { + public BitronixTransactionManager bitronixTransactionManager(bitronix.tm.Configuration configuration) { // Inject configuration to force ordering return TransactionManagerServices.getTransactionManager(); } @@ -106,10 +105,8 @@ class BitronixJtaConfiguration { public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager, ObjectProvider transactionManagerCustomizers) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - userTransaction, transactionManager); - transactionManagerCustomizers.ifAvailable( - (customizers) -> customizers.customize(jtaTransactionManager)); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, transactionManager); + transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(jtaTransactionManager)); return jtaTransactionManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java index c0fcce74bd9..d564f0193c1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java @@ -37,19 +37,16 @@ import org.springframework.transaction.jta.JtaTransactionManager; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(JtaTransactionManager.class) -@ConditionalOnJndi({ JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, - "java:comp/TransactionManager", "java:appserver/TransactionManager", - "java:pm/TransactionManager", "java:/TransactionManager" }) +@ConditionalOnJndi({ JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, "java:comp/TransactionManager", + "java:appserver/TransactionManager", "java:pm/TransactionManager", "java:/TransactionManager" }) @ConditionalOnMissingBean(PlatformTransactionManager.class) class JndiJtaConfiguration { @Bean public JtaTransactionManager transactionManager( ObjectProvider transactionManagerCustomizers) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean() - .getObject(); - transactionManagerCustomizers.ifAvailable( - (customizers) -> customizers.customize(jtaTransactionManager)); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean().getObject(); + transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(jtaTransactionManager)); return jtaTransactionManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java index 082c5655983..2fb24cec7c9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java @@ -38,11 +38,9 @@ import org.springframework.context.annotation.Import; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(javax.transaction.Transaction.class) @ConditionalOnProperty(prefix = "spring.jta", value = "enabled", matchIfMissing = true) -@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, - ActiveMQAutoConfiguration.class, ArtemisAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) -@Import({ JndiJtaConfiguration.class, BitronixJtaConfiguration.class, - AtomikosJtaConfiguration.class }) +@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, ActiveMQAutoConfiguration.class, + ArtemisAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) +@Import({ JndiJtaConfiguration.class, BitronixJtaConfiguration.class, AtomikosJtaConfiguration.class }) public class JtaAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java index 0132259524d..ff32b479ed1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; * * @author Stephane Nicoll */ -class PrimaryDefaultValidatorPostProcessor - implements ImportBeanDefinitionRegistrar, BeanFactoryAware { +class PrimaryDefaultValidatorPostProcessor implements ImportBeanDefinitionRegistrar, BeanFactoryAware { /** * The bean name of the auto-configured Validator. @@ -56,8 +55,7 @@ class PrimaryDefaultValidatorPostProcessor } @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { BeanDefinition definition = getAutoConfiguredValidator(registry); if (definition != null) { definition.setPrimary(!hasPrimarySpringValidator(registry)); @@ -67,8 +65,8 @@ class PrimaryDefaultValidatorPostProcessor private BeanDefinition getAutoConfiguredValidator(BeanDefinitionRegistry registry) { if (registry.containsBeanDefinition(VALIDATOR_BEAN_NAME)) { BeanDefinition definition = registry.getBeanDefinition(VALIDATOR_BEAN_NAME); - if (definition.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE && isTypeMatch( - VALIDATOR_BEAN_NAME, LocalValidatorFactoryBean.class)) { + if (definition.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE + && isTypeMatch(VALIDATOR_BEAN_NAME, LocalValidatorFactoryBean.class)) { return definition; } } @@ -80,8 +78,8 @@ class PrimaryDefaultValidatorPostProcessor } private boolean hasPrimarySpringValidator(BeanDefinitionRegistry registry) { - String[] validatorBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - this.beanFactory, Validator.class, false, false); + String[] validatorBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Validator.class, + false, false); for (String validatorBean : validatorBeans) { BeanDefinition definition = registry.getBeanDefinition(validatorBean); if (definition != null && definition.isPrimary()) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java index 96c10e06a68..57d48be9189 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java @@ -44,8 +44,7 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ExecutableValidator.class) -@ConditionalOnResource( - resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider") +@ConditionalOnResource(resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider") @Import(PrimaryDefaultValidatorPostProcessor.class) public class ValidationAutoConfiguration { @@ -61,11 +60,10 @@ public class ValidationAutoConfiguration { @Bean @ConditionalOnMissingBean - public static MethodValidationPostProcessor methodValidationPostProcessor( - Environment environment, @Lazy Validator validator) { + public static MethodValidationPostProcessor methodValidationPostProcessor(Environment environment, + @Lazy Validator validator) { MethodValidationPostProcessor processor = new MethodValidationPostProcessor(); - boolean proxyTargetClass = environment - .getProperty("spring.aop.proxy-target-class", Boolean.class, true); + boolean proxyTargetClass = environment.getProperty("spring.aop.proxy-target-class", Boolean.class, true); processor.setProxyTargetClass(proxyTargetClass); processor.setValidator(validator); return processor; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java index 7635912b064..b7fdd206c27 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java @@ -40,8 +40,7 @@ import org.springframework.validation.beanvalidation.SpringValidatorAdapter; * @author Phillip Webb * @since 2.0.0 */ -public class ValidatorAdapter implements SmartValidator, ApplicationContextAware, - InitializingBean, DisposableBean { +public class ValidatorAdapter implements SmartValidator, ApplicationContextAware, InitializingBean, DisposableBean { private final SmartValidator target; @@ -72,11 +71,9 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (!this.existingBean && this.target instanceof ApplicationContextAware) { - ((ApplicationContextAware) this.target) - .setApplicationContext(applicationContext); + ((ApplicationContextAware) this.target).setApplicationContext(applicationContext); } } @@ -105,8 +102,7 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware * @param validator an existing validator to use or {@code null} * @return the validator to use */ - public static Validator get(ApplicationContext applicationContext, - Validator validator) { + public static Validator get(ApplicationContext applicationContext, Validator validator) { if (validator != null) { return wrap(validator, false); } @@ -123,8 +119,7 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware private static Validator getExisting(ApplicationContext applicationContext) { try { - javax.validation.Validator validator = applicationContext - .getBean(javax.validation.Validator.class); + javax.validation.Validator validator = applicationContext.getBean(javax.validation.Validator.class); if (validator instanceof Validator) { return (Validator) validator; } @@ -150,11 +145,9 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware private static Validator wrap(Validator validator, boolean existingBean) { if (validator instanceof javax.validation.Validator) { if (validator instanceof SpringValidatorAdapter) { - return new ValidatorAdapter((SpringValidatorAdapter) validator, - existingBean); + return new ValidatorAdapter((SpringValidatorAdapter) validator, existingBean); } - return new ValidatorAdapter( - new SpringValidatorAdapter((javax.validation.Validator) validator), + return new ValidatorAdapter(new SpringValidatorAdapter((javax.validation.Validator) validator), existingBean); } return validator; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java index ca2442a8cc0..5c82245e76c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,23 +39,18 @@ class OnEnabledResourceChainCondition extends SpringBootCondition { private static final String WEBJAR_ASSET_LOCATOR = "org.webjars.WebJarAssetLocator"; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConfigurableEnvironment environment = (ConfigurableEnvironment) context - .getEnvironment(); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment(); boolean fixed = getEnabledProperty(environment, "strategy.fixed.", false); boolean content = getEnabledProperty(environment, "strategy.content.", false); Boolean chain = getEnabledProperty(environment, "", null); Boolean match = ResourceProperties.Chain.getEnabled(fixed, content, chain); - ConditionMessage.Builder message = ConditionMessage - .forCondition(ConditionalOnEnabledResourceChain.class); + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnEnabledResourceChain.class); if (match == null) { if (ClassUtils.isPresent(WEBJAR_ASSET_LOCATOR, getClass().getClassLoader())) { - return ConditionOutcome - .match(message.found("class").items(WEBJAR_ASSET_LOCATOR)); + return ConditionOutcome.match(message.found("class").items(WEBJAR_ASSET_LOCATOR)); } - return ConditionOutcome - .noMatch(message.didNotFind("class").items(WEBJAR_ASSET_LOCATOR)); + return ConditionOutcome.noMatch(message.didNotFind("class").items(WEBJAR_ASSET_LOCATOR)); } if (match) { return ConditionOutcome.match(message.because("enabled")); @@ -63,8 +58,7 @@ class OnEnabledResourceChainCondition extends SpringBootCondition { return ConditionOutcome.noMatch(message.because("disabled")); } - private Boolean getEnabledProperty(ConfigurableEnvironment environment, String key, - Boolean defaultValue) { + private Boolean getEnabledProperty(ConfigurableEnvironment environment, String key, Boolean defaultValue) { String name = "spring.resources.chain." + key + "enabled"; return environment.getProperty(name, Boolean.class, defaultValue); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java index 30ef43081bf..9b8ba0362bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java @@ -38,9 +38,8 @@ import org.springframework.http.CacheControl; @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties { - private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { - "classpath:/META-INF/resources/", "classpath:/resources/", - "classpath:/static/", "classpath:/public/" }; + private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", + "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; /** * Locations of static resources. Defaults to classpath:[/META-INF/resources/, @@ -126,8 +125,8 @@ public class ResourceProperties { * settings are present. */ public Boolean getEnabled() { - return getEnabled(getStrategy().getFixed().isEnabled(), - getStrategy().getContent().isEnabled(), this.enabled); + return getEnabled(getStrategy().getFixed().isEnabled(), getStrategy().getContent().isEnabled(), + this.enabled); } public void setEnabled(boolean enabled) { @@ -162,8 +161,7 @@ public class ResourceProperties { this.compressed = compressed; } - static Boolean getEnabled(boolean fixedEnabled, boolean contentEnabled, - Boolean chainEnabled) { + static Boolean getEnabled(boolean fixedEnabled, boolean contentEnabled, Boolean chainEnabled) { return (fixedEnabled || contentEnabled) ? Boolean.TRUE : chainEnabled; } @@ -462,20 +460,17 @@ public class ResourceProperties { public CacheControl toHttpCacheControl() { PropertyMapper map = PropertyMapper.get(); CacheControl control = createCacheControl(); - map.from(this::getMustRevalidate).whenTrue() - .toCall(control::mustRevalidate); + map.from(this::getMustRevalidate).whenTrue().toCall(control::mustRevalidate); map.from(this::getNoTransform).whenTrue().toCall(control::noTransform); map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic); map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate); - map.from(this::getProxyRevalidate).whenTrue() - .toCall(control::proxyRevalidate); - map.from(this::getStaleWhileRevalidate).whenNonNull().to( - (duration) -> control.staleWhileRevalidate(duration.getSeconds(), - TimeUnit.SECONDS)); - map.from(this::getStaleIfError).whenNonNull().to((duration) -> control - .staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); - map.from(this::getSMaxAge).whenNonNull().to((duration) -> control - .sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate); + map.from(this::getStaleWhileRevalidate).whenNonNull() + .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getStaleIfError).whenNonNull() + .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getSMaxAge).whenNonNull() + .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); // check if cacheControl remained untouched if (control.getHeaderValue() == null) { return null; @@ -491,8 +486,7 @@ public class ResourceProperties { return CacheControl.noCache(); } if (this.maxAge != null) { - return CacheControl.maxAge(this.maxAge.getSeconds(), - TimeUnit.SECONDS); + return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS); } return CacheControl.empty(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java index 6bcf4a6126a..3215b91e9a2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java @@ -140,8 +140,8 @@ public class ServerProperties { } public void setUseForwardHeaders(Boolean useForwardHeaders) { - this.forwardHeadersStrategy = Boolean.TRUE.equals(useForwardHeaders) - ? ForwardHeadersStrategy.NATIVE : ForwardHeadersStrategy.NONE; + this.forwardHeadersStrategy = Boolean.TRUE.equals(useForwardHeaders) ? ForwardHeadersStrategy.NATIVE + : ForwardHeadersStrategy.NONE; } public String getServerHeader() { @@ -294,8 +294,7 @@ public class ServerProperties { + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" // 169.254/16 + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" // 127/8 + "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" // 172.16/12 - + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" - + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + "0:0:0:0:0:0:0:1|::1"; /** diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java index 2cf03839698..a41463ad705 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java @@ -52,16 +52,14 @@ public class RestTemplateAutoConfiguration { @Bean @ConditionalOnMissingBean - public RestTemplateBuilder restTemplateBuilder( - ObjectProvider messageConverters, + public RestTemplateBuilder restTemplateBuilder(ObjectProvider messageConverters, ObjectProvider restTemplateCustomizers) { RestTemplateBuilder builder = new RestTemplateBuilder(); HttpMessageConverters converters = messageConverters.getIfUnique(); if (converters != null) { builder = builder.messageConverters(converters.getConverters()); } - List customizers = restTemplateCustomizers.orderedStream() - .collect(Collectors.toList()); + List customizers = restTemplateCustomizers.orderedStream().collect(Collectors.toList()); if (!customizers.isEmpty()) { builder = builder.customizers(customizers); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration.java index af74dafad4e..6f6c0f83db4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration.java @@ -54,8 +54,8 @@ public class EmbeddedWebServerFactoryCustomizerAutoConfiguration { public static class TomcatWebServerFactoryCustomizerConfiguration { @Bean - public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer( - Environment environment, ServerProperties serverProperties) { + public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer(Environment environment, + ServerProperties serverProperties) { return new TomcatWebServerFactoryCustomizer(environment, serverProperties); } @@ -69,8 +69,8 @@ public class EmbeddedWebServerFactoryCustomizerAutoConfiguration { public static class JettyWebServerFactoryCustomizerConfiguration { @Bean - public JettyWebServerFactoryCustomizer jettyWebServerFactoryCustomizer( - Environment environment, ServerProperties serverProperties) { + public JettyWebServerFactoryCustomizer jettyWebServerFactoryCustomizer(Environment environment, + ServerProperties serverProperties) { return new JettyWebServerFactoryCustomizer(environment, serverProperties); } @@ -84,8 +84,8 @@ public class EmbeddedWebServerFactoryCustomizerAutoConfiguration { public static class UndertowWebServerFactoryCustomizerConfiguration { @Bean - public UndertowWebServerFactoryCustomizer undertowWebServerFactoryCustomizer( - Environment environment, ServerProperties serverProperties) { + public UndertowWebServerFactoryCustomizer undertowWebServerFactoryCustomizer(Environment environment, + ServerProperties serverProperties) { return new UndertowWebServerFactoryCustomizer(environment, serverProperties); } @@ -99,8 +99,8 @@ public class EmbeddedWebServerFactoryCustomizerAutoConfiguration { public static class NettyWebServerFactoryCustomizerConfiguration { @Bean - public NettyWebServerFactoryCustomizer nettyWebServerFactoryCustomizer( - Environment environment, ServerProperties serverProperties) { + public NettyWebServerFactoryCustomizer nettyWebServerFactoryCustomizer(Environment environment, + ServerProperties serverProperties) { return new NettyWebServerFactoryCustomizer(environment, serverProperties); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java index e028de09809..9fd9dd0e92e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java @@ -48,15 +48,14 @@ import org.springframework.util.unit.DataSize; * @author Phillip Webb * @since 2.0.0 */ -public class JettyWebServerFactoryCustomizer implements - WebServerFactoryCustomizer, Ordered { +public class JettyWebServerFactoryCustomizer + implements WebServerFactoryCustomizer, Ordered { private final Environment environment; private final ServerProperties serverProperties; - public JettyWebServerFactoryCustomizer(Environment environment, - ServerProperties serverProperties) { + public JettyWebServerFactoryCustomizer(Environment environment, ServerProperties serverProperties) { this.environment = environment; this.serverProperties = serverProperties; } @@ -72,23 +71,16 @@ public class JettyWebServerFactoryCustomizer implements ServerProperties.Jetty jettyProperties = properties.getJetty(); factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders()); PropertyMapper propertyMapper = PropertyMapper.get(); - propertyMapper.from(jettyProperties::getAcceptors).whenNonNull() - .to(factory::setAcceptors); - propertyMapper.from(jettyProperties::getSelectors).whenNonNull() - .to(factory::setSelectors); - propertyMapper.from(properties::getMaxHttpHeaderSize).whenNonNull() - .asInt(DataSize::toBytes).when(this::isPositive) - .to((maxHttpHeaderSize) -> factory.addServerCustomizers( - new MaxHttpHeaderSizeCustomizer(maxHttpHeaderSize))); - propertyMapper.from(jettyProperties::getMaxHttpPostSize).asInt(DataSize::toBytes) - .when(this::isPositive) - .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, - maxHttpPostSize)); + propertyMapper.from(jettyProperties::getAcceptors).whenNonNull().to(factory::setAcceptors); + propertyMapper.from(jettyProperties::getSelectors).whenNonNull().to(factory::setSelectors); + propertyMapper.from(properties::getMaxHttpHeaderSize).whenNonNull().asInt(DataSize::toBytes) + .when(this::isPositive).to((maxHttpHeaderSize) -> factory + .addServerCustomizers(new MaxHttpHeaderSizeCustomizer(maxHttpHeaderSize))); + propertyMapper.from(jettyProperties::getMaxHttpPostSize).asInt(DataSize::toBytes).when(this::isPositive) + .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, maxHttpPostSize)); propertyMapper.from(properties::getConnectionTimeout).whenNonNull() - .to((connectionTimeout) -> customizeConnectionTimeout(factory, - connectionTimeout)); - propertyMapper.from(jettyProperties::getAccesslog) - .when(ServerProperties.Jetty.Accesslog::isEnabled) + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); + propertyMapper.from(jettyProperties::getAccesslog).when(ServerProperties.Jetty.Accesslog::isEnabled) .to((accesslog) -> customizeAccessLog(factory, accesslog)); } @@ -97,29 +89,24 @@ public class JettyWebServerFactoryCustomizer implements } private boolean getOrDeduceUseForwardHeaders() { - if (this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NONE)) { + if (this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NONE)) { CloudPlatform platform = CloudPlatform.getActive(this.environment); return platform != null && platform.isUsingForwardHeaders(); } - return this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NATIVE); + return this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NATIVE); } - private void customizeConnectionTimeout(ConfigurableJettyWebServerFactory factory, - Duration connectionTimeout) { + private void customizeConnectionTimeout(ConfigurableJettyWebServerFactory factory, Duration connectionTimeout) { factory.addServerCustomizers((server) -> { for (org.eclipse.jetty.server.Connector connector : server.getConnectors()) { if (connector instanceof AbstractConnector) { - ((AbstractConnector) connector) - .setIdleTimeout(connectionTimeout.toMillis()); + ((AbstractConnector) connector).setIdleTimeout(connectionTimeout.toMillis()); } } }); } - private void customizeMaxHttpPostSize(ConfigurableJettyWebServerFactory factory, - int maxHttpPostSize) { + private void customizeMaxHttpPostSize(ConfigurableJettyWebServerFactory factory, int maxHttpPostSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override @@ -127,19 +114,16 @@ public class JettyWebServerFactoryCustomizer implements setHandlerMaxHttpPostSize(maxHttpPostSize, server.getHandlers()); } - private void setHandlerMaxHttpPostSize(int maxHttpPostSize, - Handler... handlers) { + private void setHandlerMaxHttpPostSize(int maxHttpPostSize, Handler... handlers) { for (Handler handler : handlers) { if (handler instanceof ContextHandler) { ((ContextHandler) handler).setMaxFormContentSize(maxHttpPostSize); } else if (handler instanceof HandlerWrapper) { - setHandlerMaxHttpPostSize(maxHttpPostSize, - ((HandlerWrapper) handler).getHandler()); + setHandlerMaxHttpPostSize(maxHttpPostSize, ((HandlerWrapper) handler).getHandler()); } else if (handler instanceof HandlerCollection) { - setHandlerMaxHttpPostSize(maxHttpPostSize, - ((HandlerCollection) handler).getHandlers()); + setHandlerMaxHttpPostSize(maxHttpPostSize, ((HandlerCollection) handler).getHandlers()); } } } @@ -172,8 +156,7 @@ public class JettyWebServerFactoryCustomizer implements if (properties.getCustomFormat() != null) { return properties.getCustomFormat(); } - else if (ServerProperties.Jetty.Accesslog.FORMAT.EXTENDED_NCSA - .equals(properties.getFormat())) { + else if (ServerProperties.Jetty.Accesslog.FORMAT.EXTENDED_NCSA.equals(properties.getFormat())) { return CustomRequestLog.EXTENDED_NCSA_FORMAT; } return CustomRequestLog.NCSA_FORMAT; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java index a93ff797420..1b4a99a55fa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java @@ -45,8 +45,7 @@ public class NettyWebServerFactoryCustomizer private final ServerProperties serverProperties; - public NettyWebServerFactoryCustomizer(Environment environment, - ServerProperties serverProperties) { + public NettyWebServerFactoryCustomizer(Environment environment, ServerProperties serverProperties) { this.environment = environment; this.serverProperties = serverProperties; } @@ -60,35 +59,28 @@ public class NettyWebServerFactoryCustomizer public void customize(NettyReactiveWebServerFactory factory) { factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders()); PropertyMapper propertyMapper = PropertyMapper.get(); - propertyMapper.from(this.serverProperties::getMaxHttpHeaderSize).whenNonNull() - .asInt(DataSize::toBytes) - .to((maxHttpRequestHeaderSize) -> customizeMaxHttpHeaderSize(factory, - maxHttpRequestHeaderSize)); - propertyMapper.from(this.serverProperties::getConnectionTimeout).whenNonNull() - .asInt(Duration::toMillis).to((duration) -> factory - .addServerCustomizers(getConnectionTimeOutCustomizer(duration))); + propertyMapper.from(this.serverProperties::getMaxHttpHeaderSize).whenNonNull().asInt(DataSize::toBytes) + .to((maxHttpRequestHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpRequestHeaderSize)); + propertyMapper.from(this.serverProperties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) + .to((duration) -> factory.addServerCustomizers(getConnectionTimeOutCustomizer(duration))); } private boolean getOrDeduceUseForwardHeaders() { - if (this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NONE)) { + if (this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NONE)) { CloudPlatform platform = CloudPlatform.getActive(this.environment); return platform != null && platform.isUsingForwardHeaders(); } - return this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NATIVE); + return this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NATIVE); } - private void customizeMaxHttpHeaderSize(NettyReactiveWebServerFactory factory, - Integer maxHttpHeaderSize) { - factory.addServerCustomizers((NettyServerCustomizer) (httpServer) -> httpServer - .httpRequestDecoder((httpRequestDecoderSpec) -> httpRequestDecoderSpec - .maxHeaderSize(maxHttpHeaderSize))); + private void customizeMaxHttpHeaderSize(NettyReactiveWebServerFactory factory, Integer maxHttpHeaderSize) { + factory.addServerCustomizers((NettyServerCustomizer) (httpServer) -> httpServer.httpRequestDecoder( + (httpRequestDecoderSpec) -> httpRequestDecoderSpec.maxHeaderSize(maxHttpHeaderSize))); } private NettyServerCustomizer getConnectionTimeOutCustomizer(int duration) { - return (httpServer) -> httpServer.tcpConfiguration((tcpServer) -> tcpServer - .selectorOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, duration)); + return (httpServer) -> httpServer.tcpConfiguration( + (tcpServer) -> tcpServer.selectorOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, duration)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java index 0eb58a78646..7fca30d3417 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java @@ -53,15 +53,14 @@ import org.springframework.util.unit.DataSize; * @author Andrew McGhie * @since 2.0.0 */ -public class TomcatWebServerFactoryCustomizer implements - WebServerFactoryCustomizer, Ordered { +public class TomcatWebServerFactoryCustomizer + implements WebServerFactoryCustomizer, Ordered { private final Environment environment; private final ServerProperties serverProperties; - public TomcatWebServerFactoryCustomizer(Environment environment, - ServerProperties serverProperties) { + public TomcatWebServerFactoryCustomizer(Environment environment, ServerProperties serverProperties) { this.environment = environment; this.serverProperties = serverProperties; } @@ -76,36 +75,27 @@ public class TomcatWebServerFactoryCustomizer implements ServerProperties properties = this.serverProperties; ServerProperties.Tomcat tomcatProperties = properties.getTomcat(); PropertyMapper propertyMapper = PropertyMapper.get(); - propertyMapper.from(tomcatProperties::getBasedir).whenNonNull() - .to(factory::setBaseDirectory); - propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay).whenNonNull() - .as(Duration::getSeconds).as(Long::intValue) - .to(factory::setBackgroundProcessorDelay); + propertyMapper.from(tomcatProperties::getBasedir).whenNonNull().to(factory::setBaseDirectory); + propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay).whenNonNull().as(Duration::getSeconds) + .as(Long::intValue).to(factory::setBackgroundProcessorDelay); customizeRemoteIpValve(factory); propertyMapper.from(tomcatProperties::getMaxThreads).when(this::isPositive) - .to((maxThreads) -> customizeMaxThreads(factory, - tomcatProperties.getMaxThreads())); + .to((maxThreads) -> customizeMaxThreads(factory, tomcatProperties.getMaxThreads())); propertyMapper.from(tomcatProperties::getMinSpareThreads).when(this::isPositive) .to((minSpareThreads) -> customizeMinThreads(factory, minSpareThreads)); - propertyMapper.from(this.serverProperties.getMaxHttpHeaderSize()).whenNonNull() - .asInt(DataSize::toBytes).when(this::isPositive) - .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, - maxHttpHeaderSize)); - propertyMapper.from(tomcatProperties::getMaxSwallowSize).whenNonNull() - .asInt(DataSize::toBytes) + propertyMapper.from(this.serverProperties.getMaxHttpHeaderSize()).whenNonNull().asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize)); + propertyMapper.from(tomcatProperties::getMaxSwallowSize).whenNonNull().asInt(DataSize::toBytes) .to((maxSwallowSize) -> customizeMaxSwallowSize(factory, maxSwallowSize)); propertyMapper.from(tomcatProperties::getMaxHttpPostSize).asInt(DataSize::toBytes) .when((maxHttpPostSize) -> maxHttpPostSize != 0) - .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, - maxHttpPostSize)); - propertyMapper.from(tomcatProperties::getAccesslog) - .when(ServerProperties.Tomcat.Accesslog::isEnabled) + .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, maxHttpPostSize)); + propertyMapper.from(tomcatProperties::getAccesslog).when(ServerProperties.Tomcat.Accesslog::isEnabled) .to((enabled) -> customizeAccessLog(factory)); - propertyMapper.from(tomcatProperties::getUriEncoding).whenNonNull() - .to(factory::setUriEncoding); + propertyMapper.from(tomcatProperties::getUriEncoding).whenNonNull().to(factory::setUriEncoding); propertyMapper.from(properties::getConnectionTimeout).whenNonNull() - .to((connectionTimeout) -> customizeConnectionTimeout(factory, - connectionTimeout)); + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); propertyMapper.from(tomcatProperties::getMaxConnections).when(this::isPositive) .to((maxConnections) -> customizeMaxConnections(factory, maxConnections)); propertyMapper.from(tomcatProperties::getAcceptCount).when(this::isPositive) @@ -120,8 +110,7 @@ public class TomcatWebServerFactoryCustomizer implements return value > 0; } - private void customizeAcceptCount(ConfigurableTomcatWebServerFactory factory, - int acceptCount) { + private void customizeAcceptCount(ConfigurableTomcatWebServerFactory factory, int acceptCount) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { @@ -131,8 +120,7 @@ public class TomcatWebServerFactoryCustomizer implements }); } - private void customizeProcessorCache(ConfigurableTomcatWebServerFactory factory, - int processorCache) { + private void customizeProcessorCache(ConfigurableTomcatWebServerFactory factory, int processorCache) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { @@ -141,8 +129,7 @@ public class TomcatWebServerFactoryCustomizer implements }); } - private void customizeMaxConnections(ConfigurableTomcatWebServerFactory factory, - int maxConnections) { + private void customizeMaxConnections(ConfigurableTomcatWebServerFactory factory, int maxConnections) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { @@ -152,8 +139,7 @@ public class TomcatWebServerFactoryCustomizer implements }); } - private void customizeConnectionTimeout(ConfigurableTomcatWebServerFactory factory, - Duration connectionTimeout) { + private void customizeConnectionTimeout(ConfigurableTomcatWebServerFactory factory, Duration connectionTimeout) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { @@ -171,8 +157,7 @@ public class TomcatWebServerFactoryCustomizer implements if (StringUtils.hasText(protocolHeader) || StringUtils.hasText(remoteIpHeader) || getOrDeduceUseForwardHeaders()) { RemoteIpValve valve = new RemoteIpValve(); - valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) ? protocolHeader - : "X-Forwarded-Proto"); + valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) ? protocolHeader : "X-Forwarded-Proto"); if (StringUtils.hasLength(remoteIpHeader)) { valve.setRemoteIpHeader(remoteIpHeader); } @@ -180,26 +165,22 @@ public class TomcatWebServerFactoryCustomizer implements // addresses valve.setInternalProxies(tomcatProperties.getInternalProxies()); valve.setPortHeader(tomcatProperties.getPortHeader()); - valve.setProtocolHeaderHttpsValue( - tomcatProperties.getProtocolHeaderHttpsValue()); + valve.setProtocolHeaderHttpsValue(tomcatProperties.getProtocolHeaderHttpsValue()); // ... so it's safe to add this valve by default. factory.addEngineValves(valve); } } private boolean getOrDeduceUseForwardHeaders() { - if (this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NONE)) { + if (this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NONE)) { CloudPlatform platform = CloudPlatform.getActive(this.environment); return platform != null && platform.isUsingForwardHeaders(); } - return this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NATIVE); + return this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NATIVE); } @SuppressWarnings("rawtypes") - private void customizeMaxThreads(ConfigurableTomcatWebServerFactory factory, - int maxThreads) { + private void customizeMaxThreads(ConfigurableTomcatWebServerFactory factory, int maxThreads) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { @@ -210,8 +191,7 @@ public class TomcatWebServerFactoryCustomizer implements } @SuppressWarnings("rawtypes") - private void customizeMinThreads(ConfigurableTomcatWebServerFactory factory, - int minSpareThreads) { + private void customizeMinThreads(ConfigurableTomcatWebServerFactory factory, int minSpareThreads) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { @@ -222,8 +202,7 @@ public class TomcatWebServerFactoryCustomizer implements } @SuppressWarnings("rawtypes") - private void customizeMaxHttpHeaderSize(ConfigurableTomcatWebServerFactory factory, - int maxHttpHeaderSize) { + private void customizeMaxHttpHeaderSize(ConfigurableTomcatWebServerFactory factory, int maxHttpHeaderSize) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractHttp11Protocol) { @@ -233,8 +212,7 @@ public class TomcatWebServerFactoryCustomizer implements }); } - private void customizeMaxSwallowSize(ConfigurableTomcatWebServerFactory factory, - int maxSwallowSize) { + private void customizeMaxSwallowSize(ConfigurableTomcatWebServerFactory factory, int maxSwallowSize) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractHttp11Protocol) { @@ -244,10 +222,8 @@ public class TomcatWebServerFactoryCustomizer implements }); } - private void customizeMaxHttpPostSize(ConfigurableTomcatWebServerFactory factory, - int maxHttpPostSize) { - factory.addConnectorCustomizers( - (connector) -> connector.setMaxPostSize(maxHttpPostSize)); + private void customizeMaxHttpPostSize(ConfigurableTomcatWebServerFactory factory, int maxHttpPostSize) { + factory.addConnectorCustomizers((connector) -> connector.setMaxPostSize(maxHttpPostSize)); } private void customizeAccessLog(ConfigurableTomcatWebServerFactory factory) { @@ -269,15 +245,13 @@ public class TomcatWebServerFactoryCustomizer implements map.from(accessLogConfig.getMaxDays()).to(valve::setMaxDays); map.from(accessLogConfig.getFileDateFormat()).to(valve::setFileDateFormat); map.from(accessLogConfig.isIpv6Canonical()).to(valve::setIpv6Canonical); - map.from(accessLogConfig.isRequestAttributesEnabled()) - .to(valve::setRequestAttributesEnabled); + map.from(accessLogConfig.isRequestAttributesEnabled()).to(valve::setRequestAttributesEnabled); map.from(accessLogConfig.isBuffered()).to(valve::setBuffered); factory.addEngineValves(valve); } private void customizeStaticResources(ConfigurableTomcatWebServerFactory factory) { - ServerProperties.Tomcat.Resource resource = this.serverProperties.getTomcat() - .getResource(); + ServerProperties.Tomcat.Resource resource = this.serverProperties.getTomcat().getResource(); factory.addContextCustomizers((context) -> { context.addLifecycleListener((event) -> { if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { @@ -291,8 +265,7 @@ public class TomcatWebServerFactoryCustomizer implements }); } - private void customizeErrorReportValve(ErrorProperties error, - ConfigurableTomcatWebServerFactory factory) { + private void customizeErrorReportValve(ErrorProperties error, ConfigurableTomcatWebServerFactory factory) { if (error.getIncludeStacktrace() == IncludeStacktrace.NEVER) { factory.addContextCustomizers((context) -> { ErrorReportValve valve = new ErrorReportValve(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java index 5cadb2fb058..0024b80cfc4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java @@ -40,15 +40,14 @@ import org.springframework.util.unit.DataSize; * @author Rafiullah Hamedy * @since 2.0.0 */ -public class UndertowWebServerFactoryCustomizer implements - WebServerFactoryCustomizer, Ordered { +public class UndertowWebServerFactoryCustomizer + implements WebServerFactoryCustomizer, Ordered { private final Environment environment; private final ServerProperties serverProperties; - public UndertowWebServerFactoryCustomizer(Environment environment, - ServerProperties serverProperties) { + public UndertowWebServerFactoryCustomizer(Environment environment, ServerProperties serverProperties) { this.environment = environment; this.serverProperties = serverProperties; } @@ -62,96 +61,72 @@ public class UndertowWebServerFactoryCustomizer implements public void customize(ConfigurableUndertowWebServerFactory factory) { ServerProperties properties = this.serverProperties; ServerProperties.Undertow undertowProperties = properties.getUndertow(); - ServerProperties.Undertow.Accesslog accesslogProperties = undertowProperties - .getAccesslog(); + ServerProperties.Undertow.Accesslog accesslogProperties = undertowProperties.getAccesslog(); PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); - propertyMapper.from(undertowProperties::getBufferSize).whenNonNull() - .asInt(DataSize::toBytes).to(factory::setBufferSize); + propertyMapper.from(undertowProperties::getBufferSize).whenNonNull().asInt(DataSize::toBytes) + .to(factory::setBufferSize); propertyMapper.from(undertowProperties::getIoThreads).to(factory::setIoThreads); - propertyMapper.from(undertowProperties::getWorkerThreads) - .to(factory::setWorkerThreads); - propertyMapper.from(undertowProperties::getDirectBuffers) - .to(factory::setUseDirectBuffers); - propertyMapper.from(accesslogProperties::isEnabled) - .to(factory::setAccessLogEnabled); - propertyMapper.from(accesslogProperties::getDir) - .to(factory::setAccessLogDirectory); - propertyMapper.from(accesslogProperties::getPattern) - .to(factory::setAccessLogPattern); - propertyMapper.from(accesslogProperties::getPrefix) - .to(factory::setAccessLogPrefix); - propertyMapper.from(accesslogProperties::getSuffix) - .to(factory::setAccessLogSuffix); - propertyMapper.from(accesslogProperties::isRotate) - .to(factory::setAccessLogRotate); - propertyMapper.from(this::getOrDeduceUseForwardHeaders) - .to(factory::setUseForwardHeaders); + propertyMapper.from(undertowProperties::getWorkerThreads).to(factory::setWorkerThreads); + propertyMapper.from(undertowProperties::getDirectBuffers).to(factory::setUseDirectBuffers); + propertyMapper.from(accesslogProperties::isEnabled).to(factory::setAccessLogEnabled); + propertyMapper.from(accesslogProperties::getDir).to(factory::setAccessLogDirectory); + propertyMapper.from(accesslogProperties::getPattern).to(factory::setAccessLogPattern); + propertyMapper.from(accesslogProperties::getPrefix).to(factory::setAccessLogPrefix); + propertyMapper.from(accesslogProperties::getSuffix).to(factory::setAccessLogSuffix); + propertyMapper.from(accesslogProperties::isRotate).to(factory::setAccessLogRotate); + propertyMapper.from(this::getOrDeduceUseForwardHeaders).to(factory::setUseForwardHeaders); - propertyMapper.from(properties::getMaxHttpHeaderSize).whenNonNull() - .asInt(DataSize::toBytes).when(this::isPositive) - .to((maxHttpHeaderSize) -> customizeServerOption(factory, + propertyMapper.from(properties::getMaxHttpHeaderSize).whenNonNull().asInt(DataSize::toBytes) + .when(this::isPositive).to((maxHttpHeaderSize) -> customizeServerOption(factory, UndertowOptions.MAX_HEADER_SIZE, maxHttpHeaderSize)); - propertyMapper.from(undertowProperties::getMaxHttpPostSize).as(DataSize::toBytes) - .when(this::isPositive) - .to((maxHttpPostSize) -> customizeServerOption(factory, - UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize)); + propertyMapper.from(undertowProperties::getMaxHttpPostSize).as(DataSize::toBytes).when(this::isPositive).to( + (maxHttpPostSize) -> customizeServerOption(factory, UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize)); - propertyMapper.from(properties::getConnectionTimeout) - .to((connectionTimeout) -> customizeServerOption(factory, - UndertowOptions.NO_REQUEST_TIMEOUT, - (int) connectionTimeout.toMillis())); + propertyMapper.from(properties::getConnectionTimeout).to((connectionTimeout) -> customizeServerOption(factory, + UndertowOptions.NO_REQUEST_TIMEOUT, (int) connectionTimeout.toMillis())); propertyMapper.from(undertowProperties::getMaxParameters) - .to((maxParameters) -> customizeServerOption(factory, - UndertowOptions.MAX_PARAMETERS, maxParameters)); + .to((maxParameters) -> customizeServerOption(factory, UndertowOptions.MAX_PARAMETERS, maxParameters)); propertyMapper.from(undertowProperties::getMaxHeaders) - .to((maxHeaders) -> customizeServerOption(factory, - UndertowOptions.MAX_HEADERS, maxHeaders)); + .to((maxHeaders) -> customizeServerOption(factory, UndertowOptions.MAX_HEADERS, maxHeaders)); propertyMapper.from(undertowProperties::getMaxCookies) - .to((maxCookies) -> customizeServerOption(factory, - UndertowOptions.MAX_COOKIES, maxCookies)); + .to((maxCookies) -> customizeServerOption(factory, UndertowOptions.MAX_COOKIES, maxCookies)); propertyMapper.from(undertowProperties::isAllowEncodedSlash) - .to((allowEncodedSlash) -> customizeServerOption(factory, - UndertowOptions.ALLOW_ENCODED_SLASH, allowEncodedSlash)); + .to((allowEncodedSlash) -> customizeServerOption(factory, UndertowOptions.ALLOW_ENCODED_SLASH, + allowEncodedSlash)); propertyMapper.from(undertowProperties::isDecodeUrl) - .to((isDecodeUrl) -> customizeServerOption(factory, - UndertowOptions.DECODE_URL, isDecodeUrl)); + .to((isDecodeUrl) -> customizeServerOption(factory, UndertowOptions.DECODE_URL, isDecodeUrl)); propertyMapper.from(undertowProperties::getUrlCharset) - .to((urlCharset) -> customizeServerOption(factory, - UndertowOptions.URL_CHARSET, urlCharset.name())); + .to((urlCharset) -> customizeServerOption(factory, UndertowOptions.URL_CHARSET, urlCharset.name())); propertyMapper.from(undertowProperties::isAlwaysSetKeepAlive) - .to((alwaysSetKeepAlive) -> customizeServerOption(factory, - UndertowOptions.ALWAYS_SET_KEEP_ALIVE, alwaysSetKeepAlive)); + .to((alwaysSetKeepAlive) -> customizeServerOption(factory, UndertowOptions.ALWAYS_SET_KEEP_ALIVE, + alwaysSetKeepAlive)); - factory.addDeploymentInfoCustomizers((deploymentInfo) -> deploymentInfo - .setEagerFilterInit(undertowProperties.isEagerFilterInit())); + factory.addDeploymentInfoCustomizers( + (deploymentInfo) -> deploymentInfo.setEagerFilterInit(undertowProperties.isEagerFilterInit())); } private boolean isPositive(Number value) { return value.longValue() > 0; } - private void customizeServerOption(ConfigurableUndertowWebServerFactory factory, - Option option, T value) { - factory.addBuilderCustomizers( - (builder) -> builder.setServerOption(option, value)); + private void customizeServerOption(ConfigurableUndertowWebServerFactory factory, Option option, T value) { + factory.addBuilderCustomizers((builder) -> builder.setServerOption(option, value)); } private boolean getOrDeduceUseForwardHeaders() { - if (this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NONE)) { + if (this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NONE)) { CloudPlatform platform = CloudPlatform.getActive(this.environment); return platform != null && platform.isUsingForwardHeaders(); } - return this.serverProperties.getForwardHeadersStrategy() - .equals(ServerProperties.ForwardHeadersStrategy.NATIVE); + return this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NATIVE); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/format/WebConversionService.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/format/WebConversionService.java index d88de8783aa..39a82c225bd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/format/WebConversionService.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/format/WebConversionService.java @@ -46,11 +46,11 @@ import org.springframework.util.StringUtils; */ public class WebConversionService extends DefaultFormattingConversionService { - private static final boolean JSR_354_PRESENT = ClassUtils.isPresent( - "javax.money.MonetaryAmount", WebConversionService.class.getClassLoader()); + private static final boolean JSR_354_PRESENT = ClassUtils.isPresent("javax.money.MonetaryAmount", + WebConversionService.class.getClassLoader()); - private static final boolean JODA_TIME_PRESENT = ClassUtils.isPresent( - "org.joda.time.LocalDate", WebConversionService.class.getClassLoader()); + private static final boolean JODA_TIME_PRESENT = ClassUtils.isPresent("org.joda.time.LocalDate", + WebConversionService.class.getClassLoader()); private final String dateFormat; @@ -75,8 +75,7 @@ public class WebConversionService extends DefaultFormattingConversionService { if (JSR_354_PRESENT) { addFormatter(new CurrencyUnitFormatter()); addFormatter(new MonetaryAmountFormatter()); - addFormatterForFieldAnnotation( - new Jsr354NumberFormatAnnotationFormatterFactory()); + addFormatterForFieldAnnotation(new Jsr354NumberFormatAnnotationFormatterFactory()); } registerJsr310(); if (JODA_TIME_PRESENT) { @@ -88,8 +87,8 @@ public class WebConversionService extends DefaultFormattingConversionService { private void registerJsr310() { DateTimeFormatterRegistrar dateTime = new DateTimeFormatterRegistrar(); if (this.dateFormat != null) { - dateTime.setDateFormatter(DateTimeFormatter.ofPattern(this.dateFormat) - .withResolverStyle(ResolverStyle.SMART)); + dateTime.setDateFormatter( + DateTimeFormatter.ofPattern(this.dateFormat).withResolverStyle(ResolverStyle.SMART)); } dateTime.registerFormatters(this); } @@ -97,8 +96,7 @@ public class WebConversionService extends DefaultFormattingConversionService { private void registerJodaTime() { JodaTimeFormatterRegistrar jodaTime = new JodaTimeFormatterRegistrar(); if (this.dateFormat != null) { - jodaTime.setDateFormatter(new DateTimeFormatterBuilder() - .appendPattern(this.dateFormat).toFormatter()); + jodaTime.setDateFormatter(new DateTimeFormatterBuilder().appendPattern(this.dateFormat).toFormatter()); } jodaTime.registerFormatters(this); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfiguration.java index 617b7e3b526..3004fdb91f4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfiguration.java @@ -56,8 +56,7 @@ public class HttpHandlerAutoConfiguration { @Bean public HttpHandler httpHandler() { - return WebHttpHandlerBuilder.applicationContext(this.applicationContext) - .build(); + return WebHttpHandlerBuilder.applicationContext(this.applicationContext).build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java index 3845591ef03..5eeedff51ed 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java @@ -60,8 +60,7 @@ import org.springframework.web.server.adapter.ForwardedHeaderTransformer; public class ReactiveWebServerFactoryAutoConfiguration { @Bean - public ReactiveWebServerFactoryCustomizer reactiveWebServerFactoryCustomizer( - ServerProperties serverProperties) { + public ReactiveWebServerFactoryCustomizer reactiveWebServerFactoryCustomizer(ServerProperties serverProperties) { return new ReactiveWebServerFactoryCustomizer(serverProperties); } @@ -74,8 +73,7 @@ public class ReactiveWebServerFactoryAutoConfiguration { @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(value = "server.forward-headers-strategy", - havingValue = "framework") + @ConditionalOnProperty(value = "server.forward-headers-strategy", havingValue = "framework") public ForwardedHeaderTransformer forwardedHeaderTransformer() { return new ForwardedHeaderTransformer(); } @@ -84,8 +82,7 @@ public class ReactiveWebServerFactoryAutoConfiguration { * Registers a {@link WebServerFactoryCustomizerBeanPostProcessor}. Registered via * {@link ImportBeanDefinitionRegistrar} for early registration. */ - public static class BeanPostProcessorsRegistrar - implements ImportBeanDefinitionRegistrar, BeanFactoryAware { + public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @@ -102,15 +99,12 @@ public class ReactiveWebServerFactoryAutoConfiguration { if (this.beanFactory == null) { return; } - registerSyntheticBeanIfMissing(registry, - "webServerFactoryCustomizerBeanPostProcessor", + registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class); } - private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, - String name, Class beanClass) { - if (ObjectUtils.isEmpty( - this.beanFactory.getBeanNamesForType(beanClass, true, false))) { + private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class beanClass) { + if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java index d696d52a94d..4291faec91d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java @@ -65,13 +65,11 @@ abstract class ReactiveWebServerFactoryConfiguration { } @Bean - public NettyReactiveWebServerFactory nettyReactiveWebServerFactory( - ReactorResourceFactory resourceFactory, + public NettyReactiveWebServerFactory nettyReactiveWebServerFactory(ReactorResourceFactory resourceFactory, ObjectProvider routes) { NettyReactiveWebServerFactory serverFactory = new NettyReactiveWebServerFactory(); serverFactory.setResourceFactory(resourceFactory); - routes.orderedStream() - .forEach((route) -> serverFactory.addRouteProviders(route)); + routes.orderedStream().forEach((route) -> serverFactory.addRouteProviders(route)); return serverFactory; } @@ -88,13 +86,12 @@ abstract class ReactiveWebServerFactoryConfiguration { ObjectProvider contextCustomizers, ObjectProvider> protocolHandlerCustomizers) { TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(); - factory.getTomcatConnectorCustomizers().addAll( - connectorCustomizers.orderedStream().collect(Collectors.toList())); - factory.getTomcatContextCustomizers().addAll( - contextCustomizers.orderedStream().collect(Collectors.toList())); + factory.getTomcatConnectorCustomizers() + .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList())); + factory.getTomcatContextCustomizers() + .addAll(contextCustomizers.orderedStream().collect(Collectors.toList())); factory.getTomcatProtocolHandlerCustomizers() - .addAll(protocolHandlerCustomizers.orderedStream() - .collect(Collectors.toList())); + .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList())); return factory; } @@ -112,12 +109,10 @@ abstract class ReactiveWebServerFactoryConfiguration { } @Bean - public JettyReactiveWebServerFactory jettyReactiveWebServerFactory( - JettyResourceFactory resourceFactory, + public JettyReactiveWebServerFactory jettyReactiveWebServerFactory(JettyResourceFactory resourceFactory, ObjectProvider serverCustomizers) { JettyReactiveWebServerFactory serverFactory = new JettyReactiveWebServerFactory(); - serverFactory.getServerCustomizers().addAll( - serverCustomizers.orderedStream().collect(Collectors.toList())); + serverFactory.getServerCustomizers().addAll(serverCustomizers.orderedStream().collect(Collectors.toList())); serverFactory.setResourceFactory(resourceFactory); return serverFactory; } @@ -134,10 +129,9 @@ abstract class ReactiveWebServerFactoryConfiguration { ObjectProvider deploymentInfoCustomizers, ObjectProvider builderCustomizers) { UndertowReactiveWebServerFactory factory = new UndertowReactiveWebServerFactory(); - factory.getDeploymentInfoCustomizers().addAll(deploymentInfoCustomizers - .orderedStream().collect(Collectors.toList())); - factory.getBuilderCustomizers().addAll( - builderCustomizers.orderedStream().collect(Collectors.toList())); + factory.getDeploymentInfoCustomizers() + .addAll(deploymentInfoCustomizers.orderedStream().collect(Collectors.toList())); + factory.getBuilderCustomizers().addAll(builderCustomizers.orderedStream().collect(Collectors.toList())); return factory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizer.java index 814175a5cae..c597ce099e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,8 @@ import org.springframework.core.Ordered; * @author Yunkun Huang * @since 2.0.0 */ -public class ReactiveWebServerFactoryCustomizer implements - WebServerFactoryCustomizer, Ordered { +public class ReactiveWebServerFactoryCustomizer + implements WebServerFactoryCustomizer, Ordered { private final ServerProperties serverProperties; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ResourceChainResourceHandlerRegistrationCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ResourceChainResourceHandlerRegistrationCustomizer.java index 62f0e44bc3b..35cb76c9576 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ResourceChainResourceHandlerRegistrationCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ResourceChainResourceHandlerRegistrationCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.web.reactive.resource.VersionResourceResolver; * * @author Brian Clozel */ -class ResourceChainResourceHandlerRegistrationCustomizer - implements ResourceHandlerRegistrationCustomizer { +class ResourceChainResourceHandlerRegistrationCustomizer implements ResourceHandlerRegistrationCustomizer { @Autowired private ResourceProperties resourceProperties = new ResourceProperties(); @@ -40,12 +39,10 @@ class ResourceChainResourceHandlerRegistrationCustomizer @Override public void customize(ResourceHandlerRegistration registration) { ResourceProperties.Chain properties = this.resourceProperties.getChain(); - configureResourceChain(properties, - registration.resourceChain(properties.isCache())); + configureResourceChain(properties, registration.resourceChain(properties.isCache())); } - private void configureResourceChain(ResourceProperties.Chain properties, - ResourceChainRegistration chain) { + private void configureResourceChain(ResourceProperties.Chain properties, ResourceChainRegistration chain) { ResourceProperties.Strategy strategy = properties.getStrategy(); if (properties.isCompressed()) { chain.addResolver(new EncodedResourceResolver()); @@ -58,8 +55,7 @@ class ResourceChainResourceHandlerRegistrationCustomizer } } - private ResourceResolver getVersionResourceResolver( - ResourceProperties.Strategy properties) { + private ResourceResolver getVersionResourceResolver(ResourceProperties.Strategy properties) { VersionResourceResolver resolver = new VersionResourceResolver(); if (properties.getFixed().isEnabled()) { String version = properties.getFixed().getVersion(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/TomcatReactiveWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/TomcatReactiveWebServerFactoryCustomizer.java index e78ded87178..5e5ca0c8546 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/TomcatReactiveWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/TomcatReactiveWebServerFactoryCustomizer.java @@ -38,8 +38,7 @@ public class TomcatReactiveWebServerFactoryCustomizer @Override public void customize(TomcatReactiveWebServerFactory factory) { - factory.setDisableMBeanRegistry( - !this.serverProperties.getTomcat().getMbeanregistry().isEnabled()); + factory.setDisableMBeanRegistry(!this.serverProperties.getTomcat().getMbeanregistry().isEnabled()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java index b80e28fbe42..920a62f16a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java @@ -82,15 +82,14 @@ import org.springframework.web.reactive.result.view.ViewResolver; @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnClass(WebFluxConfigurer.class) @ConditionalOnMissingBean({ WebFluxConfigurationSupport.class }) -@AutoConfigureAfter({ ReactiveWebServerFactoryAutoConfiguration.class, - CodecsAutoConfiguration.class, ValidationAutoConfiguration.class }) +@AutoConfigureAfter({ ReactiveWebServerFactoryAutoConfiguration.class, CodecsAutoConfiguration.class, + ValidationAutoConfiguration.class }) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) public class WebFluxAutoConfiguration { @Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) - @ConditionalOnProperty(prefix = "spring.webflux.hiddenmethod.filter", - name = "enabled", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.webflux.hiddenmethod.filter", name = "enabled", matchIfMissing = true) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { return new OrderedHiddenHttpMethodFilter(); } @@ -116,9 +115,8 @@ public class WebFluxAutoConfiguration { private final ObjectProvider viewResolvers; - public WebFluxConfig(ResourceProperties resourceProperties, - WebFluxProperties webFluxProperties, ListableBeanFactory beanFactory, - ObjectProvider resolvers, + public WebFluxConfig(ResourceProperties resourceProperties, WebFluxProperties webFluxProperties, + ListableBeanFactory beanFactory, ObjectProvider resolvers, ObjectProvider codecCustomizers, ObjectProvider resourceHandlerRegistrationCustomizer, ObjectProvider viewResolvers) { @@ -127,8 +125,7 @@ public class WebFluxAutoConfiguration { this.beanFactory = beanFactory; this.argumentResolvers = resolvers; this.codecCustomizers = codecCustomizers; - this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer - .getIfAvailable(); + this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer.getIfAvailable(); this.viewResolvers = viewResolvers; } @@ -139,8 +136,7 @@ public class WebFluxAutoConfiguration { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { - this.codecCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(configurer)); + this.codecCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configurer)); } @Override @@ -150,17 +146,15 @@ public class WebFluxAutoConfiguration { return; } if (!registry.hasMappingForPattern("/webjars/**")) { - ResourceHandlerRegistration registration = registry - .addResourceHandler("/webjars/**") + ResourceHandlerRegistration registration = registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); configureResourceCaching(registration); customizeResourceHandlerRegistration(registration); } String staticPathPattern = this.webFluxProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { - ResourceHandlerRegistration registration = registry - .addResourceHandler(staticPathPattern).addResourceLocations( - this.resourceProperties.getStaticLocations()); + ResourceHandlerRegistration registration = registry.addResourceHandler(staticPathPattern) + .addResourceLocations(this.resourceProperties.getStaticLocations()); configureResourceCaching(registration); customizeResourceHandlerRegistration(registration); } @@ -168,8 +162,7 @@ public class WebFluxAutoConfiguration { private void configureResourceCaching(ResourceHandlerRegistration registration) { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); - ResourceProperties.Cache.Cachecontrol cacheControl = this.resourceProperties - .getCache().getCachecontrol(); + ResourceProperties.Cache.Cachecontrol cacheControl = this.resourceProperties.getCache().getCachecontrol(); if (cachePeriod != null && cacheControl.getMaxAge() == null) { cacheControl.setMaxAge(cachePeriod); } @@ -198,8 +191,7 @@ public class WebFluxAutoConfiguration { return this.beanFactory.getBeansOfType(type).values(); } - private void customizeResourceHandlerRegistration( - ResourceHandlerRegistration registration) { + private void customizeResourceHandlerRegistration(ResourceHandlerRegistration registration) { if (this.resourceHandlerRegistrationCustomizer != null) { this.resourceHandlerRegistrationCustomizer.customize(registration); } @@ -212,8 +204,7 @@ public class WebFluxAutoConfiguration { * Configuration equivalent to {@code @EnableWebFlux}. */ @Configuration(proxyBeanMethods = false) - public static class EnableWebFluxConfiguration - extends DelegatingWebFluxConfiguration { + public static class EnableWebFluxConfiguration extends DelegatingWebFluxConfiguration { private final WebFluxProperties webFluxProperties; @@ -228,8 +219,7 @@ public class WebFluxAutoConfiguration { @Bean @Override public FormattingConversionService webFluxConversionService() { - WebConversionService conversionService = new WebConversionService( - this.webFluxProperties.getDateFormat()); + WebConversionService conversionService = new WebConversionService(this.webFluxProperties.getDateFormat()); addFormatters(conversionService); return conversionService; } @@ -237,8 +227,7 @@ public class WebFluxAutoConfiguration { @Bean @Override public Validator webFluxValidator() { - if (!ClassUtils.isPresent("javax.validation.Validator", - getClass().getClassLoader())) { + if (!ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { return super.webFluxValidator(); } return ValidatorAdapter.get(getApplicationContext(), getValidator()); @@ -246,8 +235,8 @@ public class WebFluxAutoConfiguration { @Override protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() { - if (this.webFluxRegistrations != null && this.webFluxRegistrations - .getRequestMappingHandlerAdapter() != null) { + if (this.webFluxRegistrations != null + && this.webFluxRegistrations.getRequestMappingHandlerAdapter() != null) { return this.webFluxRegistrations.getRequestMappingHandlerAdapter(); } return super.createRequestMappingHandlerAdapter(); @@ -255,8 +244,8 @@ public class WebFluxAutoConfiguration { @Override protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() { - if (this.webFluxRegistrations != null && this.webFluxRegistrations - .getRequestMappingHandlerMapping() != null) { + if (this.webFluxRegistrations != null + && this.webFluxRegistrations.getRequestMappingHandlerMapping() != null) { return this.webFluxRegistrations.getRequestMappingHandlerMapping(); } return super.createRequestMappingHandlerMapping(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java index f31a5870e4c..17771410870 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java @@ -56,8 +56,7 @@ import org.springframework.web.util.HtmlUtils; * @since 2.0.0 * @see ErrorAttributes */ -public abstract class AbstractErrorWebExceptionHandler - implements ErrorWebExceptionHandler, InitializingBean { +public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExceptionHandler, InitializingBean { /** * Currently duplicated from Spring WebFlux HttpWebHandlerAdapter. @@ -72,8 +71,7 @@ public abstract class AbstractErrorWebExceptionHandler DISCONNECTED_CLIENT_EXCEPTIONS = Collections.unmodifiableSet(exceptions); } - private static final Log logger = HttpLogging - .forLogName(AbstractErrorWebExceptionHandler.class); + private static final Log logger = HttpLogging.forLogName(AbstractErrorWebExceptionHandler.class); private final ApplicationContext applicationContext; @@ -89,8 +87,7 @@ public abstract class AbstractErrorWebExceptionHandler private List viewResolvers = Collections.emptyList(); - public AbstractErrorWebExceptionHandler(ErrorAttributes errorAttributes, - ResourceProperties resourceProperties, + public AbstractErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext) { Assert.notNull(errorAttributes, "ErrorAttributes must not be null"); Assert.notNull(resourceProperties, "ResourceProperties must not be null"); @@ -98,8 +95,7 @@ public abstract class AbstractErrorWebExceptionHandler this.errorAttributes = errorAttributes; this.resourceProperties = resourceProperties; this.applicationContext = applicationContext; - this.templateAvailabilityProviders = new TemplateAvailabilityProviders( - applicationContext); + this.templateAvailabilityProviders = new TemplateAvailabilityProviders(applicationContext); } /** @@ -135,8 +131,7 @@ public abstract class AbstractErrorWebExceptionHandler * @param includeStackTrace whether to include the error stacktrace information * @return the error attributes as a Map. */ - protected Map getErrorAttributes(ServerRequest request, - boolean includeStackTrace) { + protected Map getErrorAttributes(ServerRequest request, boolean includeStackTrace) { return this.errorAttributes.getErrorAttributes(request, includeStackTrace); } @@ -168,8 +163,8 @@ public abstract class AbstractErrorWebExceptionHandler * @param error the error data as a map * @return a Publisher of the {@link ServerResponse} */ - protected Mono renderErrorView(String viewName, - ServerResponse.BodyBuilder responseBody, Map error) { + protected Mono renderErrorView(String viewName, ServerResponse.BodyBuilder responseBody, + Map error) { if (isTemplateAvailable(viewName)) { return responseBody.render(viewName, error); } @@ -181,8 +176,7 @@ public abstract class AbstractErrorWebExceptionHandler } private boolean isTemplateAvailable(String viewName) { - return this.templateAvailabilityProviders.getProvider(viewName, - this.applicationContext) != null; + return this.templateAvailabilityProviders.getProvider(viewName, this.applicationContext) != null; } private Resource resolveResource(String viewName) { @@ -209,26 +203,23 @@ public abstract class AbstractErrorWebExceptionHandler * @param error the error data as a map * @return a Publisher of the {@link ServerResponse} */ - protected Mono renderDefaultErrorView( - ServerResponse.BodyBuilder responseBody, Map error) { + protected Mono renderDefaultErrorView(ServerResponse.BodyBuilder responseBody, + Map error) { StringBuilder builder = new StringBuilder(); Date timestamp = (Date) error.get("timestamp"); Object message = error.get("message"); Object trace = error.get("trace"); Object requestId = error.get("requestId"); - builder.append("

    Whitelabel Error Page

    ").append( - "

    This application has no configured error view, so you are seeing this as a fallback.

    ") - .append("
    ").append(timestamp).append("
    ") - .append("
    [").append(requestId) - .append("] There was an unexpected error (type=") - .append(htmlEscape(error.get("error"))).append(", status=") - .append(htmlEscape(error.get("status"))).append(").
    "); + builder.append("

    Whitelabel Error Page

    ") + .append("

    This application has no configured error view, so you are seeing this as a fallback.

    ") + .append("
    ").append(timestamp).append("
    ").append("
    [").append(requestId) + .append("] There was an unexpected error (type=").append(htmlEscape(error.get("error"))) + .append(", status=").append(htmlEscape(error.get("status"))).append(").
    "); if (message != null) { builder.append("
    ").append(htmlEscape(message)).append("
    "); } if (trace != null) { - builder.append("
    ") - .append(htmlEscape(trace)).append("
    "); + builder.append("
    ").append(htmlEscape(trace)).append("
    "); } builder.append(""); return responseBody.syncBody(builder.toString()); @@ -256,19 +247,16 @@ public abstract class AbstractErrorWebExceptionHandler * information * @return a {@link RouterFunction} that routes and handles errors */ - protected abstract RouterFunction getRoutingFunction( - ErrorAttributes errorAttributes); + protected abstract RouterFunction getRoutingFunction(ErrorAttributes errorAttributes); @Override public Mono handle(ServerWebExchange exchange, Throwable throwable) { - if (exchange.getResponse().isCommitted() - || isDisconnectedClientError(throwable)) { + if (exchange.getResponse().isCommitted() || isDisconnectedClientError(throwable)) { return Mono.error(throwable); } this.errorAttributes.storeErrorInformation(throwable, exchange); ServerRequest request = ServerRequest.create(exchange, this.messageReaders); - return getRoutingFunction(this.errorAttributes).route(request) - .switchIfEmpty(Mono.error(throwable)) + return getRoutingFunction(this.errorAttributes).route(request).switchIfEmpty(Mono.error(throwable)) .flatMap((handler) -> handler.handle(request)) .doOnNext((response) -> logError(request, response, throwable)) .flatMap((response) -> write(exchange, response)); @@ -276,32 +264,27 @@ public abstract class AbstractErrorWebExceptionHandler private boolean isDisconnectedClientError(Throwable ex) { return DISCONNECTED_CLIENT_EXCEPTIONS.contains(ex.getClass().getSimpleName()) - || isDisconnectedClientErrorMessage( - NestedExceptionUtils.getMostSpecificCause(ex).getMessage()); + || isDisconnectedClientErrorMessage(NestedExceptionUtils.getMostSpecificCause(ex).getMessage()); } private boolean isDisconnectedClientErrorMessage(String message) { message = (message != null) ? message.toLowerCase() : ""; - return (message.contains("broken pipe") - || message.contains("connection reset by peer")); + return (message.contains("broken pipe") || message.contains("connection reset by peer")); } - private void logError(ServerRequest request, ServerResponse response, - Throwable throwable) { + private void logError(ServerRequest request, ServerResponse response, Throwable throwable) { if (logger.isDebugEnabled()) { - logger.debug( - request.exchange().getLogPrefix() + formatError(throwable, request)); + logger.debug(request.exchange().getLogPrefix() + formatError(throwable, request)); } if (response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) { - logger.error(request.exchange().getLogPrefix() + "500 Server Error for " - + formatRequest(request), throwable); + logger.error(request.exchange().getLogPrefix() + "500 Server Error for " + formatRequest(request), + throwable); } } private String formatError(Throwable ex, ServerRequest request) { String reason = ex.getClass().getSimpleName() + ": " + ex.getMessage(); - return "Resolved [" + reason + "] for HTTP " + request.methodName() + " " - + request.path(); + return "Resolved [" + reason + "] for HTTP " + request.methodName() + " " + request.path(); } private String formatRequest(ServerRequest request) { @@ -310,11 +293,9 @@ public abstract class AbstractErrorWebExceptionHandler return "HTTP " + request.methodName() + " \"" + request.path() + query + "\""; } - private Mono write(ServerWebExchange exchange, - ServerResponse response) { + private Mono write(ServerWebExchange exchange, ServerResponse response) { // force content-type since writeTo won't overwrite response header values - exchange.getResponse().getHeaders() - .setContentType(response.headers().getContentType()); + exchange.getResponse().getHeaders().setContentType(response.headers().getContentType()); return response.writeTo(exchange, new ResponseContext()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java index 9726d75c640..8756092ea69 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java @@ -74,8 +74,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r */ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { - private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", - StandardCharsets.UTF_8); + private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8); private static final Map SERIES_VIEWS; @@ -95,18 +94,15 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa * @param errorProperties the error configuration properties * @param applicationContext the current application context */ - public DefaultErrorWebExceptionHandler(ErrorAttributes errorAttributes, - ResourceProperties resourceProperties, ErrorProperties errorProperties, - ApplicationContext applicationContext) { + public DefaultErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, + ErrorProperties errorProperties, ApplicationContext applicationContext) { super(errorAttributes, resourceProperties, applicationContext); this.errorProperties = errorProperties; } @Override - protected RouterFunction getRoutingFunction( - ErrorAttributes errorAttributes) { - return route(acceptsTextHtml(), this::renderErrorView).andRoute(all(), - this::renderErrorResponse); + protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) { + return route(acceptsTextHtml(), this::renderErrorView).andRoute(all(), this::renderErrorResponse); } /** @@ -118,15 +114,12 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa boolean includeStackTrace = isIncludeStackTrace(request, MediaType.TEXT_HTML); Map error = getErrorAttributes(request, includeStackTrace); HttpStatus errorStatus = getHttpStatus(error); - ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus) - .contentType(TEXT_HTML_UTF8); + ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus).contentType(TEXT_HTML_UTF8); return Flux - .just("error/" + errorStatus.value(), - "error/" + SERIES_VIEWS.get(errorStatus.series()), "error/error") + .just("error/" + errorStatus.value(), "error/" + SERIES_VIEWS.get(errorStatus.series()), "error/error") .flatMap((viewName) -> renderErrorView(viewName, responseBody, error)) .switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled() - ? renderDefaultErrorView(responseBody, error) - : Mono.error(getError(request))) + ? renderDefaultErrorView(responseBody, error) : Mono.error(getError(request))) .next(); } @@ -138,8 +131,7 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa protected Mono renderErrorResponse(ServerRequest request) { boolean includeStackTrace = isIncludeStackTrace(request, MediaType.ALL); Map error = getErrorAttributes(request, includeStackTrace); - return ServerResponse.status(getHttpStatus(error)) - .contentType(MediaType.APPLICATION_JSON_UTF8) + return ServerResponse.status(getHttpStatus(error)).contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(error)); } @@ -150,8 +142,7 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa * @return if the stacktrace attribute should be included */ protected boolean isIncludeStackTrace(ServerRequest request, MediaType produces) { - ErrorProperties.IncludeStacktrace include = this.errorProperties - .getIncludeStacktrace(); + ErrorProperties.IncludeStacktrace include = this.errorProperties.getIncludeStacktrace(); if (include == ErrorProperties.IncludeStacktrace.ALWAYS) { return true; } @@ -184,8 +175,7 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa List acceptedMediaTypes = serverRequest.headers().accept(); acceptedMediaTypes.remove(MediaType.ALL); MediaType.sortBySpecificityAndQuality(acceptedMediaTypes); - return acceptedMediaTypes.stream() - .anyMatch(MediaType.TEXT_HTML::isCompatibleWith); + return acceptedMediaTypes.stream().anyMatch(MediaType.TEXT_HTML::isCompatibleWith); } catch (InvalidMediaTypeException ex) { return false; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/ErrorWebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/ErrorWebFluxAutoConfiguration.java index 191f614720d..7b95da860b0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/ErrorWebFluxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/ErrorWebFluxAutoConfiguration.java @@ -61,30 +61,23 @@ public class ErrorWebFluxAutoConfiguration { } @Bean - @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT) @Order(-1) - public ErrorWebExceptionHandler errorWebExceptionHandler( - ErrorAttributes errorAttributes, ResourceProperties resourceProperties, - ObjectProvider viewResolvers, - ServerCodecConfigurer serverCodecConfigurer, - ApplicationContext applicationContext) { - DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler( - errorAttributes, resourceProperties, this.serverProperties.getError(), - applicationContext); - exceptionHandler.setViewResolvers( - viewResolvers.orderedStream().collect(Collectors.toList())); + public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes, + ResourceProperties resourceProperties, ObjectProvider viewResolvers, + ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) { + DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler(errorAttributes, + resourceProperties, this.serverProperties.getError(), applicationContext); + exceptionHandler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList())); exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters()); exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders()); return exceptionHandler; } @Bean - @ConditionalOnMissingBean(value = ErrorAttributes.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { - return new DefaultErrorAttributes( - this.serverProperties.getError().isIncludeException()); + return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfiguration.java index 81b76c2fff3..7e51c30cbf1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfiguration.java @@ -39,15 +39,13 @@ import org.springframework.web.reactive.function.client.WebClient; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(WebClient.class) -@Import({ ClientHttpConnectorConfiguration.ReactorNetty.class, - ClientHttpConnectorConfiguration.JettyClient.class }) +@Import({ ClientHttpConnectorConfiguration.ReactorNetty.class, ClientHttpConnectorConfiguration.JettyClient.class }) public class ClientHttpConnectorAutoConfiguration { @Bean @Order(0) @ConditionalOnBean(ClientHttpConnector.class) - public WebClientCustomizer clientConnectorCustomizer( - ClientHttpConnector clientHttpConnector) { + public WebClientCustomizer clientConnectorCustomizer(ClientHttpConnector clientHttpConnector) { return (builder) -> builder.clientConnector(clientHttpConnector); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java index 7972d2a68a5..e27ff0e9353 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java @@ -54,10 +54,8 @@ class ClientHttpConnectorConfiguration { } @Bean - public ReactorClientHttpConnector reactorClientHttpConnector( - ReactorResourceFactory reactorResourceFactory) { - return new ReactorClientHttpConnector(reactorResourceFactory, - Function.identity()); + public ReactorClientHttpConnector reactorClientHttpConnector(ReactorResourceFactory reactorResourceFactory) { + return new ReactorClientHttpConnector(reactorResourceFactory, Function.identity()); } } @@ -74,8 +72,7 @@ class ClientHttpConnectorConfiguration { } @Bean - public JettyClientHttpConnector jettyClientHttpConnector( - JettyResourceFactory jettyResourceFactory) { + public JettyClientHttpConnector jettyClientHttpConnector(JettyResourceFactory jettyResourceFactory) { SslContextFactory sslContextFactory = new SslContextFactory.Client(); HttpClient httpClient = new HttpClient(sslContextFactory); return new JettyClientHttpConnector(httpClient, jettyResourceFactory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.java index f7a454d1410..8625053128c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.java @@ -46,17 +46,14 @@ import org.springframework.web.reactive.function.client.WebClient; */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(WebClient.class) -@AutoConfigureAfter({ CodecsAutoConfiguration.class, - ClientHttpConnectorAutoConfiguration.class }) +@AutoConfigureAfter({ CodecsAutoConfiguration.class, ClientHttpConnectorAutoConfiguration.class }) public class WebClientAutoConfiguration { private final WebClient.Builder webClientBuilder; - public WebClientAutoConfiguration( - ObjectProvider customizerProvider) { + public WebClientAutoConfiguration(ObjectProvider customizerProvider) { this.webClientBuilder = WebClient.builder(); - customizerProvider.orderedStream() - .forEach((customizer) -> customizer.customize(this.webClientBuilder)); + customizerProvider.orderedStream().forEach((customizer) -> customizer.customize(this.webClientBuilder)); } @Bean @@ -73,8 +70,7 @@ public class WebClientAutoConfiguration { @Bean @ConditionalOnMissingBean @Order(0) - public WebClientCodecCustomizer exchangeStrategiesCustomizer( - List codecCustomizers) { + public WebClientCodecCustomizer exchangeStrategiesCustomizer(List codecCustomizers) { return new WebClientCodecCustomizer(codecCustomizers); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java index ad6ad1ad548..380ac8d35b0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,11 +39,9 @@ public class WebClientCodecCustomizer implements WebClientCustomizer { @Override public void customize(WebClient.Builder webClientBuilder) { - webClientBuilder - .exchangeStrategies(ExchangeStrategies.builder() - .codecs((codecs) -> this.codecCustomizers - .forEach((customizer) -> customizer.customize(codecs))) - .build()); + webClientBuilder.exchangeStrategies(ExchangeStrategies.builder() + .codecs((codecs) -> this.codecCustomizers.forEach((customizer) -> customizer.customize(codecs))) + .build()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java index a2cbc6dc83c..3b0fa520ec6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java @@ -52,10 +52,8 @@ public class DefaultJerseyApplicationPath implements JerseyApplicationPath { return this.applicationPath; } // Jersey doesn't like to be the default servlet, so map to /* as a fallback - return MergedAnnotations - .from(this.config.getApplication().getClass(), SearchStrategy.EXHAUSTIVE) - .get(ApplicationPath.class).getValue(MergedAnnotation.VALUE, String.class) - .orElse("/*"); + return MergedAnnotations.from(this.config.getApplication().getClass(), SearchStrategy.EXHAUSTIVE) + .get(ApplicationPath.class).getValue(MergedAnnotation.VALUE, String.class).orElse("/*"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java index 1c362ed53e4..bcffa7a3a32 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java @@ -86,17 +86,12 @@ public class DispatcherServletAutoConfiguration { protected static class DispatcherServletConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) - public DispatcherServlet dispatcherServlet(HttpProperties httpProperties, - WebMvcProperties webMvcProperties) { + public DispatcherServlet dispatcherServlet(HttpProperties httpProperties, WebMvcProperties webMvcProperties) { DispatcherServlet dispatcherServlet = new DispatcherServlet(); - dispatcherServlet.setDispatchOptionsRequest( - webMvcProperties.isDispatchOptionsRequest()); - dispatcherServlet - .setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest()); - dispatcherServlet.setThrowExceptionIfNoHandlerFound( - webMvcProperties.isThrowExceptionIfNoHandlerFound()); - dispatcherServlet - .setEnableLoggingRequestDetails(httpProperties.isLogRequestDetails()); + dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest()); + dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest()); + dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound()); + dispatcherServlet.setEnableLoggingRequestDetails(httpProperties.isLogRequestDetails()); return dispatcherServlet; } @@ -118,16 +113,13 @@ public class DispatcherServletAutoConfiguration { protected static class DispatcherServletRegistrationConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) - @ConditionalOnBean(value = DispatcherServlet.class, - name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) - public DispatcherServletRegistrationBean dispatcherServletRegistration( - DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties, - ObjectProvider multipartConfig) { - DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean( - dispatcherServlet, webMvcProperties.getServlet().getPath()); + @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) + public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet, + WebMvcProperties webMvcProperties, ObjectProvider multipartConfig) { + DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, + webMvcProperties.getServlet().getPath()); registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); - registration - .setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup()); + registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup()); multipartConfig.ifAvailable(registration::setMultipartConfig); return registration; } @@ -138,28 +130,23 @@ public class DispatcherServletAutoConfiguration { private static class DefaultDispatcherServletCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Default DispatcherServlet"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Default DispatcherServlet"); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - List dispatchServletBeans = Arrays.asList(beanFactory - .getBeanNamesForType(DispatcherServlet.class, false, false)); + List dispatchServletBeans = Arrays + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); if (dispatchServletBeans.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome.noMatch(message.found("dispatcher servlet bean") - .items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + return ConditionOutcome + .noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome - .noMatch(message.found("non dispatcher servlet bean") - .items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + return ConditionOutcome.noMatch( + message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (dispatchServletBeans.isEmpty()) { - return ConditionOutcome - .match(message.didNotFind("dispatcher servlet beans").atAll()); + return ConditionOutcome.match(message.didNotFind("dispatcher servlet beans").atAll()); } - return ConditionOutcome.match(message - .found("dispatcher servlet bean", "dispatcher servlet beans") + return ConditionOutcome.match(message.found("dispatcher servlet bean", "dispatcher servlet beans") .items(Style.QUOTE, dispatchServletBeans) .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } @@ -167,12 +154,10 @@ public class DispatcherServletAutoConfiguration { } @Order(Ordered.LOWEST_PRECEDENCE - 10) - private static class DispatcherServletRegistrationCondition - extends SpringBootCondition { + private static class DispatcherServletRegistrationCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); ConditionOutcome outcome = checkDefaultDispatcherName(beanFactory); if (!outcome.isMatch()) { @@ -181,50 +166,40 @@ public class DispatcherServletAutoConfiguration { return checkServletRegistration(beanFactory); } - private ConditionOutcome checkDefaultDispatcherName( - ConfigurableListableBeanFactory beanFactory) { - List servlets = Arrays.asList(beanFactory - .getBeanNamesForType(DispatcherServlet.class, false, false)); - boolean containsDispatcherBean = beanFactory - .containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); - if (containsDispatcherBean - && !servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome - .noMatch(startMessage().found("non dispatcher servlet") - .items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + private ConditionOutcome checkDefaultDispatcherName(ConfigurableListableBeanFactory beanFactory) { + List servlets = Arrays + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); + boolean containsDispatcherBean = beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); + if (containsDispatcherBean && !servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { + return ConditionOutcome.noMatch( + startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } return ConditionOutcome.match(); } - private ConditionOutcome checkServletRegistration( - ConfigurableListableBeanFactory beanFactory) { + private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) { ConditionMessage.Builder message = startMessage(); - List registrations = Arrays.asList(beanFactory - .getBeanNamesForType(ServletRegistrationBean.class, false, false)); + List registrations = Arrays + .asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false)); boolean containsDispatcherRegistrationBean = beanFactory .containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); if (registrations.isEmpty()) { if (containsDispatcherRegistrationBean) { - return ConditionOutcome - .noMatch(message.found("non servlet registration bean").items( - DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.noMatch(message.found("non servlet registration bean") + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } - return ConditionOutcome - .match(message.didNotFind("servlet registration bean").atAll()); + return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll()); } - if (registrations - .contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) { + if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) { return ConditionOutcome.noMatch(message.found("servlet registration bean") .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } if (containsDispatcherRegistrationBean) { - return ConditionOutcome - .noMatch(message.found("non servlet registration bean").items( - DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.noMatch(message.found("non servlet registration bean") + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } - return ConditionOutcome.match(message.found("servlet registration beans") - .items(Style.QUOTE, registrations).append("and none is named " - + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.match(message.found("servlet registration beans").items(Style.QUOTE, registrations) + .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } private ConditionMessage.Builder startMessage() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBean.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBean.java index 7d7dfe838e7..9c6625cfe99 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBean.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ import org.springframework.web.servlet.DispatcherServlet; * @author Phillip Webb * @since 2.0.4 */ -public class DispatcherServletRegistrationBean extends - ServletRegistrationBean implements DispatcherServletPath { +public class DispatcherServletRegistrationBean extends ServletRegistrationBean + implements DispatcherServletPath { private final String path; @@ -54,14 +54,12 @@ public class DispatcherServletRegistrationBean extends @Override public void setUrlMappings(Collection urlMappings) { - throw new UnsupportedOperationException( - "URL Mapping cannot be changed on a DispatcherServlet registration"); + throw new UnsupportedOperationException("URL Mapping cannot be changed on a DispatcherServlet registration"); } @Override public void addUrlMappings(String... urlMappings) { - throw new UnsupportedOperationException( - "URL Mapping cannot be changed on a DispatcherServlet registration"); + throw new UnsupportedOperationException("URL Mapping cannot be changed on a DispatcherServlet registration"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.java index ba19523d7bc..6eeb0ed869d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.java @@ -44,8 +44,7 @@ import org.springframework.web.filter.CharacterEncodingFilter; @EnableConfigurationProperties(HttpProperties.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(CharacterEncodingFilter.class) -@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) public class HttpEncodingAutoConfiguration { private final HttpProperties.Encoding properties; @@ -69,8 +68,8 @@ public class HttpEncodingAutoConfiguration { return new LocaleCharsetMappingsCustomizer(this.properties); } - private static class LocaleCharsetMappingsCustomizer implements - WebServerFactoryCustomizer, Ordered { + private static class LocaleCharsetMappingsCustomizer + implements WebServerFactoryCustomizer, Ordered { private final HttpProperties.Encoding properties; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProvider.java index fa70c61b2e7..b5bc4f8d86b 100755 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProvider.java @@ -36,8 +36,8 @@ import org.springframework.util.ClassUtils; public class JspTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { @@ -53,10 +53,8 @@ public class JspTemplateAvailabilityProvider implements TemplateAvailabilityProv } private String getResourceName(String view, Environment environment) { - String prefix = environment.getProperty("spring.mvc.view.prefix", - WebMvcAutoConfiguration.DEFAULT_PREFIX); - String suffix = environment.getProperty("spring.mvc.view.suffix", - WebMvcAutoConfiguration.DEFAULT_SUFFIX); + String prefix = environment.getProperty("spring.mvc.view.prefix", WebMvcAutoConfiguration.DEFAULT_PREFIX); + String suffix = environment.getProperty("spring.mvc.view.suffix", WebMvcAutoConfiguration.DEFAULT_SUFFIX); return prefix + view + suffix; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java index 13a7b743205..951e3a3dbd2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java @@ -49,10 +49,8 @@ import org.springframework.web.servlet.DispatcherServlet; * @author Toshiaki Maki */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, - MultipartConfigElement.class }) -@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", - matchIfMissing = true) +@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class }) +@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", matchIfMissing = true) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(MultipartProperties.class) public class MultipartAutoConfiguration { @@ -64,8 +62,7 @@ public class MultipartAutoConfiguration { } @Bean - @ConditionalOnMissingBean({ MultipartConfigElement.class, - CommonsMultipartResolver.class }) + @ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class }) public MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java index 1fe9aa11948..3d935ed4dd2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java @@ -66,8 +66,7 @@ import org.springframework.web.filter.ForwardedHeaderFilter; public class ServletWebServerFactoryAutoConfiguration { @Bean - public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer( - ServerProperties serverProperties) { + public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties) { return new ServletWebServerFactoryCustomizer(serverProperties); } @@ -80,14 +79,11 @@ public class ServletWebServerFactoryAutoConfiguration { @Bean @ConditionalOnMissingFilterBean(ForwardedHeaderFilter.class) - @ConditionalOnProperty(value = "server.forward-headers-strategy", - havingValue = "framework") + @ConditionalOnProperty(value = "server.forward-headers-strategy", havingValue = "framework") public FilterRegistrationBean forwardedHeaderFilter() { ForwardedHeaderFilter filter = new ForwardedHeaderFilter(); - FilterRegistrationBean registration = new FilterRegistrationBean<>( - filter); - registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC, - DispatcherType.ERROR); + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); + registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.ERROR); registration.setOrder(Ordered.HIGHEST_PRECEDENCE); return registration; } @@ -96,8 +92,7 @@ public class ServletWebServerFactoryAutoConfiguration { * Registers a {@link WebServerFactoryCustomizerBeanPostProcessor}. Registered via * {@link ImportBeanDefinitionRegistrar} for early registration. */ - public static class BeanPostProcessorsRegistrar - implements ImportBeanDefinitionRegistrar, BeanFactoryAware { + public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @@ -114,18 +109,14 @@ public class ServletWebServerFactoryAutoConfiguration { if (this.beanFactory == null) { return; } - registerSyntheticBeanIfMissing(registry, - "webServerFactoryCustomizerBeanPostProcessor", + registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class); - registerSyntheticBeanIfMissing(registry, - "errorPageRegistrarBeanPostProcessor", + registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class); } - private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, - String name, Class beanClass) { - if (ObjectUtils.isEmpty( - this.beanFactory.getBeanNamesForType(beanClass, true, false))) { + private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class beanClass) { + if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java index d5f294775e8..ee11aba4508 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java @@ -64,8 +64,7 @@ class ServletWebServerFactoryConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class }) - @ConditionalOnMissingBean(value = ServletWebServerFactory.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedTomcat { @Bean @@ -74,13 +73,12 @@ class ServletWebServerFactoryConfiguration { ObjectProvider contextCustomizers, ObjectProvider> protocolHandlerCustomizers) { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); - factory.getTomcatConnectorCustomizers().addAll( - connectorCustomizers.orderedStream().collect(Collectors.toList())); - factory.getTomcatContextCustomizers().addAll( - contextCustomizers.orderedStream().collect(Collectors.toList())); + factory.getTomcatConnectorCustomizers() + .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList())); + factory.getTomcatContextCustomizers() + .addAll(contextCustomizers.orderedStream().collect(Collectors.toList())); factory.getTomcatProtocolHandlerCustomizers() - .addAll(protocolHandlerCustomizers.orderedStream() - .collect(Collectors.toList())); + .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList())); return factory; } @@ -90,18 +88,15 @@ class ServletWebServerFactoryConfiguration { * Nested configuration if Jetty is being used. */ @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, - WebAppContext.class }) - @ConditionalOnMissingBean(value = ServletWebServerFactory.class, - search = SearchStrategy.CURRENT) + @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) + @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedJetty { @Bean public JettyServletWebServerFactory JettyServletWebServerFactory( ObjectProvider serverCustomizers) { JettyServletWebServerFactory factory = new JettyServletWebServerFactory(); - factory.getServerCustomizers().addAll( - serverCustomizers.orderedStream().collect(Collectors.toList())); + factory.getServerCustomizers().addAll(serverCustomizers.orderedStream().collect(Collectors.toList())); return factory; } @@ -112,8 +107,7 @@ class ServletWebServerFactoryConfiguration { */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class }) - @ConditionalOnMissingBean(value = ServletWebServerFactory.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedUndertow { @Bean @@ -121,10 +115,9 @@ class ServletWebServerFactoryConfiguration { ObjectProvider deploymentInfoCustomizers, ObjectProvider builderCustomizers) { UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); - factory.getDeploymentInfoCustomizers().addAll(deploymentInfoCustomizers - .orderedStream().collect(Collectors.toList())); - factory.getBuilderCustomizers().addAll( - builderCustomizers.orderedStream().collect(Collectors.toList())); + factory.getDeploymentInfoCustomizers() + .addAll(deploymentInfoCustomizers.orderedStream().collect(Collectors.toList())); + factory.getBuilderCustomizers().addAll(builderCustomizers.orderedStream().collect(Collectors.toList())); return factory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizer.java index fda14ea06e4..e05f921910d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,8 @@ import org.springframework.core.Ordered; * @author Yunkun Huang * @since 2.0.0 */ -public class ServletWebServerFactoryCustomizer implements - WebServerFactoryCustomizer, Ordered { +public class ServletWebServerFactoryCustomizer + implements WebServerFactoryCustomizer, Ordered { private final ServerProperties serverProperties; @@ -51,18 +51,15 @@ public class ServletWebServerFactoryCustomizer implements PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this.serverProperties::getPort).to(factory::setPort); map.from(this.serverProperties::getAddress).to(factory::setAddress); - map.from(this.serverProperties.getServlet()::getContextPath) - .to(factory::setContextPath); - map.from(this.serverProperties.getServlet()::getApplicationDisplayName) - .to(factory::setDisplayName); + map.from(this.serverProperties.getServlet()::getContextPath).to(factory::setContextPath); + map.from(this.serverProperties.getServlet()::getApplicationDisplayName).to(factory::setDisplayName); map.from(this.serverProperties.getServlet()::getSession).to(factory::setSession); map.from(this.serverProperties::getSsl).to(factory::setSsl); map.from(this.serverProperties.getServlet()::getJsp).to(factory::setJsp); map.from(this.serverProperties::getCompression).to(factory::setCompression); map.from(this.serverProperties::getHttp2).to(factory::setHttp2); map.from(this.serverProperties::getServerHeader).to(factory::setServerHeader); - map.from(this.serverProperties.getServlet()::getContextParameters) - .to(factory::setInitParameters); + map.from(this.serverProperties.getServlet()::getContextParameters).to(factory::setInitParameters); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizer.java index 30e965d93c4..8e4b320cfe6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizer.java @@ -49,30 +49,24 @@ public class TomcatServletWebServerFactoryCustomizer public void customize(TomcatServletWebServerFactory factory) { ServerProperties.Tomcat tomcatProperties = this.serverProperties.getTomcat(); if (!ObjectUtils.isEmpty(tomcatProperties.getAdditionalTldSkipPatterns())) { - factory.getTldSkipPatterns() - .addAll(tomcatProperties.getAdditionalTldSkipPatterns()); + factory.getTldSkipPatterns().addAll(tomcatProperties.getAdditionalTldSkipPatterns()); } if (tomcatProperties.getRedirectContextRoot() != null) { - customizeRedirectContextRoot(factory, - tomcatProperties.getRedirectContextRoot()); + customizeRedirectContextRoot(factory, tomcatProperties.getRedirectContextRoot()); } if (tomcatProperties.getUseRelativeRedirects() != null) { - customizeUseRelativeRedirects(factory, - tomcatProperties.getUseRelativeRedirects()); + customizeUseRelativeRedirects(factory, tomcatProperties.getUseRelativeRedirects()); } factory.setDisableMBeanRegistry(!tomcatProperties.getMbeanregistry().isEnabled()); } - private void customizeRedirectContextRoot(ConfigurableTomcatWebServerFactory factory, - boolean redirectContextRoot) { - factory.addContextCustomizers((context) -> context - .setMapperContextRootRedirectEnabled(redirectContextRoot)); + private void customizeRedirectContextRoot(ConfigurableTomcatWebServerFactory factory, boolean redirectContextRoot) { + factory.addContextCustomizers((context) -> context.setMapperContextRootRedirectEnabled(redirectContextRoot)); } private void customizeUseRelativeRedirects(ConfigurableTomcatWebServerFactory factory, boolean useRelativeRedirects) { - factory.addContextCustomizers( - (context) -> context.setUseRelativeRedirects(useRelativeRedirects)); + factory.addContextCustomizers((context) -> context.setUseRelativeRedirects(useRelativeRedirects)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java index cbda523fa81..07e0d7ecf6f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java @@ -143,8 +143,8 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) -@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, - TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class }) +@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, + ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration { public static final String DEFAULT_PREFIX = ""; @@ -155,16 +155,14 @@ public class WebMvcAutoConfiguration { @Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) - @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = true) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { return new OrderedHiddenHttpMethodFilter(); } @Bean @ConditionalOnMissingBean(FormContentFilter.class) - @ConditionalOnProperty(prefix = "spring.mvc.formcontent.filter", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.mvc.formcontent.filter", name = "enabled", matchIfMissing = true) public OrderedFormContentFilter formContentFilter() { return new OrderedFormContentFilter(); } @@ -175,8 +173,7 @@ public class WebMvcAutoConfiguration { @Import(EnableWebMvcConfiguration.class) @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class }) @Order(0) - public static class WebMvcAutoConfigurationAdapter - implements WebMvcConfigurer, ResourceLoaderAware { + public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ResourceLoaderAware { private static final Log logger = LogFactory.getLog(WebMvcConfigurer.class); @@ -192,16 +189,14 @@ public class WebMvcAutoConfiguration { private ResourceLoader resourceLoader; - public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, - WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, - ObjectProvider messageConvertersProvider, + public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, + ListableBeanFactory beanFactory, ObjectProvider messageConvertersProvider, ObjectProvider resourceHandlerRegistrationCustomizerProvider) { this.resourceProperties = resourceProperties; this.mvcProperties = mvcProperties; this.beanFactory = beanFactory; this.messageConvertersProvider = messageConvertersProvider; - this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider - .getIfAvailable(); + this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable(); } @Override @@ -211,16 +206,15 @@ public class WebMvcAutoConfiguration { @Override public void configureMessageConverters(List> converters) { - this.messageConvertersProvider.ifAvailable((customConverters) -> converters - .addAll(customConverters.getConverters())); + this.messageConvertersProvider + .ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters())); } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { - if (this.beanFactory.containsBean( - TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)) { - Object taskExecutor = this.beanFactory.getBean( - TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); + if (this.beanFactory.containsBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)) { + Object taskExecutor = this.beanFactory + .getBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); if (taskExecutor instanceof AsyncTaskExecutor) { configurer.setTaskExecutor(((AsyncTaskExecutor) taskExecutor)); } @@ -233,23 +227,20 @@ public class WebMvcAutoConfiguration { @Override public void configurePathMatch(PathMatchConfigurer configurer) { - configurer.setUseSuffixPatternMatch( - this.mvcProperties.getPathmatch().isUseSuffixPattern()); + configurer.setUseSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseSuffixPattern()); configurer.setUseRegisteredSuffixPatternMatch( this.mvcProperties.getPathmatch().isUseRegisteredSuffixPattern()); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { - WebMvcProperties.Contentnegotiation contentnegotiation = this.mvcProperties - .getContentnegotiation(); + WebMvcProperties.Contentnegotiation contentnegotiation = this.mvcProperties.getContentnegotiation(); configurer.favorPathExtension(contentnegotiation.isFavorPathExtension()); configurer.favorParameter(contentnegotiation.isFavorParameter()); if (contentnegotiation.getParameterName() != null) { configurer.parameterName(contentnegotiation.getParameterName()); } - Map mediaTypes = this.mvcProperties.getContentnegotiation() - .getMediaTypes(); + Map mediaTypes = this.mvcProperties.getContentnegotiation().getMediaTypes(); mediaTypes.forEach(configurer::mediaType); } @@ -273,12 +264,10 @@ public class WebMvcAutoConfiguration { @Bean @ConditionalOnBean(ViewResolver.class) - @ConditionalOnMissingBean(name = "viewResolver", - value = ContentNegotiatingViewResolver.class) + @ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class) public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) { ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); - resolver.setContentNegotiationManager( - beanFactory.getBean(ContentNegotiationManager.class)); + resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class)); // ContentNegotiatingViewResolver uses all the other view resolvers to locate // a view so it should have a high precedence resolver.setOrder(Ordered.HIGHEST_PRECEDENCE); @@ -289,8 +278,7 @@ public class WebMvcAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.mvc", name = "locale") public LocaleResolver localeResolver() { - if (this.mvcProperties - .getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) { + if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) { return new FixedLocaleResolver(this.mvcProperties.getLocale()); } AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); @@ -302,8 +290,7 @@ public class WebMvcAutoConfiguration { public MessageCodesResolver getMessageCodesResolver() { if (this.mvcProperties.getMessageCodesResolverFormat() != null) { DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver(); - resolver.setMessageCodeFormatter( - this.mvcProperties.getMessageCodesResolverFormat()); + resolver.setMessageCodeFormatter(this.mvcProperties.getMessageCodesResolverFormat()); return resolver; } return null; @@ -333,23 +320,17 @@ public class WebMvcAutoConfiguration { return; } Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); - CacheControl cacheControl = this.resourceProperties.getCache() - .getCachecontrol().toHttpCacheControl(); + CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { - customizeResourceHandlerRegistration(registry - .addResourceHandler("/webjars/**") + customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") - .setCachePeriod(getSeconds(cachePeriod)) - .setCacheControl(cacheControl)); + .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { - customizeResourceHandlerRegistration( - registry.addResourceHandler(staticPathPattern) - .addResourceLocations(getResourceLocations( - this.resourceProperties.getStaticLocations())) - .setCachePeriod(getSeconds(cachePeriod)) - .setCacheControl(cacheControl)); + customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) + .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())) + .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } @@ -358,28 +339,21 @@ public class WebMvcAutoConfiguration { } @Bean - public WelcomePageHandlerMapping welcomePageHandlerMapping( - ApplicationContext applicationContext) { - return new WelcomePageHandlerMapping( - new TemplateAvailabilityProviders(applicationContext), - applicationContext, getWelcomePage(), - this.mvcProperties.getStaticPathPattern()); + public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) { + return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), + applicationContext, getWelcomePage(), this.mvcProperties.getStaticPathPattern()); } static String[] getResourceLocations(String[] staticLocations) { - String[] locations = new String[staticLocations.length - + SERVLET_LOCATIONS.length]; + String[] locations = new String[staticLocations.length + SERVLET_LOCATIONS.length]; System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length); - System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length, - SERVLET_LOCATIONS.length); + System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length, SERVLET_LOCATIONS.length); return locations; } private Optional getWelcomePage() { - String[] locations = getResourceLocations( - this.resourceProperties.getStaticLocations()); - return Arrays.stream(locations).map(this::getIndexHtml) - .filter(this::isReadable).findFirst(); + String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations()); + return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst(); } private Resource getIndexHtml(String location) { @@ -395,24 +369,21 @@ public class WebMvcAutoConfiguration { } } - private void customizeResourceHandlerRegistration( - ResourceHandlerRegistration registration) { + private void customizeResourceHandlerRegistration(ResourceHandlerRegistration registration) { if (this.resourceHandlerRegistrationCustomizer != null) { this.resourceHandlerRegistrationCustomizer.customize(registration); } } @Bean - @ConditionalOnMissingBean({ RequestContextListener.class, - RequestContextFilter.class }) + @ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class }) @ConditionalOnMissingFilterBean(RequestContextFilter.class) public static RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties; @@ -429,8 +400,7 @@ public class WebMvcAutoConfiguration { } @Bean - public SimpleUrlHandlerMapping faviconHandlerMapping( - FaviconRequestHandler handler) { + public SimpleUrlHandlerMapping faviconHandlerMapping(FaviconRequestHandler handler) { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", handler)); @@ -443,11 +413,9 @@ public class WebMvcAutoConfiguration { } private List resolveFaviconLocations() { - String[] staticLocations = getResourceLocations( - this.resourceProperties.getStaticLocations()); + String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations()); List locations = new ArrayList<>(staticLocations.length + 1); - Arrays.stream(staticLocations).map(this.resourceLoader::getResource) - .forEach(locations::add); + Arrays.stream(staticLocations).map(this.resourceLoader::getResource).forEach(locations::add); locations.add(new ClassPathResource("/")); return Collections.unmodifiableList(locations); } @@ -476,10 +444,8 @@ public class WebMvcAutoConfiguration { private final WebMvcRegistrations mvcRegistrations; - public EnableWebMvcConfiguration( - ObjectProvider mvcPropertiesProvider, - ObjectProvider mvcRegistrationsProvider, - ListableBeanFactory beanFactory) { + public EnableWebMvcConfiguration(ObjectProvider mvcPropertiesProvider, + ObjectProvider mvcRegistrationsProvider, ListableBeanFactory beanFactory) { this.mvcProperties = mvcPropertiesProvider.getIfAvailable(); this.mvcRegistrations = mvcRegistrationsProvider.getIfUnique(); this.beanFactory = beanFactory; @@ -489,19 +455,17 @@ public class WebMvcAutoConfiguration { @Override public RequestMappingHandlerAdapter requestMappingHandlerAdapter( ContentNegotiationManager mvcContentNegotiationManager, - FormattingConversionService mvcConversionService, - Validator mvcValidator) { - RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter( - mvcContentNegotiationManager, mvcConversionService, mvcValidator); - adapter.setIgnoreDefaultModelOnRedirect(this.mvcProperties == null - || this.mvcProperties.isIgnoreDefaultModelOnRedirect()); + FormattingConversionService mvcConversionService, Validator mvcValidator) { + RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(mvcContentNegotiationManager, + mvcConversionService, mvcValidator); + adapter.setIgnoreDefaultModelOnRedirect( + this.mvcProperties == null || this.mvcProperties.isIgnoreDefaultModelOnRedirect()); return adapter; } @Override protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() { - if (this.mvcRegistrations != null - && this.mvcRegistrations.getRequestMappingHandlerAdapter() != null) { + if (this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerAdapter() != null) { return this.mvcRegistrations.getRequestMappingHandlerAdapter(); } return super.createRequestMappingHandlerAdapter(); @@ -512,18 +476,16 @@ public class WebMvcAutoConfiguration { @Override public RequestMappingHandlerMapping requestMappingHandlerMapping( ContentNegotiationManager mvcContentNegotiationManager, - FormattingConversionService mvcConversionService, - ResourceUrlProvider mvcResourceUrlProvider) { + FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) { // Must be @Primary for MvcUriComponentsBuilder to work - return super.requestMappingHandlerMapping(mvcContentNegotiationManager, - mvcConversionService, mvcResourceUrlProvider); + return super.requestMappingHandlerMapping(mvcContentNegotiationManager, mvcConversionService, + mvcResourceUrlProvider); } @Bean @Override public FormattingConversionService mvcConversionService() { - WebConversionService conversionService = new WebConversionService( - this.mvcProperties.getDateFormat()); + WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat()); addFormatters(conversionService); return conversionService; } @@ -531,8 +493,7 @@ public class WebMvcAutoConfiguration { @Bean @Override public Validator mvcValidator() { - if (!ClassUtils.isPresent("javax.validation.Validator", - getClass().getClassLoader())) { + if (!ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { return super.mvcValidator(); } return ValidatorAdapter.get(getApplicationContext(), getValidator()); @@ -540,8 +501,7 @@ public class WebMvcAutoConfiguration { @Override protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() { - if (this.mvcRegistrations != null - && this.mvcRegistrations.getRequestMappingHandlerMapping() != null) { + if (this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerMapping() != null) { return this.mvcRegistrations.getRequestMappingHandlerMapping(); } return super.createRequestMappingHandlerMapping(); @@ -549,35 +509,30 @@ public class WebMvcAutoConfiguration { @Override protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer( - FormattingConversionService mvcConversionService, - Validator mvcValidator) { + FormattingConversionService mvcConversionService, Validator mvcValidator) { try { return this.beanFactory.getBean(ConfigurableWebBindingInitializer.class); } catch (NoSuchBeanDefinitionException ex) { - return super.getConfigurableWebBindingInitializer(mvcConversionService, - mvcValidator); + return super.getConfigurableWebBindingInitializer(mvcConversionService, mvcValidator); } } @Override protected ExceptionHandlerExceptionResolver createExceptionHandlerExceptionResolver() { - if (this.mvcRegistrations != null && this.mvcRegistrations - .getExceptionHandlerExceptionResolver() != null) { + if (this.mvcRegistrations != null && this.mvcRegistrations.getExceptionHandlerExceptionResolver() != null) { return this.mvcRegistrations.getExceptionHandlerExceptionResolver(); } return super.createExceptionHandlerExceptionResolver(); } @Override - protected void extendHandlerExceptionResolvers( - List exceptionResolvers) { + protected void extendHandlerExceptionResolvers(List exceptionResolvers) { super.extendHandlerExceptionResolvers(exceptionResolvers); if (this.mvcProperties.isLogResolvedException()) { for (HandlerExceptionResolver resolver : exceptionResolvers) { if (resolver instanceof AbstractHandlerExceptionResolver) { - ((AbstractHandlerExceptionResolver) resolver) - .setWarnLogCategory(resolver.getClass().getName()); + ((AbstractHandlerExceptionResolver) resolver).setWarnLogCategory(resolver.getClass().getName()); } } } @@ -592,8 +547,7 @@ public class WebMvcAutoConfiguration { while (iterator.hasNext()) { ContentNegotiationStrategy strategy = iterator.next(); if (strategy instanceof PathExtensionContentNegotiationStrategy) { - iterator.set(new OptionalPathExtensionContentNegotiationStrategy( - strategy)); + iterator.set(new OptionalPathExtensionContentNegotiationStrategy(strategy)); } } return manager; @@ -618,8 +572,7 @@ public class WebMvcAutoConfiguration { } - static class ResourceChainResourceHandlerRegistrationCustomizer - implements ResourceHandlerRegistrationCustomizer { + static class ResourceChainResourceHandlerRegistrationCustomizer implements ResourceHandlerRegistrationCustomizer { @Autowired private ResourceProperties resourceProperties = new ResourceProperties(); @@ -627,12 +580,10 @@ public class WebMvcAutoConfiguration { @Override public void customize(ResourceHandlerRegistration registration) { ResourceProperties.Chain properties = this.resourceProperties.getChain(); - configureResourceChain(properties, - registration.resourceChain(properties.isCache())); + configureResourceChain(properties, registration.resourceChain(properties.isCache())); } - private void configureResourceChain(ResourceProperties.Chain properties, - ResourceChainRegistration chain) { + private void configureResourceChain(ResourceProperties.Chain properties, ResourceChainRegistration chain) { Strategy strategy = properties.getStrategy(); if (properties.isCompressed()) { chain.addResolver(new EncodedResourceResolver()); @@ -645,8 +596,7 @@ public class WebMvcAutoConfiguration { } } - private ResourceResolver getVersionResourceResolver( - ResourceProperties.Strategy properties) { + private ResourceResolver getVersionResourceResolver(ResourceProperties.Strategy properties) { VersionResourceResolver resolver = new VersionResourceResolver(); if (properties.getFixed().isEnabled()) { String version = properties.getFixed().getVersion(); @@ -666,24 +616,20 @@ public class WebMvcAutoConfiguration { * Decorator to make {@link PathExtensionContentNegotiationStrategy} optional * depending on a request attribute. */ - static class OptionalPathExtensionContentNegotiationStrategy - implements ContentNegotiationStrategy { + static class OptionalPathExtensionContentNegotiationStrategy implements ContentNegotiationStrategy { - private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class.getName() + ".SKIP"; private final ContentNegotiationStrategy delegate; - OptionalPathExtensionContentNegotiationStrategy( - ContentNegotiationStrategy delegate) { + OptionalPathExtensionContentNegotiationStrategy(ContentNegotiationStrategy delegate) { this.delegate = delegate; } @Override public List resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { - Object skip = webRequest.getAttribute(SKIP_ATTRIBUTE, - RequestAttributes.SCOPE_REQUEST); + Object skip = webRequest.getAttribute(SKIP_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); if (skip != null && Boolean.parseBoolean(skip.toString())) { return MEDIA_TYPE_ALL_LIST; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java index 9e9145b001b..cb360da69f1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,8 +107,7 @@ public class WebMvcProperties { return this.messageCodesResolverFormat; } - public void setMessageCodesResolverFormat( - DefaultMessageCodesResolver.Format messageCodesResolverFormat) { + public void setMessageCodesResolverFormat(DefaultMessageCodesResolver.Format messageCodesResolverFormat) { this.messageCodesResolverFormat = messageCodesResolverFormat; } @@ -148,8 +147,7 @@ public class WebMvcProperties { return this.throwExceptionIfNoHandlerFound; } - public void setThrowExceptionIfNoHandlerFound( - boolean throwExceptionIfNoHandlerFound) { + public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) { this.throwExceptionIfNoHandlerFound = throwExceptionIfNoHandlerFound; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMapping.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMapping.java index dd4eca36d5d..7717a8a548e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMapping.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,28 +46,23 @@ final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping { private static final Log logger = LogFactory.getLog(WelcomePageHandlerMapping.class); - private static final List MEDIA_TYPES_ALL = Collections - .singletonList(MediaType.ALL); + private static final List MEDIA_TYPES_ALL = Collections.singletonList(MediaType.ALL); WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, - ApplicationContext applicationContext, Optional welcomePage, - String staticPathPattern) { + ApplicationContext applicationContext, Optional welcomePage, String staticPathPattern) { if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) { logger.info("Adding welcome page: " + welcomePage.get()); setRootViewName("forward:index.html"); } - else if (welcomeTemplateExists(templateAvailabilityProviders, - applicationContext)) { + else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) { logger.info("Adding welcome page template: index"); setRootViewName("index"); } } - private boolean welcomeTemplateExists( - TemplateAvailabilityProviders templateAvailabilityProviders, + private boolean welcomeTemplateExists(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext) { - return templateAvailabilityProviders.getProvider("index", - applicationContext) != null; + return templateAvailabilityProviders.getProvider("index", applicationContext) != null; } private void setRootViewName(String viewName) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/AbstractErrorController.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/AbstractErrorController.java index f6300eae603..afb2f3dc4f8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/AbstractErrorController.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/AbstractErrorController.java @@ -51,15 +51,13 @@ public abstract class AbstractErrorController implements ErrorController { this(errorAttributes, null); } - public AbstractErrorController(ErrorAttributes errorAttributes, - List errorViewResolvers) { + public AbstractErrorController(ErrorAttributes errorAttributes, List errorViewResolvers) { Assert.notNull(errorAttributes, "ErrorAttributes must not be null"); this.errorAttributes = errorAttributes; this.errorViewResolvers = sortErrorViewResolvers(errorViewResolvers); } - private List sortErrorViewResolvers( - List resolvers) { + private List sortErrorViewResolvers(List resolvers) { List sorted = new ArrayList<>(); if (resolvers != null) { sorted.addAll(resolvers); @@ -68,8 +66,7 @@ public abstract class AbstractErrorController implements ErrorController { return sorted; } - protected Map getErrorAttributes(HttpServletRequest request, - boolean includeStackTrace) { + protected Map getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { WebRequest webRequest = new ServletWebRequest(request); return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace); } @@ -83,8 +80,7 @@ public abstract class AbstractErrorController implements ErrorController { } protected HttpStatus getStatus(HttpServletRequest request) { - Integer statusCode = (Integer) request - .getAttribute("javax.servlet.error.status_code"); + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } @@ -107,8 +103,8 @@ public abstract class AbstractErrorController implements ErrorController { * used * @since 1.4.0 */ - protected ModelAndView resolveErrorView(HttpServletRequest request, - HttpServletResponse response, HttpStatus status, Map model) { + protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, + Map model) { for (ErrorViewResolver resolver : this.errorViewResolvers) { ModelAndView modelAndView = resolver.resolveErrorView(request, status, model); if (modelAndView != null) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java index 30cbe2d48d5..08fb13d56f8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java @@ -59,8 +59,7 @@ public class BasicErrorController extends AbstractErrorController { * @param errorAttributes the error attributes * @param errorProperties configuration properties */ - public BasicErrorController(ErrorAttributes errorAttributes, - ErrorProperties errorProperties) { + public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) { this(errorAttributes, errorProperties, Collections.emptyList()); } @@ -70,8 +69,8 @@ public class BasicErrorController extends AbstractErrorController { * @param errorProperties configuration properties * @param errorViewResolvers error view resolvers */ - public BasicErrorController(ErrorAttributes errorAttributes, - ErrorProperties errorProperties, List errorViewResolvers) { + public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, + List errorViewResolvers) { super(errorAttributes, errorViewResolvers); Assert.notNull(errorProperties, "ErrorProperties must not be null"); this.errorProperties = errorProperties; @@ -83,11 +82,10 @@ public class BasicErrorController extends AbstractErrorController { } @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) - public ModelAndView errorHtml(HttpServletRequest request, - HttpServletResponse response) { + public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); - Map model = Collections.unmodifiableMap(getErrorAttributes( - request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); + Map model = Collections + .unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); @@ -95,8 +93,7 @@ public class BasicErrorController extends AbstractErrorController { @RequestMapping public ResponseEntity> error(HttpServletRequest request) { - Map body = getErrorAttributes(request, - isIncludeStackTrace(request, MediaType.ALL)); + Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); return new ResponseEntity<>(body, status); } @@ -107,8 +104,7 @@ public class BasicErrorController extends AbstractErrorController { * @param produces the media type produced (or {@code MediaType.ALL}) * @return if the stacktrace attribute should be included */ - protected boolean isIncludeStackTrace(HttpServletRequest request, - MediaType produces) { + protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) { IncludeStacktrace include = getErrorProperties().getIncludeStacktrace(); if (include == IncludeStacktrace.ALWAYS) { return true; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolver.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolver.java index b2be1e840c7..b1181106d8f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolver.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,18 +79,15 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { * @param applicationContext the source application context * @param resourceProperties resource properties */ - public DefaultErrorViewResolver(ApplicationContext applicationContext, - ResourceProperties resourceProperties) { + public DefaultErrorViewResolver(ApplicationContext applicationContext, ResourceProperties resourceProperties) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(resourceProperties, "ResourceProperties must not be null"); this.applicationContext = applicationContext; this.resourceProperties = resourceProperties; - this.templateAvailabilityProviders = new TemplateAvailabilityProviders( - applicationContext); + this.templateAvailabilityProviders = new TemplateAvailabilityProviders(applicationContext); } - DefaultErrorViewResolver(ApplicationContext applicationContext, - ResourceProperties resourceProperties, + DefaultErrorViewResolver(ApplicationContext applicationContext, ResourceProperties resourceProperties, TemplateAvailabilityProviders templateAvailabilityProviders) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(resourceProperties, "ResourceProperties must not be null"); @@ -100,8 +97,7 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { } @Override - public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, - Map model) { + public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model) { ModelAndView modelAndView = resolve(String.valueOf(status.value()), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { modelAndView = resolve(SERIES_VIEWS.get(status.series()), model); @@ -111,8 +107,8 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { private ModelAndView resolve(String viewName, Map model) { String errorViewName = "error/" + viewName; - TemplateAvailabilityProvider provider = this.templateAvailabilityProviders - .getProvider(errorViewName, this.applicationContext); + TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, + this.applicationContext); if (provider != null) { return new ModelAndView(errorViewName, model); } @@ -160,11 +156,10 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { } @Override - public void render(Map model, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public void render(Map model, HttpServletRequest request, HttpServletResponse response) + throws Exception { response.setContentType(getContentType()); - FileCopyUtils.copy(this.resource.getInputStream(), - response.getOutputStream()); + FileCopyUtils.copy(this.resource.getInputStream(), response.getOutputStream()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java index 1db1e56bc35..c5d0e8ae9cd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java @@ -87,8 +87,7 @@ import org.springframework.web.util.HtmlUtils; @ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) // Load before the main WebMvcAutoConfiguration so that the error View is available @AutoConfigureBefore(WebMvcAutoConfiguration.class) -@EnableConfigurationProperties({ ServerProperties.class, ResourceProperties.class, - WebMvcProperties.class }) +@EnableConfigurationProperties({ ServerProperties.class, ResourceProperties.class, WebMvcProperties.class }) public class ErrorMvcAutoConfiguration { private final ServerProperties serverProperties; @@ -98,16 +97,13 @@ public class ErrorMvcAutoConfiguration { } @Bean - @ConditionalOnMissingBean(value = ErrorAttributes.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { - return new DefaultErrorAttributes( - this.serverProperties.getError().isIncludeException()); + return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException()); } @Bean - @ConditionalOnMissingBean(value = ErrorController.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, ObjectProvider errorViewResolvers) { return new BasicErrorController(errorAttributes, this.serverProperties.getError(), @@ -115,8 +111,7 @@ public class ErrorMvcAutoConfiguration { } @Bean - public ErrorPageCustomizer errorPageCustomizer( - DispatcherServletPath dispatcherServletPath) { + public ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) { return new ErrorPageCustomizer(this.serverProperties, dispatcherServletPath); } @@ -142,15 +137,13 @@ public class ErrorMvcAutoConfiguration { @ConditionalOnBean(DispatcherServlet.class) @ConditionalOnMissingBean public DefaultErrorViewResolver conventionErrorViewResolver() { - return new DefaultErrorViewResolver(this.applicationContext, - this.resourceProperties); + return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties); } } @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true) @Conditional(ErrorTemplateMissingCondition.class) protected static class WhitelabelErrorViewConfiguration { @@ -180,21 +173,15 @@ public class ErrorMvcAutoConfiguration { private static class ErrorTemplateMissingCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("ErrorTemplate Missing"); - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - context.getClassLoader()); - TemplateAvailabilityProvider provider = providers.getProvider("error", - context.getEnvironment(), context.getClassLoader(), - context.getResourceLoader()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("ErrorTemplate Missing"); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(context.getClassLoader()); + TemplateAvailabilityProvider provider = providers.getProvider("error", context.getEnvironment(), + context.getClassLoader(), context.getResourceLoader()); if (provider != null) { - return ConditionOutcome - .noMatch(message.foundExactly("template from " + provider)); + return ConditionOutcome.noMatch(message.foundExactly("template from " + provider)); } - return ConditionOutcome - .match(message.didNotFind("error template view").atAll()); + return ConditionOutcome.match(message.didNotFind("error template view").atAll()); } } @@ -204,14 +191,13 @@ public class ErrorMvcAutoConfiguration { */ private static class StaticView implements View { - private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", - StandardCharsets.UTF_8); + private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8); private static final Log logger = LogFactory.getLog(StaticView.class); @Override - public void render(Map model, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public void render(Map model, HttpServletRequest request, HttpServletResponse response) + throws Exception { if (response.isCommitted()) { String message = getMessage(model); logger.error(message); @@ -228,15 +214,13 @@ public class ErrorMvcAutoConfiguration { builder.append("

    Whitelabel Error Page

    ").append( "

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    ") .append("
    ").append(timestamp).append("
    ") - .append("
    There was an unexpected error (type=") - .append(htmlEscape(model.get("error"))).append(", status=") - .append(htmlEscape(model.get("status"))).append(").
    "); + .append("
    There was an unexpected error (type=").append(htmlEscape(model.get("error"))) + .append(", status=").append(htmlEscape(model.get("status"))).append(").
    "); if (message != null) { builder.append("
    ").append(htmlEscape(message)).append("
    "); } if (trace != null) { - builder.append("
    ") - .append(htmlEscape(trace)).append("
    "); + builder.append("
    ").append(htmlEscape(trace)).append("
    "); } builder.append(""); response.getWriter().append(builder.toString()); @@ -273,16 +257,15 @@ public class ErrorMvcAutoConfiguration { private final DispatcherServletPath dispatcherServletPath; - protected ErrorPageCustomizer(ServerProperties properties, - DispatcherServletPath dispatcherServletPath) { + protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) { this.properties = properties; this.dispatcherServletPath = dispatcherServletPath; } @Override public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { - ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath - .getRelativePath(this.properties.getError().getPath())); + ErrorPage errorPage = new ErrorPage( + this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath())); errorPageRegistry.addErrorPages(errorPage); } @@ -297,18 +280,15 @@ public class ErrorMvcAutoConfiguration { * {@link BeanFactoryPostProcessor} to ensure that the target class of ErrorController * MVC beans are preserved when using AOP. */ - static class PreserveErrorControllerTargetClassPostProcessor - implements BeanFactoryPostProcessor { + static class PreserveErrorControllerTargetClassPostProcessor implements BeanFactoryPostProcessor { @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] errorControllerBeans = beanFactory - .getBeanNamesForType(ErrorController.class, false, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] errorControllerBeans = beanFactory.getBeanNamesForType(ErrorController.class, false, false); for (String errorControllerBean : errorControllerBeans) { try { - beanFactory.getBeanDefinition(errorControllerBean).setAttribute( - AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); + beanFactory.getBeanDefinition(errorControllerBean) + .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); } catch (Throwable ex) { // Ignore diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorViewResolver.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorViewResolver.java index 5c7cbaece0b..bc84e5d0f9d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorViewResolver.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,6 @@ public interface ErrorViewResolver { * @param model the suggested model to be used with the view * @return a resolved {@link ModelAndView} or {@code null} */ - ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, - Map model); + ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsCondition.java index a595057d7f1..350fc5ddbcd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.boot.autoconfigure.condition.OnPropertyListCondition; class OnWsdlLocationsCondition extends OnPropertyListCondition { OnWsdlLocationsCondition() { - super("spring.webservices.wsdl-locations", - () -> ConditionMessage.forCondition("WSDL locations")); + super("spring.webservices.wsdl-locations", () -> ConditionMessage.forCondition("WSDL locations")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java index 31b4f5f0844..37c6893ff38 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java @@ -73,8 +73,8 @@ public class WebServicesAutoConfiguration { servlet.setApplicationContext(applicationContext); String path = properties.getPath(); String urlMapping = path + (path.endsWith("/") ? "*" : "/*"); - ServletRegistrationBean registration = new ServletRegistrationBean<>( - servlet, urlMapping); + ServletRegistrationBean registration = new ServletRegistrationBean<>(servlet, + urlMapping); WebServicesProperties.Servlet servletProperties = properties.getServlet(); registration.setLoadOnStartup(servletProperties.getLoadOnStartup()); servletProperties.getInit().forEach(registration::addInitParameter); @@ -104,42 +104,34 @@ public class WebServicesAutoConfiguration { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Binder binder = Binder.get(this.applicationContext.getEnvironment()); - List wsdlLocations = binder - .bind("spring.webservices.wsdl-locations", - Bindable.listOf(String.class)) + List wsdlLocations = binder.bind("spring.webservices.wsdl-locations", Bindable.listOf(String.class)) .orElse(Collections.emptyList()); for (String wsdlLocation : wsdlLocations) { - registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, - SimpleWsdl11Definition::new, registry); - registerBeans(wsdlLocation, "*.xsd", SimpleXsdSchema.class, - SimpleXsdSchema::new, registry); + registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, SimpleWsdl11Definition::new, + registry); + registerBeans(wsdlLocation, "*.xsd", SimpleXsdSchema.class, SimpleXsdSchema::new, registry); } } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } private void registerBeans(String location, String pattern, Class type, Function beanSupplier, BeanDefinitionRegistry registry) { for (Resource resource : getResources(location, pattern)) { BeanDefinition beanDefinition = BeanDefinitionBuilder - .genericBeanDefinition(type, () -> beanSupplier.apply(resource)) - .getBeanDefinition(); - registry.registerBeanDefinition( - StringUtils.stripFilenameExtension(resource.getFilename()), + .genericBeanDefinition(type, () -> beanSupplier.apply(resource)).getBeanDefinition(); + registry.registerBeanDefinition(StringUtils.stripFilenameExtension(resource.getFilename()), beanDefinition); } } private Resource[] getResources(String location, String pattern) { try { - return this.applicationContext - .getResources(ensureTrailingSlash(location) + pattern); + return this.applicationContext.getResources(ensureTrailingSlash(location) + pattern); } catch (IOException ex) { return new Resource[0]; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java index e037724603f..42384bfa572 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java @@ -46,8 +46,8 @@ public class WebServiceTemplateAutoConfiguration { public WebServiceTemplateBuilder webServiceTemplateBuilder( ObjectProvider webServiceTemplateCustomizers) { WebServiceTemplateBuilder builder = new WebServiceTemplateBuilder(); - List customizers = webServiceTemplateCustomizers - .orderedStream().collect(Collectors.toList()); + List customizers = webServiceTemplateCustomizers.orderedStream() + .collect(Collectors.toList()); if (!customizers.isEmpty()) { builder = builder.customizers(customizers); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java index 6e37ac3a0e7..da424560d1d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class TomcatWebSocketReactiveWebServerCustomizer @Override public void customize(TomcatReactiveWebServerFactory factory) { - factory.addContextCustomizers((context) -> context - .addApplicationListener(WsContextListener.class.getName())); + factory.addContextCustomizers((context) -> context.addApplicationListener(WsContextListener.class.getName())); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/JettyWebSocketServletWebServerCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/JettyWebSocketServletWebServerCustomizer.java index 96bc864a9bf..1d514dc2556 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/JettyWebSocketServletWebServerCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/JettyWebSocketServletWebServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class JettyWebSocketServletWebServerCustomizer @Override public void configure(WebAppContext context) throws Exception { - ServerContainer serverContainer = WebSocketServerContainerInitializer - .configureContext(context); + ServerContainer serverContainer = WebSocketServerContainerInitializer.configureContext(context); ShutdownThread.deregister(serverContainer); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/TomcatWebSocketServletWebServerCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/TomcatWebSocketServletWebServerCustomizer.java index b453458eebd..86c33f81581 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/TomcatWebSocketServletWebServerCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/TomcatWebSocketServletWebServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class TomcatWebSocketServletWebServerCustomizer @Override public void customize(TomcatServletWebServerFactory factory) { - factory.addContextCustomizers((context) -> context - .addApplicationListener(WsContextListener.class.getName())); + factory.addContextCustomizers((context) -> context.addApplicationListener(WsContextListener.class.getName())); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/UndertowWebSocketServletWebServerCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/UndertowWebSocketServletWebServerCustomizer.java index 8eaa6e8137c..d8b7fdb8c94 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/UndertowWebSocketServletWebServerCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/UndertowWebSocketServletWebServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,14 +44,12 @@ public class UndertowWebSocketServletWebServerCustomizer return 0; } - private static class WebsocketDeploymentInfoCustomizer - implements UndertowDeploymentInfoCustomizer { + private static class WebsocketDeploymentInfoCustomizer implements UndertowDeploymentInfoCustomizer { @Override public void customize(DeploymentInfo deploymentInfo) { WebSocketDeploymentInfo info = new WebSocketDeploymentInfo(); - deploymentInfo.addServletContextAttribute( - WebSocketDeploymentInfo.ATTRIBUTE_NAME, info); + deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, info); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfiguration.java index f9ad5c66086..902d37f40f6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfiguration.java @@ -51,11 +51,9 @@ import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerCo public class WebSocketMessagingAutoConfiguration { @Configuration(proxyBeanMethods = false) - @ConditionalOnBean({ DelegatingWebSocketMessageBrokerConfiguration.class, - ObjectMapper.class }) + @ConditionalOnBean({ DelegatingWebSocketMessageBrokerConfiguration.class, ObjectMapper.class }) @ConditionalOnClass({ ObjectMapper.class, AbstractMessageBrokerConfiguration.class }) - static class WebSocketMessageConverterConfiguration - implements WebSocketMessageBrokerConfigurer { + static class WebSocketMessageConverterConfiguration implements WebSocketMessageBrokerConfigurer { private final ObjectMapper objectMapper; @@ -64,8 +62,7 @@ public class WebSocketMessagingAutoConfiguration { } @Override - public boolean configureMessageConverters( - List messageConverters) { + public boolean configureMessageConverters(List messageConverters) { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setObjectMapper(this.objectMapper); DefaultContentTypeResolver resolver = new DefaultContentTypeResolver(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java index 88ad7cd5a7a..880ef6eb177 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorContro * @author Dave Syer */ @RunWith(Suite.class) -@SuiteClasses({ BasicErrorControllerDirectMockMvcTests.class, - JmxAutoConfigurationTests.class, IntegrationAutoConfigurationTests.class }) +@SuiteClasses({ BasicErrorControllerDirectMockMvcTests.class, JmxAutoConfigurationTests.class, + IntegrationAutoConfigurationTests.class }) @Ignore public class AdhocTestSuite { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java index c463bd33791..f322cadad75 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java @@ -56,8 +56,7 @@ public class AutoConfigurationExcludeFilterTests { this.context = new AnnotationConfigApplicationContext(Config.class); assertThat(this.context.getBeansOfType(String.class)).hasSize(1); assertThat(this.context.getBean(String.class)).isEqualTo("test"); - assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(FILTERED)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> this.context.getBean(FILTERED)); } @Configuration(proxyBeanMethods = false) @@ -68,8 +67,7 @@ public class AutoConfigurationExcludeFilterTests { } - static class TestAutoConfigurationExcludeFilter - extends AutoConfigurationExcludeFilter { + static class TestAutoConfigurationExcludeFilter extends AutoConfigurationExcludeFilter { @Override protected List getAutoConfigurations() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java index e6fbad151e5..16f490201f0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java @@ -46,29 +46,25 @@ public class AutoConfigurationImportSelectorIntegrationTests { @Test public void singleSelector() { this.contextRunner.withUserConfiguration(SingleConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)) - .containsExactly("ConfigC")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigC")); } @Test public void multipleSelectorsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(Config.class, AnotherConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)) - .containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD")); } @Test public void multipleSelectorsWithRedundantImportsShouldMergeAndSortCorrectly() { - this.contextRunner - .withUserConfiguration(SingleConfig.class, Config.class, - AnotherConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)) - .containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD")); + this.contextRunner.withUserConfiguration(SingleConfig.class, Config.class, AnotherConfig.class) + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD")); } private List getImportedConfigBeans(AssertableApplicationContext context) { - String shortName = ClassUtils - .getShortName(AutoConfigurationImportSelectorIntegrationTests.class); + String shortName = ClassUtils.getShortName(AutoConfigurationImportSelectorIntegrationTests.class); int beginIndex = shortName.length() + 1; List orderedConfigBeans = new ArrayList<>(); for (String bean : context.getBeanDefinitionNames()) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index 9e53aa47d8e..ab4e0cbc2ec 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -71,15 +71,14 @@ public class AutoConfigurationImportSelectorTests { @Test public void importsAreSelectedWhenUsingEnableAutoConfiguration() { String[] imports = selectImports(BasicEnableAutoConfiguration.class); - assertThat(imports).hasSameSizeAs(SpringFactoriesLoader.loadFactoryNames( - EnableAutoConfiguration.class, getClass().getClassLoader())); + assertThat(imports).hasSameSizeAs( + SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, getClass().getClassLoader())); assertThat(this.importSelector.getLastEvent().getExclusions()).isEmpty(); } @Test public void classExclusionsAreApplied() { - String[] imports = selectImports( - EnableAutoConfigurationWithClassExclusions.class); + String[] imports = selectImports(EnableAutoConfigurationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) .contains(FreeMarkerAutoConfiguration.class.getName()); @@ -95,8 +94,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void classNamesExclusionsAreApplied() { - String[] imports = selectImports( - EnableAutoConfigurationWithClassNameExclusions.class); + String[] imports = selectImports(EnableAutoConfigurationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) .contains(MustacheAutoConfiguration.class.getName()); @@ -104,8 +102,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void classNamesExclusionsAreAppliedWhenUsingSpringBootApplication() { - String[] imports = selectImports( - SpringBootApplicationWithClassNameExclusions.class); + String[] imports = selectImports(SpringBootApplicationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) .contains(MustacheAutoConfiguration.class.getName()); @@ -113,8 +110,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void propertyExclusionsAreApplied() { - this.environment.setProperty("spring.autoconfigure.exclude", - FreeMarkerAutoConfiguration.class.getName()); + this.environment.setProperty("spring.autoconfigure.exclude", FreeMarkerAutoConfiguration.class.getName()); String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) @@ -124,68 +120,58 @@ public class AutoConfigurationImportSelectorTests { @Test public void severalPropertyExclusionsAreApplied() { this.environment.setProperty("spring.autoconfigure.exclude", - FreeMarkerAutoConfiguration.class.getName() + "," - + MustacheAutoConfiguration.class.getName()); + FreeMarkerAutoConfiguration.class.getName() + "," + MustacheAutoConfiguration.class.getName()); testSeveralPropertyExclusionsAreApplied(); } @Test public void severalPropertyExclusionsAreAppliedWithExtraSpaces() { this.environment.setProperty("spring.autoconfigure.exclude", - FreeMarkerAutoConfiguration.class.getName() + " , " - + MustacheAutoConfiguration.class.getName() + " "); + FreeMarkerAutoConfiguration.class.getName() + " , " + MustacheAutoConfiguration.class.getName() + " "); testSeveralPropertyExclusionsAreApplied(); } @Test public void severalPropertyYamlExclusionsAreApplied() { - this.environment.setProperty("spring.autoconfigure.exclude[0]", - FreeMarkerAutoConfiguration.class.getName()); - this.environment.setProperty("spring.autoconfigure.exclude[1]", - MustacheAutoConfiguration.class.getName()); + this.environment.setProperty("spring.autoconfigure.exclude[0]", FreeMarkerAutoConfiguration.class.getName()); + this.environment.setProperty("spring.autoconfigure.exclude[1]", MustacheAutoConfiguration.class.getName()); testSeveralPropertyExclusionsAreApplied(); } private void testSeveralPropertyExclusionsAreApplied() { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 2); - assertThat(this.importSelector.getLastEvent().getExclusions()).contains( - FreeMarkerAutoConfiguration.class.getName(), - MustacheAutoConfiguration.class.getName()); + assertThat(this.importSelector.getLastEvent().getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName()); } @Test public void combinedExclusionsAreApplied() { - this.environment.setProperty("spring.autoconfigure.exclude", - ThymeleafAutoConfiguration.class.getName()); - String[] imports = selectImports( - EnableAutoConfigurationWithClassAndClassNameExclusions.class); + this.environment.setProperty("spring.autoconfigure.exclude", ThymeleafAutoConfiguration.class.getName()); + String[] imports = selectImports(EnableAutoConfigurationWithClassAndClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 3); assertThat(this.importSelector.getLastEvent().getExclusions()).contains( - FreeMarkerAutoConfiguration.class.getName(), - MustacheAutoConfiguration.class.getName(), + FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName(), ThymeleafAutoConfiguration.class.getName()); } @Test public void nonAutoConfigurationClassExclusionsShouldThrowException() { - assertThatIllegalStateException().isThrownBy( - () -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); + assertThatIllegalStateException() + .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); } @Test public void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() { - assertThatIllegalStateException().isThrownBy(() -> selectImports( - EnableAutoConfigurationWithFaultyClassNameExclude.class)); + assertThatIllegalStateException() + .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class)); } @Test public void nonAutoConfigurationPropertyExclusionsWhenPresentOnClassPathShouldThrowException() { this.environment.setProperty("spring.autoconfigure.exclude", - "org.springframework.boot.autoconfigure." - + "AutoConfigurationImportSelectorTests.TestConfiguration"); - assertThatIllegalStateException() - .isThrownBy(() -> selectImports(BasicEnableAutoConfiguration.class)); + "org.springframework.boot.autoconfigure." + "AutoConfigurationImportSelectorTests.TestConfiguration"); + assertThatIllegalStateException().isThrownBy(() -> selectImports(BasicEnableAutoConfiguration.class)); } @Test @@ -193,10 +179,9 @@ public class AutoConfigurationImportSelectorTests { this.environment.setProperty("spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure.DoesNotExist2"); selectImports(EnableAutoConfigurationWithAbsentClassNameExclude.class); - assertThat(this.importSelector.getLastEvent().getExclusions()) - .containsExactlyInAnyOrder( - "org.springframework.boot.autoconfigure.DoesNotExist1", - "org.springframework.boot.autoconfigure.DoesNotExist2"); + assertThat(this.importSelector.getLastEvent().getExclusions()).containsExactlyInAnyOrder( + "org.springframework.boot.autoconfigure.DoesNotExist1", + "org.springframework.boot.autoconfigure.DoesNotExist2"); } @Test @@ -206,14 +191,12 @@ public class AutoConfigurationImportSelectorTests { this.filters.add(new TestAutoConfigurationImportFilter(defaultImports, 3, 4)); String[] filtered = selectImports(BasicEnableAutoConfiguration.class); assertThat(filtered).hasSize(defaultImports.length - 3); - assertThat(filtered).doesNotContain(defaultImports[1], defaultImports[3], - defaultImports[4]); + assertThat(filtered).doesNotContain(defaultImports[1], defaultImports[3], defaultImports[4]); } @Test public void filterShouldSupportAware() { - TestAutoConfigurationImportFilter filter = new TestAutoConfigurationImportFilter( - new String[] {}); + TestAutoConfigurationImportFilter filter = new TestAutoConfigurationImportFilter(new String[] {}); this.filters.add(filter); selectImports(BasicEnableAutoConfiguration.class); assertThat(filter.getBeanFactory()).isEqualTo(this.beanFactory); @@ -224,12 +207,10 @@ public class AutoConfigurationImportSelectorTests { } private List getAutoConfigurationClassNames() { - return SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, - getClass().getClassLoader()); + return SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, getClass().getClassLoader()); } - private class TestAutoConfigurationImportSelector - extends AutoConfigurationImportSelector { + private class TestAutoConfigurationImportSelector extends AutoConfigurationImportSelector { private AutoConfigurationImportEvent lastEvent; @@ -249,8 +230,7 @@ public class AutoConfigurationImportSelectorTests { } - private static class TestAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, BeanFactoryAware { + private static class TestAutoConfigurationImportFilter implements AutoConfigurationImportFilter, BeanFactoryAware { private final Set nonMatching = new HashSet<>(); @@ -263,8 +243,7 @@ public class AutoConfigurationImportSelectorTests { } @Override - public boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata) { + public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { boolean[] result = new boolean[autoConfigurationClasses.length]; for (int i = 0; i < result.length; i++) { result[i] = !this.nonMatching.contains(autoConfigurationClasses[i]); @@ -303,8 +282,7 @@ public class AutoConfigurationImportSelectorTests { } - @EnableAutoConfiguration( - excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") + @EnableAutoConfiguration(excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") private class EnableAutoConfigurationWithClassNameExclusions { } @@ -326,14 +304,12 @@ public class AutoConfigurationImportSelectorTests { } - @EnableAutoConfiguration( - excludeName = "org.springframework.boot.autoconfigure.DoesNotExist1") + @EnableAutoConfiguration(excludeName = "org.springframework.boot.autoconfigure.DoesNotExist1") private class EnableAutoConfigurationWithAbsentClassNameExclude { } - @SpringBootApplication( - excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") + @SpringBootApplication(excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") private class SpringBootApplicationWithClassNameExclusions { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java index 69843ca6a66..e2ec8ed55eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java @@ -71,8 +71,7 @@ public class AutoConfigurationMetadataLoaderTests { @Test public void getSetWithDefaultWhenMissingShouldReturnDefault() { - assertThat(load().getSet("test", "setx", Collections.singleton("x"))) - .containsExactly("x"); + assertThat(load().getSet("test", "setx", Collections.singleton("x"))).containsExactly("x"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index 9359d740611..8c0b08ca6b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -41,26 +41,22 @@ public class AutoConfigurationPackagesTests { @Test public void setAndGet() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ConfigWithRegistrar.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithRegistrar.class); assertThat(AutoConfigurationPackages.get(context.getBeanFactory())) .containsExactly(getClass().getPackage().getName()); } @Test public void getWithoutSet() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - EmptyConfig.class); - assertThatIllegalStateException() - .isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory())) - .withMessageContaining( - "Unable to retrieve @EnableAutoConfiguration base packages"); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfig.class); + assertThatIllegalStateException().isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory())) + .withMessageContaining("Unable to retrieve @EnableAutoConfiguration base packages"); } @Test public void detectsMultipleAutoConfigurationPackages() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - FirstConfiguration.class, SecondConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FirstConfiguration.class, + SecondConfiguration.class); List packages = AutoConfigurationPackages.get(context.getBeanFactory()); Package package1 = FirstConfiguration.class.getPackage(); Package package2 = SecondConfiguration.class.getPackage(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java index 1b2894cfc4a..8e2bdda9e7b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java @@ -47,8 +47,7 @@ public class AutoConfigurationReproTests { @Test public void doesNotEarlyInitializeFactoryBeans() { SpringApplication application = new SpringApplication(EarlyInitConfig.class, - PropertySourcesPlaceholderConfigurer.class, - ServletWebServerFactoryAutoConfiguration.class); + PropertySourcesPlaceholderConfigurer.class, ServletWebServerFactoryAutoConfiguration.class); this.context = application.run("--server.port=0"); String bean = (String) this.context.getBean("earlyInit"); assertThat(bean).isEqualTo("bucket"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index 99f4b3eba0a..3aa34df0ec6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -75,19 +75,16 @@ public class AutoConfigurationSorterTests { private AutoConfigurationSorter sorter; - private AutoConfigurationMetadata autoConfigurationMetadata = mock( - AutoConfigurationMetadata.class); + private AutoConfigurationMetadata autoConfigurationMetadata = mock(AutoConfigurationMetadata.class); @BeforeEach public void setup() { - this.sorter = new AutoConfigurationSorter(new SkipCycleMetadataReaderFactory(), - this.autoConfigurationMetadata); + this.sorter = new AutoConfigurationSorter(new SkipCycleMetadataReaderFactory(), this.autoConfigurationMetadata); } @Test public void byOrderAnnotation() { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(LOWEST, HIGHEST, DEFAULT)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(LOWEST, HIGHEST, DEFAULT)); assertThat(actual).containsExactly(HIGHEST, DEFAULT, LOWEST); } @@ -111,22 +108,19 @@ public class AutoConfigurationSorterTests { @Test public void byAutoConfigureMixedBeforeAndAfter() { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(A, B, C, W, X)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, W, X)); assertThat(actual).containsExactly(C, W, B, A, X); } @Test public void byAutoConfigureMixedBeforeAndAfterWithClassNames() { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); assertThat(actual).containsExactly(C, W2, B, A2, X); } @Test public void byAutoConfigureMixedBeforeAndAfterWithDifferentInputOrder() { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(W, X, A, B, C)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(W, X, A, B, C)); assertThat(actual).containsExactly(C, W, B, A, X); } @@ -138,11 +132,8 @@ public class AutoConfigurationSorterTests { @Test public void byAutoConfigureAfterWithCycle() { - this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), - this.autoConfigurationMetadata); - assertThatIllegalStateException() - .isThrownBy( - () -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D))) + this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); + assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D))) .withMessageContaining("AutoConfigure cycle detected"); } @@ -150,10 +141,8 @@ public class AutoConfigurationSorterTests { public void usesAnnotationPropertiesWhenPossible() throws Exception { MetadataReaderFactory readerFactory = new SkipCycleMetadataReaderFactory(); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A2, B, C, W2, X); - this.sorter = new AutoConfigurationSorter(readerFactory, - this.autoConfigurationMetadata); - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); + this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); assertThat(actual).containsExactly(C, W2, B, A2, X); } @@ -161,8 +150,7 @@ public class AutoConfigurationSorterTests { public void useAnnotationWithNoDirectLink() throws Exception { MetadataReaderFactory readerFactory = new SkipCycleMetadataReaderFactory(); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, E); - this.sorter = new AutoConfigurationSorter(readerFactory, - this.autoConfigurationMetadata); + this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, E)); assertThat(actual).containsExactly(E, A); } @@ -171,33 +159,26 @@ public class AutoConfigurationSorterTests { public void useAnnotationWithNoDirectLinkAndCycle() throws Exception { MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, D); - this.sorter = new AutoConfigurationSorter(readerFactory, - this.autoConfigurationMetadata); - assertThatIllegalStateException() - .isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(D, B))) + this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); + assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(D, B))) .withMessageContaining("AutoConfigure cycle detected"); } - private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) - throws Exception { + private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) throws Exception { Properties properties = new Properties(); for (String className : classNames) { Class type = ClassUtils.forName(className, null); properties.put(type.getName(), ""); - AutoConfigureOrder order = type - .getDeclaredAnnotation(AutoConfigureOrder.class); + AutoConfigureOrder order = type.getDeclaredAnnotation(AutoConfigureOrder.class); if (order != null) { - properties.put(className + ".AutoConfigureOrder", - String.valueOf(order.value())); + properties.put(className + ".AutoConfigureOrder", String.valueOf(order.value())); } - AutoConfigureBefore autoConfigureBefore = type - .getDeclaredAnnotation(AutoConfigureBefore.class); + AutoConfigureBefore autoConfigureBefore = type.getDeclaredAnnotation(AutoConfigureBefore.class); if (autoConfigureBefore != null) { properties.put(className + ".AutoConfigureBefore", merge(autoConfigureBefore.value(), autoConfigureBefore.name())); } - AutoConfigureAfter autoConfigureAfter = type - .getDeclaredAnnotation(AutoConfigureAfter.class); + AutoConfigureAfter autoConfigureAfter = type.getDeclaredAnnotation(AutoConfigureAfter.class); if (autoConfigureAfter != null) { properties.put(className + ".AutoConfigureAfter", merge(autoConfigureAfter.value(), autoConfigureAfter.name())); @@ -237,14 +218,12 @@ public class AutoConfigurationSorterTests { } - @AutoConfigureAfter( - name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") + @AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureA2 { } - @AutoConfigureAfter({ AutoConfigureC.class, AutoConfigureD.class, - AutoConfigureE.class }) + @AutoConfigureAfter({ AutoConfigureC.class, AutoConfigureD.class, AutoConfigureE.class }) public static class AutoConfigureB { } @@ -267,8 +246,7 @@ public class AutoConfigurationSorterTests { } - @AutoConfigureBefore( - name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") + @AutoConfigureBefore(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureW2 { } @@ -287,8 +265,7 @@ public class AutoConfigurationSorterTests { } - private static class SkipCycleMetadataReaderFactory - extends CachingMetadataReaderFactory { + private static class SkipCycleMetadataReaderFactory extends CachingMetadataReaderFactory { @Override public MetadataReader getMetadataReader(String className) throws IOException { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java index 70043207ab0..1df5f76eb85 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java @@ -31,10 +31,9 @@ public class AutoConfigurationsTests { @Test public void ofShouldCreateOrderedConfigurations() { - Configurations configurations = AutoConfigurations.of(AutoConfigureA.class, - AutoConfigureB.class); - assertThat(Configurations.getClasses(configurations)) - .containsExactly(AutoConfigureB.class, AutoConfigureA.class); + Configurations configurations = AutoConfigurations.of(AutoConfigureA.class, AutoConfigureB.class); + assertThat(Configurations.getClasses(configurations)).containsExactly(AutoConfigureB.class, + AutoConfigureA.class); } @AutoConfigureAfter(AutoConfigureB.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java index 4f0f746edc4..ebc93d7e279 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import org.springframework.boot.testsupport.context.AbstractConfigurationClassTe * * @author Andy Wilkinson */ -public class AutoConfigureConfigurationClassTests - extends AbstractConfigurationClassTests { +public class AutoConfigureConfigurationClassTests extends AbstractConfigurationClassTests { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java index d17b5b54a5b..f8cd55ad67f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java @@ -67,32 +67,28 @@ public class ImportAutoConfigurationImportSelectorTests { @Test public void importsAreSelected() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportFreeMarker.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarker.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsExactly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void importsAreSelectedUsingClassesAttribute() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportFreeMarkerUsingClassesAttribute.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarkerUsingClassesAttribute.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsExactly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void propertyExclusionsAreNotApplied() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportFreeMarker.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarker.class); this.importSelector.selectImports(annotationMetadata); verifyZeroInteractions(this.environment); } @Test public void multipleImportsAreFound() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - MultipleImports.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImports.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName(), ThymeleafAutoConfiguration.class.getName()); @@ -100,104 +96,92 @@ public class ImportAutoConfigurationImportSelectorTests { @Test public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() throws IOException { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportWithSelfAnnotatingAnnotation.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotation.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(ThymeleafAutoConfiguration.class.getName()); } @Test public void exclusionsAreApplied() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - MultipleImportsWithExclusion.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImportsWithExclusion.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void exclusionsWithoutImport() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ExclusionWithoutImport.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ExclusionWithoutImport.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void exclusionsAliasesAreApplied() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportWithSelfAnnotatingAnnotationExclude.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotationExclude.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).isEmpty(); } @Test - public void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() - throws Exception { - Set set1 = this.importSelector.determineImports( - getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + public void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1.hashCode()).isEqualTo(set2.hashCode()); } @Test - public void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() - throws Exception { - Set set1 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); + public void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); } @Test - public void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() - throws Exception { - Set set1 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); + public void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); assertThat(set1).isEqualTo(set2); } @Test - public void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() - throws Exception { - Set set1 = this.importSelector.determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); + public void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1.hashCode()).isEqualTo(set2.hashCode()); } @Test - public void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() - throws Exception { - Set set1 = this.importSelector.determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + public void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isNotEqualTo(set2); } @Test public void determineImportsShouldNotSetPackageImport() throws Exception { Class packageImportClass = ClassUtils.resolveClassName( - "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImport", - null); + "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImport", null); Set selectedImports = this.importSelector - .determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); for (Object selectedImport : selectedImports) { assertThat(selectedImport).isNotInstanceOf(packageImportClass); } } private AnnotationMetadata getAnnotationMetadata(Class source) throws IOException { - return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()) - .getAnnotationMetadata(); + return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()).getAnnotationMetadata(); } @ImportAutoConfiguration(FreeMarkerAutoConfiguration.class) @@ -328,8 +312,7 @@ public class ImportAutoConfigurationImportSelectorTests { } - private static class TestImportAutoConfigurationImportSelector - extends ImportAutoConfigurationImportSelector { + private static class TestImportAutoConfigurationImportSelector extends ImportAutoConfigurationImportSelector { @Override protected Collection loadFactoryNames(Class source) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java index d3e919777a4..c0659a7c589 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java @@ -38,39 +38,34 @@ public class ImportAutoConfigurationTests { @Test public void multipleAnnotationsShouldMergeCorrectly() { - assertThat(getImportedConfigBeans(Config.class)).containsExactly("ConfigA", - "ConfigB", "ConfigC", "ConfigD"); - assertThat(getImportedConfigBeans(AnotherConfig.class)).containsExactly("ConfigA", - "ConfigB", "ConfigC", "ConfigD"); + assertThat(getImportedConfigBeans(Config.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); + assertThat(getImportedConfigBeans(AnotherConfig.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", + "ConfigD"); } @Test public void classesAsAnAlias() { - assertThat(getImportedConfigBeans(AnotherConfigUsingClasses.class)) - .containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); + assertThat(getImportedConfigBeans(AnotherConfigUsingClasses.class)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD"); } @Test public void excluding() { - assertThat(getImportedConfigBeans(ExcludingConfig.class)) - .containsExactly("ConfigA", "ConfigB", "ConfigD"); + assertThat(getImportedConfigBeans(ExcludingConfig.class)).containsExactly("ConfigA", "ConfigB", "ConfigD"); } @Test public void excludeAppliedGlobally() { - assertThat(getImportedConfigBeans(ExcludeDConfig.class, ImportADConfig.class)) - .containsExactly("ConfigA"); + assertThat(getImportedConfigBeans(ExcludeDConfig.class, ImportADConfig.class)).containsExactly("ConfigA"); } @Test public void excludeWithRedundancy() { - assertThat(getImportedConfigBeans(ExcludeADConfig.class, ExcludeDConfig.class, - ImportADConfig.class)).isEmpty(); + assertThat(getImportedConfigBeans(ExcludeADConfig.class, ExcludeDConfig.class, ImportADConfig.class)).isEmpty(); } private List getImportedConfigBeans(Class... config) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - config); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(config); String shortName = ClassUtils.getShortName(ImportAutoConfigurationTests.class); int beginIndex = shortName.length() + 1; List orderedConfigBeans = new ArrayList<>(); @@ -102,8 +97,7 @@ public class ImportAutoConfigurationTests { } - @ImportAutoConfiguration(classes = { ConfigD.class, ConfigB.class }, - exclude = ConfigC.class) + @ImportAutoConfiguration(classes = { ConfigD.class, ConfigB.class }, exclude = ConfigC.class) @MetaImportAutoConfiguration static class ExcludingConfig { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java index 9ac0a3a31c0..c68bb4edaac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java @@ -51,8 +51,7 @@ public class SharedMetadataReaderFactoryContextInitializerTests { // and happened to be loaded first initializers.add(0, new Initializer()); GenericApplicationContext context = (GenericApplicationContext) application.run(); - BeanDefinition definition = context.getBeanDefinition( - SharedMetadataReaderFactoryContextInitializer.BEAN_NAME); + BeanDefinition definition = context.getBeanDefinition(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME); assertThat(definition.getAttribute("seen")).isEqualTo(true); } @@ -60,8 +59,7 @@ public class SharedMetadataReaderFactoryContextInitializerTests { } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override public void initialize(GenericApplicationContext applicationContext) { @@ -73,13 +71,11 @@ public class SharedMetadataReaderFactoryContextInitializerTests { static class PostProcessor implements BeanDefinitionRegistryPostProcessor { @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { for (String name : registry.getBeanDefinitionNames()) { BeanDefinition definition = registry.getBeanDefinition(name); definition.setAttribute("seen", true); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java index 9da6ca515dd..c5f763636c1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java @@ -34,17 +34,14 @@ public class SpringBootApplicationTests { @Test public void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, - Configuration.class); + .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test public void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes( - NoBeanMethodProxyingSpringBootApplication.class, - Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootApplication.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java index aae5b12abf0..bb78ced9835 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,17 +27,13 @@ import org.springframework.util.ClassUtils; * * @author Phillip Webb */ -public class TestAutoConfigurationPackageRegistrar - implements ImportBeanDefinitionRegistrar { +public class TestAutoConfigurationPackageRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes( - TestAutoConfigurationPackage.class.getName(), true)); - AutoConfigurationPackages.register(registry, - ClassUtils.getPackageName(attributes.getString("value"))); + .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); + AutoConfigurationPackages.register(registry, ClassUtils.getPackageName(attributes.getString("value"))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java index 078c6bcbf46..8d51a6d4a39 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; public class TestAutoConfigurationSorter extends AutoConfigurationSorter { public TestAutoConfigurationSorter(MetadataReaderFactory metadataReaderFactory) { - super(metadataReaderFactory, - AutoConfigurationMetadataLoader.loadMetadata(new Properties())); + super(metadataReaderFactory, AutoConfigurationMetadataLoader.loadMetadata(new Properties())); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index f41ba87ba24..acc1319c529 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -60,15 +60,13 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { private final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(MultipleMBeanExportersConfiguration.class, - SpringApplicationAdminJmxAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MultipleMBeanExportersConfiguration.class, + SpringApplicationAdminJmxAutoConfiguration.class)); @Test public void notRegisteredByDefault() { - this.contextRunner.run((context) -> assertThatExceptionOfType( - InstanceNotFoundException.class).isThrownBy( - () -> this.server.getObjectInstance(createDefaultObjectName()))); + this.contextRunner.run((context) -> assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName()))); } @Test @@ -76,17 +74,14 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { this.contextRunner.withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { ObjectName objectName = createDefaultObjectName(); ObjectInstance objectInstance = this.server.getObjectInstance(objectName); - assertThat(objectInstance).as("Lifecycle bean should have been registered") - .isNotNull(); + assertThat(objectInstance).as("Lifecycle bean should have been registered").isNotNull(); }); } @Test public void registerWithCustomJmxName() { String customJmxName = "org.acme:name=FooBar"; - this.contextRunner - .withSystemProperties( - "spring.application.admin.jmx-name=" + customJmxName) + this.contextRunner.withSystemProperties("spring.application.admin.jmx-name=" + customJmxName) .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { try { this.server.getObjectInstance(createObjectName(customJmxName)); @@ -95,24 +90,20 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { fail("Admin MBean should have been exposed with custom name"); } assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.server - .getObjectInstance(createDefaultObjectName())); + .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName())); }); } @Test public void registerWithSimpleWebApp() throws Exception { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() - .sources(ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - MultipleMBeanExportersConfiguration.class, - SpringApplicationAdminJmxAutoConfiguration.class) + .sources(ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) .run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) { assertThat(context).isInstanceOf(ServletWebServerApplicationContext.class); - assertThat(this.server.getAttribute(createDefaultObjectName(), - "EmbeddedWebApplication")).isEqualTo(Boolean.TRUE); - int expected = ((ServletWebServerApplicationContext) context).getWebServer() - .getPort(); + assertThat(this.server.getAttribute(createDefaultObjectName(), "EmbeddedWebApplication")) + .isEqualTo(Boolean.TRUE); + int expected = ((ServletWebServerApplicationContext) context).getWebServer().getPort(); String actual = getProperty(createDefaultObjectName(), "local.server.port"); assertThat(actual).isEqualTo(String.valueOf(expected)); } @@ -120,23 +111,16 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { @Test public void onlyRegisteredOnceWhenThereIsAChildContext() { - SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder() - .web(WebApplicationType.NONE) - .sources(MultipleMBeanExportersConfiguration.class, - SpringApplicationAdminJmxAutoConfiguration.class); + SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder().web(WebApplicationType.NONE) + .sources(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); SpringApplicationBuilder childBuilder = parentBuilder - .child(MultipleMBeanExportersConfiguration.class, - SpringApplicationAdminJmxAutoConfiguration.class) + .child(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) .web(WebApplicationType.NONE); - try (ConfigurableApplicationContext parent = parentBuilder - .run("--" + ENABLE_ADMIN_PROP); - ConfigurableApplicationContext child = childBuilder - .run("--" + ENABLE_ADMIN_PROP)) { - BeanFactoryUtils.beanOfType(parent.getBeanFactory(), - SpringApplicationAdminMXBeanRegistrar.class); - assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> BeanFactoryUtils.beanOfType(child.getBeanFactory(), - SpringApplicationAdminMXBeanRegistrar.class)); + try (ConfigurableApplicationContext parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); + ConfigurableApplicationContext child = childBuilder.run("--" + ENABLE_ADMIN_PROP)) { + BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> BeanFactoryUtils + .beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class)); } } @@ -154,8 +138,8 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { } private String getProperty(ObjectName objectName, String key) throws Exception { - return (String) this.server.invoke(objectName, "getProperty", - new Object[] { key }, new String[] { String.class.getName() }); + return (String) this.server.invoke(objectName, "getProperty", new Object[] { key }, + new String[] { String.class.getName() }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index e2b235c35bd..551b7378aad 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -87,108 +87,82 @@ public class RabbitAutoConfigurationTests { @Test public void testDefaultRabbitConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - RabbitMessagingTemplate messagingTemplate = context - .getBean(RabbitMessagingTemplate.class); - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - RabbitAdmin amqpAdmin = context.getBean(RabbitAdmin.class); - assertThat(rabbitTemplate.getConnectionFactory()) - .isEqualTo(connectionFactory); - assertThat(getMandatory(rabbitTemplate)).isFalse(); - assertThat(messagingTemplate.getRabbitTemplate()) - .isEqualTo(rabbitTemplate); - assertThat(amqpAdmin).isNotNull(); - assertThat(connectionFactory.getHost()).isEqualTo("localhost"); - assertThat(connectionFactory.isPublisherConfirms()).isFalse(); - assertThat(connectionFactory.isPublisherReturns()).isFalse(); - assertThat(context.containsBean("rabbitListenerContainerFactory")) - .as("Listener container factory should be created by default") - .isTrue(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + RabbitMessagingTemplate messagingTemplate = context.getBean(RabbitMessagingTemplate.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + RabbitAdmin amqpAdmin = context.getBean(RabbitAdmin.class); + assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory); + assertThat(getMandatory(rabbitTemplate)).isFalse(); + assertThat(messagingTemplate.getRabbitTemplate()).isEqualTo(rabbitTemplate); + assertThat(amqpAdmin).isNotNull(); + assertThat(connectionFactory.getHost()).isEqualTo("localhost"); + assertThat(connectionFactory.isPublisherConfirms()).isFalse(); + assertThat(connectionFactory.isPublisherReturns()).isFalse(); + assertThat(context.containsBean("rabbitListenerContainerFactory")) + .as("Listener container factory should be created by default").isTrue(); + }); } @Test public void testDefaultRabbitTemplateConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - RabbitTemplate defaultRabbitTemplate = new RabbitTemplate(); - assertThat(rabbitTemplate.getRoutingKey()) - .isEqualTo(defaultRabbitTemplate.getRoutingKey()); - assertThat(rabbitTemplate.getExchange()) - .isEqualTo(defaultRabbitTemplate.getExchange()); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + RabbitTemplate defaultRabbitTemplate = new RabbitTemplate(); + assertThat(rabbitTemplate.getRoutingKey()).isEqualTo(defaultRabbitTemplate.getRoutingKey()); + assertThat(rabbitTemplate.getExchange()).isEqualTo(defaultRabbitTemplate.getExchange()); + }); } @Test public void testDefaultConnectionFactoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - RabbitProperties properties = new RabbitProperties(); - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory( - context); - assertThat(rabbitConnectionFactory.getUsername()) - .isEqualTo(properties.getUsername()); - assertThat(rabbitConnectionFactory.getPassword()) - .isEqualTo(properties.getPassword()); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + RabbitProperties properties = new RabbitProperties(); + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getUsername()).isEqualTo(properties.getUsername()); + assertThat(rabbitConnectionFactory.getPassword()).isEqualTo(properties.getPassword()); + }); } @Test public void testConnectionFactoryWithOverrides() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.host:remote-server", - "spring.rabbitmq.port:9000", "spring.rabbitmq.username:alice", - "spring.rabbitmq.password:secret", - "spring.rabbitmq.virtual_host:/vhost", - "spring.rabbitmq.connection-timeout:123") + .withPropertyValues("spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", + "spring.rabbitmq.username:alice", "spring.rabbitmq.password:secret", + "spring.rabbitmq.virtual_host:/vhost", "spring.rabbitmq.connection-timeout:123") .run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); assertThat(connectionFactory.getPort()).isEqualTo(9000); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); - com.rabbitmq.client.ConnectionFactory rcf = connectionFactory - .getRabbitConnectionFactory(); + com.rabbitmq.client.ConnectionFactory rcf = connectionFactory.getRabbitConnectionFactory(); assertThat(rcf.getConnectionTimeout()).isEqualTo(123); - assertThat((Address[]) ReflectionTestUtils.getField(connectionFactory, - "addresses")).hasSize(1); + assertThat((Address[]) ReflectionTestUtils.getField(connectionFactory, "addresses")).hasSize(1); }); } @Test public void testConnectionFactoryWithCustomConnectionNameStrategy() { - this.contextRunner - .withUserConfiguration(ConnectionNameStrategyConfiguration.class) - .run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - Address[] addresses = (Address[]) ReflectionTestUtils - .getField(connectionFactory, "addresses"); - assertThat(addresses).hasSize(1); - com.rabbitmq.client.ConnectionFactory rcf = mock( - com.rabbitmq.client.ConnectionFactory.class); - given(rcf.newConnection(isNull(), eq(addresses), anyString())) - .willReturn(mock(Connection.class)); - ReflectionTestUtils.setField(connectionFactory, - "rabbitConnectionFactory", rcf); - connectionFactory.createConnection(); - verify(rcf).newConnection(isNull(), eq(addresses), eq("test#0")); - connectionFactory.resetConnection(); - connectionFactory.createConnection(); - verify(rcf).newConnection(isNull(), eq(addresses), eq("test#1")); - }); + this.contextRunner.withUserConfiguration(ConnectionNameStrategyConfiguration.class).run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + Address[] addresses = (Address[]) ReflectionTestUtils.getField(connectionFactory, "addresses"); + assertThat(addresses).hasSize(1); + com.rabbitmq.client.ConnectionFactory rcf = mock(com.rabbitmq.client.ConnectionFactory.class); + given(rcf.newConnection(isNull(), eq(addresses), anyString())).willReturn(mock(Connection.class)); + ReflectionTestUtils.setField(connectionFactory, "rabbitConnectionFactory", rcf); + connectionFactory.createConnection(); + verify(rcf).newConnection(isNull(), eq(addresses), eq("test#0")); + connectionFactory.resetConnection(); + connectionFactory.createConnection(); + verify(rcf).newConnection(isNull(), eq(addresses), eq("test#1")); + }); } @Test public void testConnectionFactoryEmptyVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:").run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); }); } @@ -197,8 +171,7 @@ public class RabbitAutoConfigurationTests { public void testConnectionFactoryVirtualHostNoLeadingSlash() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:foo").run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); }); } @@ -206,10 +179,8 @@ public class RabbitAutoConfigurationTests { @Test public void testConnectionFactoryVirtualHostMultiLeadingSlashes() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:///foo") - .run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + .withPropertyValues("spring.rabbitmq.virtual_host:///foo").run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); }); } @@ -218,8 +189,7 @@ public class RabbitAutoConfigurationTests { public void testConnectionFactoryDefaultVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:/").run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); }); } @@ -227,11 +197,9 @@ public class RabbitAutoConfigurationTests { @Test public void testConnectionFactoryPublisherSettings() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-confirms=true", - "spring.rabbitmq.publisher-returns=true") + .withPropertyValues("spring.rabbitmq.publisher-confirms=true", "spring.rabbitmq.publisher-returns=true") .run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); assertThat(connectionFactory.isPublisherConfirms()).isTrue(); assertThat(connectionFactory.isPublisherReturns()).isTrue(); @@ -241,37 +209,28 @@ public class RabbitAutoConfigurationTests { @Test public void testRabbitTemplateMessageConverters() { - this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); - assertThat(rabbitTemplate) - .hasFieldOrPropertyWithValue("retryTemplate", null); - }); + this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class).run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("retryTemplate", null); + }); } @Test public void testRabbitTemplateRetry() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", - "spring.rabbitmq.template.retry.maxAttempts:4", - "spring.rabbitmq.template.retry.initialInterval:2000", - "spring.rabbitmq.template.retry.multiplier:1.5", - "spring.rabbitmq.template.retry.maxInterval:5000", - "spring.rabbitmq.template.receiveTimeout:123", - "spring.rabbitmq.template.replyTimeout:456") - .run((context) -> { + this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( + "spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.maxAttempts:4", + "spring.rabbitmq.template.retry.initialInterval:2000", "spring.rabbitmq.template.retry.multiplier:1.5", + "spring.rabbitmq.template.retry.maxInterval:5000", "spring.rabbitmq.template.receiveTimeout:123", + "spring.rabbitmq.template.replyTimeout:456").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate) - .hasFieldOrPropertyWithValue("receiveTimeout", 123L); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout", - 456L); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils - .getField(rabbitTemplate, "retryTemplate"); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("receiveTimeout", 123L); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout", 456L); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, + "retryTemplate"); assertThat(retryTemplate).isNotNull(); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils - .getField(retryTemplate, "retryPolicy"); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, + "retryPolicy"); ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils .getField(retryTemplate, "backOffPolicy"); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); @@ -283,19 +242,18 @@ public class RabbitAutoConfigurationTests { @Test public void testRabbitTemplateRetryWithCustomizer() { - this.contextRunner - .withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) + this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.initialInterval:2000") .run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils - .getField(rabbitTemplate, "retryTemplate"); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, + "retryTemplate"); assertThat(retryTemplate).isNotNull(); ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils .getField(retryTemplate, "backOffPolicy"); - assertThat(backOffPolicy).isSameAs(context.getBean( - RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy); + assertThat(backOffPolicy) + .isSameAs(context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy); assertThat(backOffPolicy.getInitialInterval()).isEqualTo(100); }); } @@ -308,28 +266,23 @@ public class RabbitAutoConfigurationTests { .run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); assertThat(rabbitTemplate.getExchange()).isEqualTo("my-exchange"); - assertThat(rabbitTemplate.getRoutingKey()) - .isEqualTo("my-routing-key"); + assertThat(rabbitTemplate.getRoutingKey()).isEqualTo("my-routing-key"); }); } @Test public void testRabbitTemplateDefaultReceiveQueue() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues( - "spring.rabbitmq.template.default-receive-queue:default-queue") - .run((context) -> { + .withPropertyValues("spring.rabbitmq.template.default-receive-queue:default-queue").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue( - "defaultReceiveQueue", "default-queue"); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("defaultReceiveQueue", "default-queue"); }); } @Test public void testRabbitTemplateMandatory() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.mandatory:true") - .run((context) -> { + .withPropertyValues("spring.rabbitmq.template.mandatory:true").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); assertThat(getMandatory(rabbitTemplate)).isTrue(); }); @@ -337,10 +290,8 @@ public class RabbitAutoConfigurationTests { @Test public void testRabbitTemplateMandatoryDisabledEvenIfPublisherReturnsIsSet() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.mandatory:false", - "spring.rabbitmq.publisher-returns=true") - .run((context) -> { + this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( + "spring.rabbitmq.template.mandatory:false", "spring.rabbitmq.publisher-returns=true").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); assertThat(getMandatory(rabbitTemplate)).isFalse(); }); @@ -348,16 +299,13 @@ public class RabbitAutoConfigurationTests { @Test public void testConnectionFactoryBackOff() { - this.contextRunner.withUserConfiguration(TestConfiguration2.class) - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - assertThat(connectionFactory) - .isEqualTo(rabbitTemplate.getConnectionFactory()); - assertThat(connectionFactory.getHost()).isEqualTo("otherserver"); - assertThat(connectionFactory.getPort()).isEqualTo(8001); - }); + this.contextRunner.withUserConfiguration(TestConfiguration2.class).run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory).isEqualTo(rabbitTemplate.getConnectionFactory()); + assertThat(connectionFactory.getHost()).isEqualTo("otherserver"); + assertThat(connectionFactory.getPort()).isEqualTo(8001); + }); } @Test @@ -365,39 +313,30 @@ public class RabbitAutoConfigurationTests { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.cache.channel.size=23", "spring.rabbitmq.cache.channel.checkoutTimeout=1000", - "spring.rabbitmq.cache.connection.mode=CONNECTION", - "spring.rabbitmq.cache.connection.size=2") + "spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.size=2") .run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getChannelCacheSize()).isEqualTo(23); - assertThat(connectionFactory.getCacheMode()) - .isEqualTo(CacheMode.CONNECTION); + assertThat(connectionFactory.getCacheMode()).isEqualTo(CacheMode.CONNECTION); assertThat(connectionFactory.getConnectionCacheSize()).isEqualTo(2); - assertThat(connectionFactory) - .hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L); + assertThat(connectionFactory).hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L); }); } @Test public void testRabbitTemplateBackOff() { - this.contextRunner.withUserConfiguration(TestConfiguration3.class) - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate.getMessageConverter()) - .isEqualTo(context.getBean("testMessageConverter")); - }); + this.contextRunner.withUserConfiguration(TestConfiguration3.class).run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate.getMessageConverter()).isEqualTo(context.getBean("testMessageConverter")); + }); } @Test public void testRabbitMessagingTemplateBackOff() { - this.contextRunner.withUserConfiguration(TestConfiguration4.class) - .run((context) -> { - RabbitMessagingTemplate messagingTemplate = context - .getBean(RabbitMessagingTemplate.class); - assertThat(messagingTemplate.getDefaultDestination()) - .isEqualTo("fooBar"); - }); + this.contextRunner.withUserConfiguration(TestConfiguration4.class).run((context) -> { + RabbitMessagingTemplate messagingTemplate = context.getBean(RabbitMessagingTemplate.class); + assertThat(messagingTemplate.getDefaultDestination()).isEqualTo("fooBar"); + }); } @Test @@ -405,43 +344,35 @@ public class RabbitAutoConfigurationTests { // There should NOT be an AmqpAdmin bean when dynamic is switch to false this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.dynamic:false") - .run((context) -> assertThatExceptionOfType( - NoSuchBeanDefinitionException.class) - .isThrownBy(() -> context.getBean(AmqpAdmin.class)) - .withMessageContaining("No qualifying bean of type '" - + AmqpAdmin.class.getName() + "'")); + .run((context) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> context.getBean(AmqpAdmin.class)) + .withMessageContaining("No qualifying bean of type '" + AmqpAdmin.class.getName() + "'")); } @Test public void testEnableRabbitCreateDefaultContainerFactory() { - this.contextRunner.withUserConfiguration(EnableRabbitConfiguration.class) - .run((context) -> { - RabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - RabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory.getClass()) - .isEqualTo(SimpleRabbitListenerContainerFactory.class); - }); + this.contextRunner.withUserConfiguration(EnableRabbitConfiguration.class).run((context) -> { + RabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory.getClass()).isEqualTo(SimpleRabbitListenerContainerFactory.class); + }); } @Test public void testRabbitListenerContainerFactoryBackOff() { - this.contextRunner.withUserConfiguration(TestConfiguration5.class) - .run((context) -> { - SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - SimpleRabbitListenerContainerFactory.class); - rabbitListenerContainerFactory.setTxSize(10); - verify(rabbitListenerContainerFactory).setTxSize(10); - assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration5.class).run((context) -> { + SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + rabbitListenerContainerFactory.setTxSize(10); + verify(rabbitListenerContainerFactory).setTxSize(10); + assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull(); + }); } @Test public void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner - .withUserConfiguration(MessageConvertersConfiguration.class, - MessageRecoverersConfiguration.class) + .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", "spring.rabbitmq.listener.simple.retry.maxAttempts:4", "spring.rabbitmq.listener.simple.retry.initialInterval:2000", @@ -458,16 +389,12 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.listener.simple.missingQueuesFatal:false") .run((context) -> { SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - SimpleRabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory) - .hasFieldOrPropertyWithValue("concurrentConsumers", 5); - assertThat(rabbitListenerContainerFactory) - .hasFieldOrPropertyWithValue("maxConcurrentConsumers", 10); - assertThat(rabbitListenerContainerFactory) - .hasFieldOrPropertyWithValue("txSize", 20); - assertThat(rabbitListenerContainerFactory) - .hasFieldOrPropertyWithValue("missingQueuesFatal", false); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("concurrentConsumers", 5); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("maxConcurrentConsumers", + 10); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("txSize", 20); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", false); checkCommonProps(context, rabbitListenerContainerFactory); }); } @@ -475,8 +402,7 @@ public class RabbitAutoConfigurationTests { @Test public void testDirectRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner - .withUserConfiguration(MessageConvertersConfiguration.class, - MessageRecoverersConfiguration.class) + .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.type:direct", "spring.rabbitmq.listener.direct.retry.enabled:true", "spring.rabbitmq.listener.direct.retry.maxAttempts:4", @@ -492,74 +418,58 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.listener.direct.missingQueuesFatal:true") .run((context) -> { DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - DirectRabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory) - .hasFieldOrPropertyWithValue("consumersPerQueue", 5); - assertThat(rabbitListenerContainerFactory) - .hasFieldOrPropertyWithValue("missingQueuesFatal", true); + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("consumersPerQueue", 5); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", true); checkCommonProps(context, rabbitListenerContainerFactory); }); } @Test public void testSimpleRabbitListenerContainerFactoryRetryWithCustomizer() { - this.contextRunner - .withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) + this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", "spring.rabbitmq.listener.simple.retry.maxAttempts:4") .run((context) -> { SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - SimpleRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); assertListenerRetryTemplate(rabbitListenerContainerFactory, - context.getBean( - RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); + context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); }); } @Test public void testDirectRabbitListenerContainerFactoryRetryWithCustomizer() { - this.contextRunner - .withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) + this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.type:direct", "spring.rabbitmq.listener.direct.retry.enabled:true", "spring.rabbitmq.listener.direct.retry.maxAttempts:4") .run((context) -> { DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - DirectRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); assertListenerRetryTemplate(rabbitListenerContainerFactory, - context.getBean( - RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); + context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); }); } - private void assertListenerRetryTemplate( - AbstractRabbitListenerContainerFactory rabbitListenerContainerFactory, + private void assertListenerRetryTemplate(AbstractRabbitListenerContainerFactory rabbitListenerContainerFactory, RetryPolicy retryPolicy) { Advice[] adviceChain = rabbitListenerContainerFactory.getAdviceChain(); assertThat(adviceChain).isNotNull(); assertThat(adviceChain.length).isEqualTo(1); Advice advice = adviceChain[0]; - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice, - "retryOperations"); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice, "retryOperations"); assertThat(retryTemplate).hasFieldOrPropertyWithValue("retryPolicy", retryPolicy); } @Test public void testRabbitListenerContainerFactoryConfigurersAreAvailable() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", - "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40", - "spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40") - .run((context) -> { - assertThat(context).hasSingleBean( - SimpleRabbitListenerContainerFactoryConfigurer.class); - assertThat(context).hasSingleBean( - DirectRabbitListenerContainerFactoryConfigurer.class); + this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( + "spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.maxConcurrency:10", + "spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40").run((context) -> { + assertThat(context).hasSingleBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + assertThat(context).hasSingleBean(DirectRabbitListenerContainerFactoryConfigurer.class); }); } @@ -572,10 +482,8 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.listener.simple.prefetch:40") .run((context) -> { SimpleRabbitListenerContainerFactoryConfigurer configurer = context - .getBean( - SimpleRabbitListenerContainerFactoryConfigurer.class); - SimpleRabbitListenerContainerFactory factory = mock( - SimpleRabbitListenerContainerFactory.class); + .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); configurer.configure(factory, mock(ConnectionFactory.class)); verify(factory).setConcurrentConsumers(5); verify(factory).setMaxConcurrentConsumers(10); @@ -591,10 +499,8 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.listener.direct.prefetch:40") .run((context) -> { DirectRabbitListenerContainerFactoryConfigurer configurer = context - .getBean( - DirectRabbitListenerContainerFactoryConfigurer.class); - DirectRabbitListenerContainerFactory factory = mock( - DirectRabbitListenerContainerFactory.class); + .getBean(DirectRabbitListenerContainerFactoryConfigurer.class); + DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class); configurer.configure(factory, mock(ConnectionFactory.class)); verify(factory).setConsumersPerQueue(5); verify(factory).setPrefetchCount(40); @@ -603,35 +509,29 @@ public class RabbitAutoConfigurationTests { private void checkCommonProps(AssertableApplicationContext context, AbstractRabbitListenerContainerFactory containerFactory) { - assertThat(containerFactory).hasFieldOrPropertyWithValue("autoStartup", - Boolean.FALSE); - assertThat(containerFactory).hasFieldOrPropertyWithValue("acknowledgeMode", - AcknowledgeMode.MANUAL); + assertThat(containerFactory).hasFieldOrPropertyWithValue("autoStartup", Boolean.FALSE); + assertThat(containerFactory).hasFieldOrPropertyWithValue("acknowledgeMode", AcknowledgeMode.MANUAL); assertThat(containerFactory).hasFieldOrPropertyWithValue("prefetchCount", 40); assertThat(containerFactory).hasFieldOrPropertyWithValue("messageConverter", context.getBean("myMessageConverter")); - assertThat(containerFactory).hasFieldOrPropertyWithValue("defaultRequeueRejected", - Boolean.FALSE); + assertThat(containerFactory).hasFieldOrPropertyWithValue("defaultRequeueRejected", Boolean.FALSE); assertThat(containerFactory).hasFieldOrPropertyWithValue("idleEventInterval", 5L); Advice[] adviceChain = containerFactory.getAdviceChain(); assertThat(adviceChain).isNotNull(); assertThat(adviceChain.length).isEqualTo(1); Advice advice = adviceChain[0]; - MessageRecoverer messageRecoverer = context.getBean("myMessageRecoverer", - MessageRecoverer.class); - MethodInvocationRecoverer mir = (MethodInvocationRecoverer) ReflectionTestUtils - .getField(advice, "recoverer"); + MessageRecoverer messageRecoverer = context.getBean("myMessageRecoverer", MessageRecoverer.class); + MethodInvocationRecoverer mir = (MethodInvocationRecoverer) ReflectionTestUtils.getField(advice, + "recoverer"); Message message = mock(Message.class); Exception ex = new Exception("test"); mir.recover(new Object[] { "foo", message }, ex); verify(messageRecoverer).recover(message, ex); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice, - "retryOperations"); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice, "retryOperations"); assertThat(retryTemplate).isNotNull(); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils - .getField(retryTemplate, "retryPolicy"); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils - .getField(retryTemplate, "backOffPolicy"); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, "retryPolicy"); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils.getField(retryTemplate, + "backOffPolicy"); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); @@ -640,47 +540,37 @@ public class RabbitAutoConfigurationTests { @Test public void enableRabbitAutomatically() { - this.contextRunner.withUserConfiguration(NoEnableRabbitConfiguration.class) - .run((context) -> { - assertThat(context).hasBean( - RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); - assertThat(context).hasBean( - RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); - }); + this.contextRunner.withUserConfiguration(NoEnableRabbitConfiguration.class).run((context) -> { + assertThat(context).hasBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); + assertThat(context).hasBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); + }); } @Test public void customizeRequestedHeartBeat() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20") - .run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory( - context); - assertThat(rabbitConnectionFactory.getRequestedHeartbeat()) - .isEqualTo(20); + .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20").run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getRequestedHeartbeat()).isEqualTo(20); }); } @Test public void noSslByDefault() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory( - context); - assertThat(rabbitConnectionFactory.getSocketFactory()).isNull(); - assertThat(rabbitConnectionFactory.isSSL()).isFalse(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getSocketFactory()).isNull(); + assertThat(rabbitConnectionFactory.isSSL()).isFalse(); + }); } @Test public void enableSsl() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory( - context); + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(rabbitConnectionFactory.getSocketFactory()) - .as("SocketFactory must use SSL") + assertThat(rabbitConnectionFactory.getSocketFactory()).as("SocketFactory must use SSL") .isInstanceOf(SSLSocketFactory.class); }); } @@ -688,58 +578,50 @@ public class RabbitAutoConfigurationTests { @Test // Make sure that we at least attempt to load the store public void enableSslWithNonExistingKeystoreShouldFail() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", - "spring.rabbitmq.ssl.keyStorePassword=secret") + this.contextRunner + .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStorePassword=secret") .run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasMessageContaining("foo"); - assertThat(context).getFailure() - .hasMessageContaining("does not exist"); + assertThat(context).getFailure().hasMessageContaining("does not exist"); }); } @Test // Make sure that we at least attempt to load the store public void enableSslWithNonExistingTrustStoreShouldFail() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=bar", - "spring.rabbitmq.ssl.trustStorePassword=secret") + this.contextRunner + .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStorePassword=secret") .run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasMessageContaining("bar"); - assertThat(context).getFailure() - .hasMessageContaining("does not exist"); + assertThat(context).getFailure().hasMessageContaining("does not exist"); }); } @Test public void enableSslWithInvalidKeystoreTypeShouldFail() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", - "spring.rabbitmq.ssl.keyStoreType=fooType") + this.contextRunner + .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStoreType=fooType") .run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasMessageContaining("fooType"); - assertThat(context).getFailure() - .hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); }); } @Test public void enableSslWithInvalidTrustStoreTypeShouldFail() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=bar", - "spring.rabbitmq.ssl.trustStoreType=barType") + this.contextRunner + .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStoreType=barType") .run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasMessageContaining("barType"); - assertThat(context).getFailure() - .hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); }); } @@ -748,11 +630,9 @@ public class RabbitAutoConfigurationTests { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", - "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", - "spring.rabbitmq.ssl.trustStorePassword=secret") + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret") .run((context) -> assertThat(context).hasNotFailed()); } @@ -762,11 +642,9 @@ public class RabbitAutoConfigurationTests { .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.validateServerCertificate=false") .run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory( - context); + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); TrustManager trustManager = getTrustManager(rabbitConnectionFactory); - assertThat(trustManager) - .isInstanceOf(TrustEverythingTrustManager.class); + assertThat(trustManager).isInstanceOf(TrustEverythingTrustManager.class); }); } @@ -774,18 +652,15 @@ public class RabbitAutoConfigurationTests { public void enableSslWithValidateServerCertificateDefault() throws Exception { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory( - context); + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); TrustManager trustManager = getTrustManager(rabbitConnectionFactory); - assertThat(trustManager) - .isNotInstanceOf(TrustEverythingTrustManager.class); + assertThat(trustManager).isNotInstanceOf(TrustEverythingTrustManager.class); }); } - private TrustManager getTrustManager( - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) { - SslContextFactory sslContextFactory = (SslContextFactory) ReflectionTestUtils - .getField(rabbitConnectionFactory, "sslContextFactory"); + private TrustManager getTrustManager(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) { + SslContextFactory sslContextFactory = (SslContextFactory) ReflectionTestUtils.getField(rabbitConnectionFactory, + "sslContextFactory"); SSLContext sslContext = sslContextFactory.create("connection"); Object spi = ReflectionTestUtils.getField(sslContext, "contextSpi"); Object trustManager = ReflectionTestUtils.getField(spi, "trustManager"); @@ -795,10 +670,8 @@ public class RabbitAutoConfigurationTests { return (TrustManager) trustManager; } - private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory( - AssertableApplicationContext context) { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory(AssertableApplicationContext context) { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); return connectionFactory.getRabbitConnectionFactory(); } @@ -825,8 +698,7 @@ public class RabbitAutoConfigurationTests { protected static class TestConfiguration3 { @Bean - RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, - MessageConverter messageConverter) { + RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(messageConverter); return rabbitTemplate; @@ -844,8 +716,7 @@ public class RabbitAutoConfigurationTests { @Bean RabbitMessagingTemplate messagingTemplate(RabbitTemplate rabbitTemplate) { - RabbitMessagingTemplate messagingTemplate = new RabbitMessagingTemplate( - rabbitTemplate); + RabbitMessagingTemplate messagingTemplate = new RabbitMessagingTemplate(rabbitTemplate); messagingTemplate.setDefaultDestination("fooBar"); return messagingTemplate; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java index 552aa7db4dc..f66bf6404a9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java @@ -108,8 +108,7 @@ public class RabbitPropertiesTests { @Test public void determineVirtualHostReturnsVirtualHostOfFirstAddress() { - this.properties.setAddresses( - "rabbit1.example.com:1234/alpha,rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234/alpha,rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @@ -122,8 +121,7 @@ public class RabbitPropertiesTests { @Test public void determineVirtualHostReturnsPropertyWhenFirstAddressHasNoVirtualHost() { this.properties.setVirtualHost("alpha"); - this.properties - .setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @@ -152,8 +150,7 @@ public class RabbitPropertiesTests { @Test public void determineUsernameReturnsUsernameOfFirstAddress() { - this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," - + "rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," + "rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineUsername()).isEqualTo("user"); } @@ -166,8 +163,7 @@ public class RabbitPropertiesTests { @Test public void determineUsernameReturnsPropertyWhenFirstAddressHasNoUsername() { this.properties.setUsername("alice"); - this.properties.setAddresses("rabbit1.example.com:1234/alpha," - + "user:secret@rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234/alpha," + "user:secret@rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineUsername()).isEqualTo("alice"); } @@ -184,8 +180,7 @@ public class RabbitPropertiesTests { @Test public void determinePasswordReturnsPasswordOfFirstAddress() { - this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," - + "rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," + "rabbit2.example.com:2345/bravo"); assertThat(this.properties.determinePassword()).isEqualTo("secret"); } @@ -198,8 +193,7 @@ public class RabbitPropertiesTests { @Test public void determinePasswordReturnsPropertyWhenFirstAddressHasNoPassword() { this.properties.setPassword("12345678"); - this.properties.setAddresses("rabbit1.example.com:1234/alpha," - + "user:secret@rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234/alpha," + "user:secret@rabbit2.example.com:2345/bravo"); assertThat(this.properties.determinePassword()).isEqualTo("12345678"); } @@ -210,48 +204,40 @@ public class RabbitPropertiesTests { @Test public void customAddresses() { - this.properties.setAddresses( - "user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); - assertThat(this.properties.getAddresses()).isEqualTo( - "user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + assertThat(this.properties.getAddresses()) + .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); } @Test public void determineAddressesReturnsAddressesWithJustHostAndPort() { - this.properties.setAddresses( - "user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); - assertThat(this.properties.determineAddresses()) - .isEqualTo("rabbit1.example.com:1234,rabbit2.example.com:5672"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + assertThat(this.properties.determineAddresses()).isEqualTo("rabbit1.example.com:1234,rabbit2.example.com:5672"); } @Test public void determineAddressesUsesHostAndPortPropertiesWhenNoAddressesSet() { this.properties.setHost("rabbit.example.com"); this.properties.setPort(1234); - assertThat(this.properties.determineAddresses()) - .isEqualTo("rabbit.example.com:1234"); + assertThat(this.properties.determineAddresses()).isEqualTo("rabbit.example.com:1234"); } @Test public void simpleContainerUseConsistentDefaultValues() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); SimpleMessageListenerContainer container = factory.createListenerContainer(); - RabbitProperties.SimpleContainer simple = this.properties.getListener() - .getSimple(); + RabbitProperties.SimpleContainer simple = this.properties.getListener().getSimple(); assertThat(simple.isAutoStartup()).isEqualTo(container.isAutoStartup()); - assertThat(container).hasFieldOrPropertyWithValue("missingQueuesFatal", - simple.isMissingQueuesFatal()); + assertThat(container).hasFieldOrPropertyWithValue("missingQueuesFatal", simple.isMissingQueuesFatal()); } @Test public void directContainerUseConsistentDefaultValues() { DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory(); DirectMessageListenerContainer container = factory.createListenerContainer(); - RabbitProperties.DirectContainer direct = this.properties.getListener() - .getDirect(); + RabbitProperties.DirectContainer direct = this.properties.getListener().getDirect(); assertThat(direct.isAutoStartup()).isEqualTo(container.isAutoStartup()); - assertThat(container).hasFieldOrPropertyWithValue("missingQueuesFatal", - direct.isMissingQueuesFatal()); + assertThat(container).hasFieldOrPropertyWithValue("missingQueuesFatal", direct.isMissingQueuesFatal()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java index e4d021e4d55..1332b0e5b4b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java @@ -44,8 +44,8 @@ public class AopAutoConfigurationTests { @Test public void aopDisabled() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.auto:false").run((context) -> { + this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.aop.auto:false") + .run((context) -> { TestAspect aspect = context.getBean(TestAspect.class); assertThat(aspect.isCalled()).isFalse(); TestBean bean = context.getBean(TestBean.class); @@ -56,28 +56,24 @@ public class AopAutoConfigurationTests { @Test public void aopWithDefaultSettings() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run(proxyTargetClassEnabled()); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run(proxyTargetClassEnabled()); } @Test public void aopWithEnabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class:true") - .run(proxyTargetClassEnabled()); + .withPropertyValues("spring.aop.proxy-target-class:true").run(proxyTargetClassEnabled()); } @Test public void aopWithDisabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class:false") - .run(proxyTargetClassDisabled()); + .withPropertyValues("spring.aop.proxy-target-class:false").run(proxyTargetClassDisabled()); } @Test public void customConfigurationWithProxyTargetClassDefaultDoesNotDisableProxying() { - this.contextRunner.withUserConfiguration(CustomTestConfiguration.class) - .run(proxyTargetClassEnabled()); + this.contextRunner.withUserConfiguration(CustomTestConfiguration.class).run(proxyTargetClassEnabled()); } private ContextConsumer proxyTargetClassEnabled() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index 42670c083cd..d1ba34e130b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -73,18 +73,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class BatchAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, - TransactionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test public void testDefaultContext() { - this.contextRunner.withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); assertThat(context).hasSingleBean(JobExplorer.class); - assertThat( - context.getBean(BatchProperties.class).getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.EMBEDDED); + assertThat(context.getBean(BatchProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.EMBEDDED); assertThat(new JdbcTemplate(context.getBean(DataSource.class)) .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); }); @@ -92,18 +90,17 @@ public class BatchAutoConfigurationTests { @Test public void testNoDatabase() { - this.contextRunner.withUserConfiguration(TestCustomConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - JobExplorer explorer = context.getBean(JobExplorer.class); - assertThat(explorer.getJobInstances("job", 0, 100)).isEmpty(); - }); + this.contextRunner.withUserConfiguration(TestCustomConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + JobExplorer explorer = context.getBean(JobExplorer.class); + assertThat(explorer.getJobInstances("job", 0, 100)).isEmpty(); + }); } @Test public void testNoBatchConfiguration() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class, - EmbeddedDataSourceConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(EmptyConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean(JobLauncher.class); assertThat(context).doesNotHaveBean(JobRepository.class); }); @@ -111,12 +108,12 @@ public class BatchAutoConfigurationTests { @Test public void testDefinesAndLaunchesJob() { - this.contextRunner.withUserConfiguration(JobConfiguration.class, - EmbeddedDataSourceConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); context.getBean(JobLauncherCommandLineRunner.class).run(); - assertThat(context.getBean(JobRepository.class) - .getLastJobExecution("job", new JobParameters())).isNotNull(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) + .isNotNull(); }); } @@ -125,35 +122,29 @@ public class BatchAutoConfigurationTests { this.contextRunner .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.names:discreteRegisteredJob") - .run((context) -> { + .withPropertyValues("spring.batch.job.names:discreteRegisteredJob").run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); context.getBean(JobLauncherCommandLineRunner.class).run(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution( - "discreteRegisteredJob", new JobParameters())).isNotNull(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteRegisteredJob", + new JobParameters())).isNotNull(); }); } @Test public void testDefinesAndLaunchesLocalJob() { this.contextRunner - .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.names:discreteLocalJob") - .run((context) -> { + .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.batch.job.names:discreteLocalJob").run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); context.getBean(JobLauncherCommandLineRunner.class).run(); - assertThat(context.getBean(JobRepository.class) - .getLastJobExecution("discreteLocalJob", new JobParameters())) - .isNotNull(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteLocalJob", + new JobParameters())).isNotNull(); }); } @Test public void testDisableLaunchesJob() { - this.contextRunner - .withUserConfiguration(JobConfiguration.class, - EmbeddedDataSourceConfiguration.class) + this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.batch.job.enabled:false").run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); assertThat(context).doesNotHaveBean(CommandLineRunner.class); @@ -162,79 +153,67 @@ public class BatchAutoConfigurationTests { @Test public void testDisableSchemaLoader() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class) + this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.batch.initialize-schema:never") .run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); - assertThat( - context.getBean(BatchProperties.class).getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.NEVER); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> new JdbcTemplate(context.getBean(DataSource.class)) + assertThat(context.getBean(BatchProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.NEVER); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> new JdbcTemplate(context.getBean(DataSource.class)) .queryForList("select * from BATCH_JOB_EXECUTION")); }); } @Test public void testUsingJpa() { - this.contextRunner.withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, + this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class).run((context) -> { - PlatformTransactionManager transactionManager = context - .getBean(PlatformTransactionManager.class); + PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); // It's a lazy proxy, but it does render its target if you ask for // toString(): - assertThat(transactionManager.toString() - .contains("JpaTransactionManager")).isTrue(); + assertThat(transactionManager.toString().contains("JpaTransactionManager")).isTrue(); assertThat(context).hasSingleBean(EntityManagerFactory.class); // Ensure the JobRepository can be used (no problem with isolation // level) - assertThat(context.getBean(JobRepository.class) - .getLastJobExecution("job", new JobParameters())).isNull(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) + .isNull(); }); } @Test public void testRenamePrefix() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.batch.schema:classpath:batch/custom-schema-hsql.sql", "spring.batch.tablePrefix:PREFIX_") .run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); - assertThat( - context.getBean(BatchProperties.class).getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.EMBEDDED); + assertThat(context.getBean(BatchProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.EMBEDDED); assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION")) - .isEmpty(); + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); JobExplorer jobExplorer = context.getBean(JobExplorer.class); assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); JobRepository jobRepository = context.getBean(JobRepository.class); - assertThat(jobRepository.getLastJobExecution("test", - new JobParameters())).isNull(); + assertThat(jobRepository.getLastJobExecution("test", new JobParameters())).isNull(); }); } @Test public void testCustomizeJpaTransactionManagerUsingProperties() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class) .withPropertyValues("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") .run((context) -> { assertThat(context).hasSingleBean(BatchConfigurer.class); JpaTransactionManager transactionManager = JpaTransactionManager.class - .cast(context.getBean(BatchConfigurer.class) - .getTransactionManager()); + .cast(context.getBean(BatchConfigurer.class).getTransactionManager()); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); }); @@ -242,16 +221,13 @@ public class BatchAutoConfigurationTests { @Test public void testCustomizeDataSourceTransactionManagerUsingProperties() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class) + this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") .run((context) -> { assertThat(context).hasSingleBean(BatchConfigurer.class); DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class - .cast(context.getBean(BatchConfigurer.class) - .getTransactionManager()); + .cast(context.getBean(BatchConfigurer.class).getTransactionManager()); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); }); @@ -299,8 +275,7 @@ public class BatchAutoConfigurationTests { @Override public JobExplorer getJobExplorer() throws Exception { - MapJobExplorerFactoryBean explorer = new MapJobExplorerFactoryBean( - this.factory); + MapJobExplorerFactoryBean explorer = new MapJobExplorerFactoryBean(this.factory); explorer.afterPropertiesSet(); return explorer.getObject(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java index cb5ea1aedb0..019e86c5276 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,51 +50,40 @@ import static org.assertj.core.api.Assertions.assertThat; public class BatchAutoConfigurationWithoutJpaTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, - TransactionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test public void jdbcWithDefaultSettings() { - this.contextRunner - .withUserConfiguration(DefaultConfiguration.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true") - .run((context) -> { + this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.datasource.generate-unique-name=true").run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); assertThat(context).hasSingleBean(JobExplorer.class); assertThat(context).hasSingleBean(JobRepository.class); assertThat(context).hasSingleBean(PlatformTransactionManager.class); - assertThat( - context.getBean(PlatformTransactionManager.class).toString()) - .contains("DataSourceTransactionManager"); - assertThat( - context.getBean(BatchProperties.class).getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.EMBEDDED); + assertThat(context.getBean(PlatformTransactionManager.class).toString()) + .contains("DataSourceTransactionManager"); + assertThat(context.getBean(BatchProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.EMBEDDED); assertThat(new JdbcTemplate(context.getBean(DataSource.class)) .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); - assertThat(context.getBean(JobExplorer.class) - .findRunningJobExecutions("test")).isEmpty(); - assertThat(context.getBean(JobRepository.class) - .getLastJobExecution("test", new JobParameters())).isNull(); + assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) + .isNull(); }); } @Test public void jdbcWithCustomPrefix() { - this.contextRunner - .withUserConfiguration(DefaultConfiguration.class, - EmbeddedDataSourceConfiguration.class) + this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.batch.schema:classpath:batch/custom-schema-hsql.sql", "spring.batch.tablePrefix:PREFIX_") .run((context) -> { assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION")) - .isEmpty(); - assertThat(context.getBean(JobExplorer.class) - .findRunningJobExecutions("test")).isEmpty(); - assertThat(context.getBean(JobRepository.class) - .getLastJobExecution("test", new JobParameters())).isNull(); + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); + assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) + .isNull(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java index 19491a93043..9cf05705fd2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java @@ -79,15 +79,13 @@ public class JobLauncherCommandLineRunnerTests { JobRepository jobRepository = this.context.getBean(JobRepository.class); JobLauncher jobLauncher = this.context.getBean(JobLauncher.class); this.jobs = new JobBuilderFactory(jobRepository); - PlatformTransactionManager transactionManager = this.context - .getBean(PlatformTransactionManager.class); + PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.class); this.steps = new StepBuilderFactory(jobRepository, transactionManager); Tasklet tasklet = (contribution, chunkContext) -> null; this.step = this.steps.get("step").tasklet(tasklet).build(); this.job = this.jobs.get("job").start(this.step).build(); this.jobExplorer = this.context.getBean(JobExplorer.class); - this.runner = new JobLauncherCommandLineRunner(jobLauncher, this.jobExplorer, - jobRepository); + this.runner = new JobLauncherCommandLineRunner(jobLauncher, this.jobExplorer, jobRepository); this.context.getBean(BatchConfiguration.class).clear(); } @@ -100,15 +98,13 @@ public class JobLauncherCommandLineRunnerTests { public void basicExecution() throws Exception { this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); - this.runner.execute(this.job, - new JobParametersBuilder().addLong("id", 1L).toJobParameters()); + this.runner.execute(this.job, new JobParametersBuilder().addLong("id", 1L).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @Test public void incrementExistingExecution() throws Exception { - this.job = this.jobs.get("job").start(this.step) - .incrementer(new RunIdIncrementer()).build(); + this.job = this.jobs.get("job").start(this.step).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); @@ -116,27 +112,22 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecution() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()) .incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); - this.runner.execute(this.job, - new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); + this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); } @Test public void runDifferentInstances() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()).build(); + this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()).build(); // start a job instance - JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo") - .toJobParameters(); + JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo").toJobParameters(); this.runner.execute(this.job, jobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); // start a different job instance - JobParameters otherJobParameters = new JobParametersBuilder() - .addString("name", "bar").toJobParameters(); + JobParameters otherJobParameters = new JobParametersBuilder().addString("name", "bar").toJobParameters(); this.runner.execute(this.job, otherJobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @@ -144,8 +135,8 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecutionOnNonRestartableJob() throws Exception { this.job = this.jobs.get("job").preventRestart() - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) - .incrementer(new RunIdIncrementer()).build(); + .start(this.steps.get("step").tasklet(throwingTasklet()).build()).incrementer(new RunIdIncrementer()) + .build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); // A failed job that is not restartable does not re-use the job params of @@ -153,40 +144,35 @@ public class JobLauncherCommandLineRunnerTests { assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); assertThatExceptionOfType(JobRestartException.class).isThrownBy(() -> { // try to re-run a failed execution - this.runner.execute(this.job, - new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); + this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); fail("expected JobRestartException"); }).withMessageContaining("JobInstance already exists and is not restartable"); } @Test public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()) .incrementer(new RunIdIncrementer()).build(); - JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) - .addLong("foo", 2L, false).toJobParameters(); + JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) + .toJobParameters(); this.runner.execute(this.job, jobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); // try to re-run a failed execution with non identifying parameters - this.runner.execute(this.job, new JobParametersBuilder(jobParameters) - .addLong("run.id", 1L).toJobParameters()); + this.runner.execute(this.job, new JobParametersBuilder(jobParameters).addLong("run.id", 1L).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); } @Test - public void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() - throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + public void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() throws Exception { + this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()) .incrementer(new RunIdIncrementer()).build(); - JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) - .addLong("foo", 2L, false).toJobParameters(); + JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) + .toJobParameters(); this.runner.execute(this.job, jobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); // try to re-run a failed execution with non identifying parameters - this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L) - .addLong("id", 2L, false).addLong("foo", 3L, false).toJobParameters()); + this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).addLong("id", 2L, false) + .addLong("foo", 3L, false).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); JobInstance jobInstance = this.jobExplorer.getJobInstance(0L); assertThat(this.jobExplorer.getJobExecutions(jobInstance)).hasSize(2); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java index 4c9fb02d592..17082f57eaf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java @@ -50,20 +50,17 @@ abstract class AbstractCacheAutoConfigurationTests { protected final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); - protected T getCacheManager( - AssertableApplicationContext loaded, Class type) { + protected T getCacheManager(AssertableApplicationContext loaded, Class type) { CacheManager cacheManager = loaded.getBean(CacheManager.class); assertThat(cacheManager).as("Wrong cache manager type").isInstanceOf(type); return type.cast(cacheManager); } @SuppressWarnings("rawtypes") - protected ContextConsumer verifyCustomizers( - String... expectedCustomizerNames) { + protected ContextConsumer verifyCustomizers(String... expectedCustomizerNames) { return (context) -> { CacheManager cacheManager = getCacheManager(context, CacheManager.class); - List expected = new ArrayList<>( - Arrays.asList(expectedCustomizerNames)); + List expected = new ArrayList<>(Arrays.asList(expectedCustomizerNames)); Map customizer = context .getBeansOfType(CacheManagerTestCustomizer.class); customizer.forEach((key, value) -> { @@ -147,8 +144,7 @@ abstract class AbstractCacheAutoConfigurationTests { } - abstract static class CacheManagerTestCustomizer - implements CacheManagerCustomizer { + abstract static class CacheManagerTestCustomizer implements CacheManagerCustomizer { T cacheManager; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index dae93c1dd53..b676ca4f30a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -93,33 +93,28 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void noEnableCaching() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run( - (context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test public void cacheManagerBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerConfiguration.class) - .run((context) -> assertThat( - getCacheManager(context, ConcurrentMapCacheManager.class) - .getCacheNames()).containsOnly("custom1")); + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .containsOnly("custom1")); } @Test public void cacheManagerFromSupportBackOff() { - this.contextRunner - .withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class) - .run((context) -> assertThat( - getCacheManager(context, ConcurrentMapCacheManager.class) - .getCacheNames()).containsOnly("custom1")); + this.contextRunner.withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class) + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .containsOnly("custom1")); } @Test public void cacheResolverFromSupportBackOff() { - this.contextRunner - .withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(CacheManager.class)); + this.contextRunner.withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test @@ -135,85 +130,69 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void notSupportedCachingMode() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=foobar") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class).hasMessageContaining( - "Failed to bind properties under 'spring.cache.type'")); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to bind properties under 'spring.cache.type'")); } @Test public void simpleCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=simple") - .run((context) -> assertThat( - getCacheManager(context, ConcurrentMapCacheManager.class) - .getCacheNames()).isEmpty()); + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .isEmpty()); } @Test public void simpleCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "simple") - .run(verifyCustomizers("allCacheManagerCustomizer", - "simpleCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); } @Test public void simpleCacheExplicitWithCacheNames() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=simple", - "spring.cache.cacheNames[0]=foo", + .withPropertyValues("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> { - ConcurrentMapCacheManager cacheManager = getCacheManager(context, - ConcurrentMapCacheManager.class); + ConcurrentMapCacheManager cacheManager = getCacheManager(context, ConcurrentMapCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); } @Test public void genericCacheWithCaches() { - this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class) - .run((context) -> { - SimpleCacheManager cacheManager = getCacheManager(context, - SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")) - .isEqualTo(context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")) - .isEqualTo(context.getBean("secondCache")); - assertThat(cacheManager.getCacheNames()).hasSize(2); - }); + this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class).run((context) -> { + SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); + assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")).isEqualTo(context.getBean("secondCache")); + assertThat(cacheManager.getCacheNames()).hasSize(2); + }); } @Test public void genericCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=generic") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("No cache manager could be auto-configured") .hasMessageContaining("GENERIC")); } @Test public void genericCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(GenericCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(GenericCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "generic") - .run(verifyCustomizers("allCacheManagerCustomizer", - "genericCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); } @Test public void genericCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class) .withPropertyValues("spring.cache.type=generic").run((context) -> { - SimpleCacheManager cacheManager = getCacheManager(context, - SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")) - .isEqualTo(context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")) - .isEqualTo(context.getBean("secondCache")); + SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); + assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")).isEqualTo(context.getBean("secondCache")); assertThat(cacheManager.getCacheNames()).hasSize(2); }); } @@ -222,126 +201,96 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void couchbaseCacheExplicit() { this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.class) .withPropertyValues("spring.cache.type=couchbase").run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, - CouchbaseCacheManager.class); + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); }); } @Test public void couchbaseCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(CouchbaseCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(CouchbaseCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "couchbase") - .run(verifyCustomizers("allCacheManagerCustomizer", - "couchbaseCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); } @Test public void couchbaseCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", - "spring.cache.cacheNames[0]=foo", + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, - CouchbaseCacheManager.class); + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache cache = cacheManager.getCache("foo"); assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(0); - assertThat(((CouchbaseCache) cache).getNativeCache()) - .isEqualTo(context.getBean("bucket")); + assertThat(((CouchbaseCache) cache).getNativeCache()).isEqualTo(context.getBean("bucket")); }); } @Test public void couchbaseCacheExplicitWithTtl() { this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", - "spring.cache.cacheNames=foo,bar", + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", "spring.cache.couchbase.expiration=2000") .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, - CouchbaseCacheManager.class); + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache cache = cacheManager.getCache("foo"); assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(2); - assertThat(((CouchbaseCache) cache).getNativeCache()) - .isEqualTo(context.getBean("bucket")); + assertThat(((CouchbaseCache) cache).getNativeCache()).isEqualTo(context.getBean("bucket")); }); } @Test public void redisCacheExplicit() { this.contextRunner.withUserConfiguration(RedisConfiguration.class) - .withPropertyValues("spring.cache.type=redis", - "spring.cache.redis.time-to-live=15000", - "spring.cache.redis.cacheNullValues=false", - "spring.cache.redis.keyPrefix=prefix", + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", + "spring.cache.redis.cacheNullValues=false", "spring.cache.redis.keyPrefix=prefix", "spring.cache.redis.useKeyPrefix=true") .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, - RedisCacheManager.class); + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration( - cacheManager); - assertThat(redisCacheConfiguration.getTtl()) - .isEqualTo(java.time.Duration.ofSeconds(15)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()) - .isFalse(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("keyName")) - .isEqualTo("prefix"); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(15)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isFalse(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("keyName")).isEqualTo("prefix"); assertThat(redisCacheConfiguration.usePrefix()).isTrue(); }); } @Test public void redisCacheWithRedisCacheConfiguration() { - this.contextRunner - .withUserConfiguration(RedisWithCacheConfigurationConfiguration.class) - .withPropertyValues("spring.cache.type=redis", - "spring.cache.redis.time-to-live=15000", + this.contextRunner.withUserConfiguration(RedisWithCacheConfigurationConfiguration.class) + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", "spring.cache.redis.keyPrefix=foo") .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, - RedisCacheManager.class); + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration( - cacheManager); - assertThat(redisCacheConfiguration.getTtl()) - .isEqualTo(java.time.Duration.ofSeconds(30)); - assertThat(redisCacheConfiguration.getKeyPrefixFor("")) - .isEqualTo("bar"); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(30)); + assertThat(redisCacheConfiguration.getKeyPrefixFor("")).isEqualTo("bar"); }); } @Test public void redisCacheWithCustomizers() { this.contextRunner.withUserConfiguration(RedisWithCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=" + "redis").run(verifyCustomizers( - "allCacheManagerCustomizer", "redisCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=" + "redis") + .run(verifyCustomizers("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); } @Test public void redisCacheExplicitWithCaches() { - this.contextRunner.withUserConfiguration(RedisConfiguration.class) - .withPropertyValues("spring.cache.type=redis", - "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, - RedisCacheManager.class); + this.contextRunner.withUserConfiguration(RedisConfiguration.class).withPropertyValues("spring.cache.type=redis", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar").run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration( - cacheManager); - assertThat(redisCacheConfiguration.getTtl()) - .isEqualTo(java.time.Duration.ofMinutes(0)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()) - .isTrue(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("test")) - .isEqualTo("test::"); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofMinutes(0)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isTrue(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("test")).isEqualTo("test::"); assertThat(redisCacheConfiguration.usePrefix()).isTrue(); }); } @@ -350,8 +299,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void noOpCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=none").run((context) -> { - NoOpCacheManager cacheManager = getCacheManager(context, - NoOpCacheManager.class); + NoOpCacheManager cacheManager = getCacheManager(context, NoOpCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); }); } @@ -360,8 +308,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void jCacheCacheNoProviderExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("No cache manager could be auto-configured") .hasMessageContaining("JCACHE")); } @@ -370,11 +317,9 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void jCacheCacheWithProvider() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); assertThat(context.getBean(javax.cache.CacheManager.class)) .isEqualTo(cacheManager.getCacheManager()); @@ -385,13 +330,10 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void jCacheCacheWithCaches() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); } @@ -400,20 +342,15 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void jCacheCacheWithCachesAndCustomConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=one", - "spring.cache.cacheNames[1]=two") + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two") .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); CompleteConfiguration defaultCacheConfiguration = context .getBean(CompleteConfiguration.class); - verify(cacheManager.getCacheManager()).createCache("one", - defaultCacheConfiguration); - verify(cacheManager.getCacheManager()).createCache("two", - defaultCacheConfiguration); + verify(cacheManager.getCacheManager()).createCache("one", defaultCacheConfiguration); + verify(cacheManager.getCacheManager()).createCache("two", defaultCacheConfiguration); }); } @@ -421,10 +358,8 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void jCacheCacheWithExistingJCacheManager() { this.contextRunner.withUserConfiguration(JCacheCustomCacheManager.class) .withPropertyValues("spring.cache.type=jcache").run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()) - .isEqualTo(context.getBean("customJCacheCacheManager")); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customJCacheCacheManager")); }); } @@ -434,8 +369,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + wrongCachingProviderClassName) - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining(wrongCachingProviderClassName)); } @@ -444,15 +378,12 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); }); } @@ -461,62 +392,49 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining("does not exist") - .hasMessageContaining(configLocation)); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) + .hasMessageContaining("does not exist").hasMessageContaining(configLocation)); } @Test public void jCacheCacheUseBeanClassLoader() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager().getClassLoader()) - .isEqualTo(context.getClassLoader()); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheManager().getClassLoader()).isEqualTo(context.getClassLoader()); }); } @Test public void hazelcastCacheExplicit() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(HazelcastAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) .withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, - HazelcastCacheManager.class); + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); // NOTE: the hazelcast implementation knows about a cache in a lazy // manner. cacheManager.getCache("defaultCache"); assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); - assertThat(context.getBean(HazelcastInstance.class)) - .isEqualTo(cacheManager.getHazelcastInstance()); + assertThat(context.getBean(HazelcastInstance.class)).isEqualTo(cacheManager.getHazelcastInstance()); }); } @Test public void hazelcastCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "hazelcast") - .run(verifyCustomizers("allCacheManagerCustomizer", - "hazelcastCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); } @Test public void hazelcastCacheWithExistingHazelcastInstance() { this.contextRunner.withUserConfiguration(HazelcastCustomHazelcastInstance.class) .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, - HazelcastCacheManager.class); + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); assertThat(cacheManager.getHazelcastInstance()) .isEqualTo(context.getBean("customHazelcastInstance")); }); @@ -525,19 +443,13 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void hazelcastCacheWithHazelcastAutoConfiguration() { String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; - this.contextRunner - .withConfiguration( - AutoConfigurations.of(HazelcastAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast", - "spring.hazelcast.config=" + hazelcastConfig) + .withPropertyValues("spring.cache.type=hazelcast", "spring.hazelcast.config=" + hazelcastConfig) .run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, - HazelcastCacheManager.class); - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(cacheManager.getHazelcastInstance()) - .isSameAs(hazelcastInstance); + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + assertThat(cacheManager.getHazelcastInstance()).isSameAs(hazelcastInstance); assertThat(hazelcastInstance.getConfig().getConfigurationFile()) .isEqualTo(new ClassPathResource(hazelcastConfig).getFile()); assertThat(cacheManager.getCache("foobar")).isNotNull(); @@ -551,14 +463,11 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT try { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", - "bar"); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); }); } @@ -577,11 +486,9 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); }); } @@ -593,24 +500,17 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void hazelcastAsJCacheWithExistingHazelcastInstance() { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); - this.contextRunner - .withConfiguration( - AutoConfigurations.of(HazelcastAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); - javax.cache.CacheManager jCacheManager = cacheManager - .getCacheManager(); - assertThat(jCacheManager).isInstanceOf( - com.hazelcast.cache.HazelcastCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); + assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); assertThat(context).hasSingleBean(HazelcastInstance.class); - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager) - .getHazelcastInstance()).isSameAs(hazelcastInstance); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) + .isSameAs(hazelcastInstance); assertThat(hazelcastInstance.getName()).isEqualTo("default-instance"); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); }); @@ -619,8 +519,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void infinispanCacheWithConfig() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", - "spring.cache.infinispan.config=infinispan.xml") + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") .run((context) -> { SpringEmbeddedCacheManager cacheManager = getCacheManager(context, SpringEmbeddedCacheManager.class); @@ -630,33 +529,28 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void infinispanCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "infinispan") - .run(verifyCustomizers("allCacheManagerCustomizer", - "infinispanCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); } @Test public void infinispanCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", - "spring.cache.cacheNames[0]=foo", + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run((context) -> assertThat( - getCacheManager(context, SpringEmbeddedCacheManager.class) - .getCacheNames()).containsOnly("foo", "bar")); + .run((context) -> assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar")); } @Test public void infinispanCacheWithCachesAndCustomConfig() { this.contextRunner.withUserConfiguration(InfinispanCustomConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", - "spring.cache.cacheNames[0]=foo", + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> { - assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class) - .getCacheNames()).containsOnly("foo", "bar"); + assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar"); verify(context.getBean(ConfigurationBuilder.class), times(2)).build(); }); } @@ -666,12 +560,10 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT String cachingProviderClassName = JCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderClassName, - "spring.cache.cacheNames[0]=foo", + "spring.cache.jcache.provider=" + cachingProviderClassName, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run((context) -> assertThat( - getCacheManager(context, JCacheCacheManager.class) - .getCacheNames()).containsOnly("foo", "bar")); + .run((context) -> assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar")); } @Test @@ -684,9 +576,8 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT "spring.cache.jcache.config=" + configLocation) .run((context) -> { Resource configResource = new ClassPathResource(configLocation); - assertThat(getCacheManager(context, JCacheCacheManager.class) - .getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); }); } @@ -694,16 +585,14 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT public void jCacheCacheWithCachesAndCustomizer() { String cachingProviderClassName = HazelcastCachingProvider.class.getName(); try { - this.contextRunner - .withUserConfiguration(JCacheWithCustomizerConfiguration.class) + this.contextRunner.withUserConfiguration(JCacheWithCustomizerConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderClassName, - "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> // see customizer - assertThat(getCacheManager(context, JCacheCacheManager.class) - .getCacheNames()).containsOnly("foo", "custom1")); + assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()).containsOnly("foo", + "custom1")); } finally { Caching.getCachingProvider(cachingProviderClassName).close(); @@ -713,42 +602,34 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void caffeineCacheWithExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", - "spring.cache.cacheNames=foo") - .run((context) -> { - CaffeineCacheManager manager = getCacheManager(context, - CaffeineCacheManager.class); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo").run((context) -> { + CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); assertThat(manager.getCacheNames()).containsOnly("foo"); Cache foo = manager.getCache("foo"); foo.get("1"); // See next tests: no spec given so stats should be disabled - assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) - .isEqualTo(0L); + assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L); }); } @Test public void caffeineCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "caffeine") - .run(verifyCustomizers("allCacheManagerCustomizer", - "caffeineCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); } @Test public void caffeineCacheWithExplicitCacheBuilder() { this.contextRunner.withUserConfiguration(CaffeineCacheBuilderConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", - "spring.cache.cacheNames=foo,bar") + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") .run(this::validateCaffeineCacheWithStats); } @Test public void caffeineCacheExplicitWithSpec() { this.contextRunner.withUserConfiguration(CaffeineCacheSpecConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", - "spring.cache.cacheNames[0]=foo", + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run(this::validateCaffeineCacheWithStats); } @@ -756,41 +637,32 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Test public void caffeineCacheExplicitWithSpecString() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", - "spring.cache.caffeine.spec=recordStats", - "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run(this::validateCaffeineCacheWithStats); } @Test public void autoConfiguredCacheManagerCanBeSwapped() { - this.contextRunner - .withUserConfiguration(CacheManagerPostProcessorConfiguration.class) + this.contextRunner.withUserConfiguration(CacheManagerPostProcessorConfiguration.class) .withPropertyValues("spring.cache.type=caffeine").run((context) -> { getCacheManager(context, SimpleCacheManager.class); - CacheManagerPostProcessor postProcessor = context - .getBean(CacheManagerPostProcessor.class); + CacheManagerPostProcessor postProcessor = context.getBean(CacheManagerPostProcessor.class); assertThat(postProcessor.cacheManagers).hasSize(1); - assertThat(postProcessor.cacheManagers.get(0)) - .isInstanceOf(CaffeineCacheManager.class); + assertThat(postProcessor.cacheManagers.get(0)).isInstanceOf(CaffeineCacheManager.class); }); } private void validateCaffeineCacheWithStats(AssertableApplicationContext context) { - CaffeineCacheManager manager = getCacheManager(context, - CaffeineCacheManager.class); + CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); assertThat(manager.getCacheNames()).containsOnly("foo", "bar"); Cache foo = manager.getCache("foo"); foo.get("1"); - assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) - .isEqualTo(1L); + assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(1L); } - private RedisCacheConfiguration getDefaultRedisCacheConfiguration( - RedisCacheManager cacheManager) { - return (RedisCacheConfiguration) ReflectionTestUtils.getField(cacheManager, - "defaultCacheConfig"); + private RedisCacheConfiguration getDefaultRedisCacheConfiguration(RedisCacheManager cacheManager) { + return (RedisCacheConfiguration) ReflectionTestUtils.getField(cacheManager, "defaultCacheConfig"); } @Configuration(proxyBeanMethods = false) @@ -828,16 +700,14 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT } @Configuration(proxyBeanMethods = false) - @Import({ GenericCacheConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ GenericCacheConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class GenericCacheAndCustomizersConfiguration { } @Configuration(proxyBeanMethods = false) @EnableCaching - @Import({ HazelcastAutoConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ HazelcastAutoConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class HazelcastCacheAndCustomizersConfiguration { } @@ -857,8 +727,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT } @Configuration(proxyBeanMethods = false) - @Import({ CouchbaseCacheConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ CouchbaseCacheConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class CouchbaseCacheAndCustomizersConfiguration { } @@ -880,9 +749,8 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Bean public org.springframework.data.redis.cache.RedisCacheConfiguration customRedisCacheConfiguration() { - return org.springframework.data.redis.cache.RedisCacheConfiguration - .defaultCacheConfig().entryTtl(java.time.Duration.ofSeconds(30)) - .prefixKeysWith("bar"); + return org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(java.time.Duration.ofSeconds(30)).prefixKeysWith("bar"); } } @@ -925,8 +793,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT JCacheManagerCustomizer myCustomizer() { return (cacheManager) -> { MutableConfiguration config = new MutableConfiguration<>(); - config.setExpiryPolicyFactory( - CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)); + config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)); config.setStatisticsEnabled(true); cacheManager.createCache("custom1", config); cacheManager.destroyCache("bar"); @@ -941,8 +808,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Bean public net.sf.ehcache.CacheManager customEhCacheCacheManager() { - net.sf.ehcache.CacheManager cacheManager = mock( - net.sf.ehcache.CacheManager.class); + net.sf.ehcache.CacheManager cacheManager = mock(net.sf.ehcache.CacheManager.class); given(cacheManager.getStatus()).willReturn(Status.STATUS_ALIVE); given(cacheManager.getCacheNames()).willReturn(new String[0]); return cacheManager; @@ -987,8 +853,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Configuration(proxyBeanMethods = false) @EnableCaching - static class CustomCacheManagerFromSupportConfiguration - extends CachingConfigurerSupport { + static class CustomCacheManagerFromSupportConfiguration extends CachingConfigurerSupport { @Override @Bean @@ -1001,8 +866,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Configuration(proxyBeanMethods = false) @EnableCaching - static class CustomCacheResolverFromSupportConfiguration - extends CachingConfigurerSupport { + static class CustomCacheResolverFromSupportConfiguration extends CachingConfigurerSupport { @Override @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java index ec4dbffe0f7..bb4997f2e79 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java @@ -66,8 +66,7 @@ public class CacheManagerCustomizersTests { assertThat(list.get(1).getCount()).isEqualTo(1); } - static class CacheNamesCacheManagerCustomizer - implements CacheManagerCustomizer { + static class CacheNamesCacheManagerCustomizer implements CacheManagerCustomizer { @Override public void customize(ConcurrentMapCacheManager cacheManager) { @@ -76,8 +75,7 @@ public class CacheManagerCustomizersTests { } - private static class TestCustomizer - implements CacheManagerCustomizer { + private static class TestCustomizer implements CacheManagerCustomizer { private int count; @@ -92,8 +90,7 @@ public class CacheManagerCustomizersTests { } - private static class TestConcurrentMapCacheManagerCustomizer - extends TestCustomizer { + private static class TestConcurrentMapCacheManagerCustomizer extends TestCustomizer { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java index 4930aae770d..3a21100a9fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions("ehcache-3*.jar") -public class EhCache2CacheAutoConfigurationTests - extends AbstractCacheAutoConfigurationTests { +public class EhCache2CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); @@ -48,10 +47,8 @@ public class EhCache2CacheAutoConfigurationTests public void ehCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=ehcache").run((context) -> { - EhCacheCacheManager cacheManager = getCacheManager(context, - EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", - "cacheTest2"); + EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", "cacheTest2"); assertThat(context.getBean(net.sf.ehcache.CacheManager.class)) .isEqualTo(cacheManager.getCacheManager()); }); @@ -59,11 +56,9 @@ public class EhCache2CacheAutoConfigurationTests @Test public void ehCacheWithCustomizers() { - this.contextRunner - .withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "ehcache") - .run(verifyCustomizers("allCacheManagerCustomizer", - "ehcacheCacheManagerCustomizer")); + .run(verifyCustomizers("allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer")); } @Test @@ -72,10 +67,8 @@ public class EhCache2CacheAutoConfigurationTests .withPropertyValues("spring.cache.type=ehcache", "spring.cache.ehcache.config=cache/ehcache-override.xml") .run((context) -> { - EhCacheCacheManager cacheManager = getCacheManager(context, - EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()) - .containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); + EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); }); } @@ -83,10 +76,8 @@ public class EhCache2CacheAutoConfigurationTests public void ehCacheWithExistingCacheManager() { this.contextRunner.withUserConfiguration(EhCacheCustomCacheManager.class) .withPropertyValues("spring.cache.type=ehcache").run((context) -> { - EhCacheCacheManager cacheManager = getCacheManager(context, - EhCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()) - .isEqualTo(context.getBean("customEhCacheCacheManager")); + EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); + assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customEhCacheCacheManager")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java index 43038a1c734..172e9bebf8b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,20 +37,16 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions("ehcache-2*.jar") -public class EhCache3CacheAutoConfigurationTests - extends AbstractCacheAutoConfigurationTests { +public class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test public void ehcache3AsJCacheWithCaches() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); } @@ -60,16 +56,13 @@ public class EhCache3CacheAutoConfigurationTests String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, - JCacheCacheManager.class); + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java index 261f1642027..9c6380355f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class MockCachingProvider implements CachingProvider { @Override @SuppressWarnings("rawtypes") - public CacheManager getCacheManager(URI uri, ClassLoader classLoader, - Properties properties) { + public CacheManager getCacheManager(URI uri, ClassLoader classLoader, Properties properties) { CacheManager cacheManager = mock(CacheManager.class); given(cacheManager.getURI()).willReturn(uri); given(cacheManager.getClassLoader()).willReturn(classLoader); @@ -53,14 +52,13 @@ public class MockCachingProvider implements CachingProvider { String cacheName = invocation.getArgument(0); return caches.get(cacheName); }); - given(cacheManager.createCache(anyString(), any(Configuration.class))) - .will((invocation) -> { - String cacheName = invocation.getArgument(0); - Cache cache = mock(Cache.class); - given(cache.getName()).willReturn(cacheName); - caches.put(cacheName, cache); - return cache; - }); + given(cacheManager.createCache(anyString(), any(Configuration.class))).will((invocation) -> { + String cacheName = invocation.getArgument(0); + Cache cache = mock(Cache.class); + given(cache.getName()).willReturn(cacheName); + caches.put(cacheName, cache); + return cache; + }); return cacheManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index a7f0c85fbb7..70b52b35ef6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -44,39 +44,32 @@ public class CassandraAutoConfigurationTests { public void createClusterWithDefault() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Cluster.class); - assertThat(context.getBean(Cluster.class).getClusterName()) - .startsWith("cluster"); + assertThat(context.getBean(Cluster.class).getClusterName()).startsWith("cluster"); }); } @Test public void createClusterWithOverrides() { - this.contextRunner - .withPropertyValues("spring.data.cassandra.cluster-name=testcluster") - .run((context) -> { - assertThat(context).hasSingleBean(Cluster.class); - assertThat(context.getBean(Cluster.class).getClusterName()) - .isEqualTo("testcluster"); - }); + this.contextRunner.withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> { + assertThat(context).hasSingleBean(Cluster.class); + assertThat(context.getBean(Cluster.class).getClusterName()).isEqualTo("testcluster"); + }); } @Test public void createCustomizeCluster() { - this.contextRunner.withUserConfiguration(MockCustomizerConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(Cluster.class); - assertThat(context).hasSingleBean(ClusterBuilderCustomizer.class); - }); + this.contextRunner.withUserConfiguration(MockCustomizerConfig.class).run((context) -> { + assertThat(context).hasSingleBean(Cluster.class); + assertThat(context).hasSingleBean(ClusterBuilderCustomizer.class); + }); } @Test public void customizerOverridesAutoConfig() { this.contextRunner.withUserConfiguration(SimpleCustomizerConfig.class) - .withPropertyValues("spring.data.cassandra.cluster-name=testcluster") - .run((context) -> { + .withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> { assertThat(context).hasSingleBean(Cluster.class); - assertThat(context.getBean(Cluster.class).getClusterName()) - .isEqualTo("overridden-name"); + assertThat(context.getBean(Cluster.class).getClusterName()).isEqualTo("overridden-name"); }); } @@ -84,34 +77,26 @@ public class CassandraAutoConfigurationTests { public void defaultPoolOptions() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Cluster.class); - PoolingOptions poolingOptions = context.getBean(Cluster.class) - .getConfiguration().getPoolingOptions(); - assertThat(poolingOptions.getIdleTimeoutSeconds()) - .isEqualTo(PoolingOptions.DEFAULT_IDLE_TIMEOUT_SECONDS); - assertThat(poolingOptions.getPoolTimeoutMillis()) - .isEqualTo(PoolingOptions.DEFAULT_POOL_TIMEOUT_MILLIS); + PoolingOptions poolingOptions = context.getBean(Cluster.class).getConfiguration().getPoolingOptions(); + assertThat(poolingOptions.getIdleTimeoutSeconds()).isEqualTo(PoolingOptions.DEFAULT_IDLE_TIMEOUT_SECONDS); + assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(PoolingOptions.DEFAULT_POOL_TIMEOUT_MILLIS); assertThat(poolingOptions.getHeartbeatIntervalSeconds()) .isEqualTo(PoolingOptions.DEFAULT_HEARTBEAT_INTERVAL_SECONDS); - assertThat(poolingOptions.getMaxQueueSize()) - .isEqualTo(PoolingOptions.DEFAULT_MAX_QUEUE_SIZE); + assertThat(poolingOptions.getMaxQueueSize()).isEqualTo(PoolingOptions.DEFAULT_MAX_QUEUE_SIZE); }); } @Test public void customizePoolOptions() { - this.contextRunner - .withPropertyValues("spring.data.cassandra.pool.idle-timeout=42", - "spring.data.cassandra.pool.pool-timeout=52", - "spring.data.cassandra.pool.heartbeat-interval=62", - "spring.data.cassandra.pool.max-queue-size=72") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.data.cassandra.pool.idle-timeout=42", + "spring.data.cassandra.pool.pool-timeout=52", "spring.data.cassandra.pool.heartbeat-interval=62", + "spring.data.cassandra.pool.max-queue-size=72").run((context) -> { assertThat(context).hasSingleBean(Cluster.class); - PoolingOptions poolingOptions = context.getBean(Cluster.class) - .getConfiguration().getPoolingOptions(); + PoolingOptions poolingOptions = context.getBean(Cluster.class).getConfiguration() + .getPoolingOptions(); assertThat(poolingOptions.getIdleTimeoutSeconds()).isEqualTo(42); assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(52); - assertThat(poolingOptions.getHeartbeatIntervalSeconds()) - .isEqualTo(62); + assertThat(poolingOptions.getHeartbeatIntervalSeconds()).isEqualTo(62); assertThat(poolingOptions.getMaxQueueSize()).isEqualTo(72); }); } @@ -119,9 +104,7 @@ public class CassandraAutoConfigurationTests { @Test public void clusterFactoryIsCalledToCreateCluster() { this.contextRunner.withUserConfiguration(ClusterFactoryConfig.class) - .run((context) -> assertThat( - context.getBean(TestClusterFactory.class).initializer) - .isNotNull()); + .run((context) -> assertThat(context.getBean(TestClusterFactory.class).initializer).isNotNull()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java index 73cb8fb6caa..d7ef8a5763a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java @@ -40,8 +40,7 @@ public class CloudServiceConnectorsAutoConfigurationTests { @Test public void testOrder() { - TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter( - new CachingMetadataReaderFactory()); + TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter(new CachingMetadataReaderFactory()); Collection classNames = new ArrayList<>(); classNames.add(MongoAutoConfiguration.class.getName()); classNames.add(DataSourceAutoConfiguration.class.getName()); @@ -49,8 +48,7 @@ public class CloudServiceConnectorsAutoConfigurationTests { classNames.add(JpaRepositoriesAutoConfiguration.class.getName()); classNames.add(CloudServiceConnectorsAutoConfiguration.class.getName()); List ordered = sorter.getInPriorityOrder(classNames); - assertThat(ordered.get(0)) - .isEqualTo(CloudServiceConnectorsAutoConfiguration.class.getName()); + assertThat(ordered.get(0)).isEqualTo(CloudServiceConnectorsAutoConfiguration.class.getName()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java index 3ba94b01b1f..3580b6f95b5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java @@ -44,10 +44,8 @@ public class AbstractNestedConditionTests { public void invalidMemberPhase() { this.contextRunner.withUserConfiguration(InvalidConfig.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getCause()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Nested condition " - + InvalidNestedCondition.class.getName() + assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Nested condition " + InvalidNestedCondition.class.getName() + " uses a configuration phase that is inappropriate for class " + OnBeanCondition.class.getName()); }); @@ -55,16 +53,13 @@ public class AbstractNestedConditionTests { @Test public void invalidNestedMemberPhase() { - this.contextRunner.withUserConfiguration(DoubleNestedConfig.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getCause()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Nested condition " - + DoubleNestedCondition.class.getName() - + " uses a configuration phase that is inappropriate for class " - + ValidNestedCondition.class.getName()); - }); + this.contextRunner.withUserConfiguration(DoubleNestedConfig.class).run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Nested condition " + DoubleNestedCondition.class.getName() + + " uses a configuration phase that is inappropriate for class " + + ValidNestedCondition.class.getName()); + }); } @Configuration(proxyBeanMethods = false) @@ -85,8 +80,7 @@ public class AbstractNestedConditionTests { } @Override - protected ConditionOutcome getFinalMatchOutcome( - MemberMatchOutcomes memberOutcomes) { + protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { return ConditionOutcome.match(); } @@ -115,8 +109,7 @@ public class AbstractNestedConditionTests { } @Override - protected ConditionOutcome getFinalMatchOutcome( - MemberMatchOutcomes memberOutcomes) { + protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { return ConditionOutcome.match(); } @@ -140,8 +133,7 @@ public class AbstractNestedConditionTests { } @Override - protected ConditionOutcome getFinalMatchOutcome( - MemberMatchOutcomes memberOutcomes) { + protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { return ConditionOutcome.match(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java index 8c88a7058fc..85dd52f3e5f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java @@ -44,20 +44,17 @@ public class AllNestedConditionsTests { @Test public void propertyA() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a") - .run(match(false)); + this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a").run(match(false)); } @Test public void propertyB() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("b:b") - .run(match(false)); + this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("b:b").run(match(false)); } @Test public void both() { - this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("a:a", "b:b").run(match(true)); + this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a", "b:b").run(match(true)); } private ContextConsumer match(boolean expected) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java index b1f6543fc42..51efe6ea5b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java @@ -47,20 +47,17 @@ public class AnyNestedConditionTests { @Test public void propertyA() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a") - .run(match(true)); + this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a").run(match(true)); } @Test public void propertyB() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("b:b") - .run(match(true)); + this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("b:b").run(match(true)); } @Test public void both() { - this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("a:a", "b:b").run(match(true)); + this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a", "b:b").run(match(true)); } private ContextConsumer match(boolean expected) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java index 217d5796926..52b22fb5cce 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java @@ -54,59 +54,54 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { public void shouldBeInSpringFactories() { List factories = SpringFactoriesLoader .loadFactories(AutoConfigurationImportListener.class, null); - assertThat(factories).hasAtLeastOneElementOfType( - ConditionEvaluationReportAutoConfigurationImportListener.class); + assertThat(factories) + .hasAtLeastOneElementOfType(ConditionEvaluationReportAutoConfigurationImportListener.class); } @Test public void onAutoConfigurationImportEventShouldRecordCandidates() { List candidateConfigurations = Collections.singletonList("Test"); Set exclusions = Collections.emptySet(); - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - candidateConfigurations, exclusions); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, candidateConfigurations, + exclusions); this.listener.onAutoConfigurationImportEvent(event); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); - assertThat(report.getUnconditionalClasses()) - .containsExactlyElementsOf(candidateConfigurations); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); + assertThat(report.getUnconditionalClasses()).containsExactlyElementsOf(candidateConfigurations); } @Test public void onAutoConfigurationImportEventShouldRecordExclusions() { List candidateConfigurations = Collections.emptyList(); Set exclusions = Collections.singleton("Test"); - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - candidateConfigurations, exclusions); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, candidateConfigurations, + exclusions); this.listener.onAutoConfigurationImportEvent(event); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); assertThat(report.getExclusions()).containsExactlyElementsOf(exclusions); } @Test public void onAutoConfigurationImportEventShouldApplyExclusionsGlobally() { - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - Arrays.asList("First", "Second"), Collections.emptySet()); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, Arrays.asList("First", "Second"), + Collections.emptySet()); this.listener.onAutoConfigurationImportEvent(event); - AutoConfigurationImportEvent anotherEvent = new AutoConfigurationImportEvent(this, - Collections.emptyList(), Collections.singleton("First")); + AutoConfigurationImportEvent anotherEvent = new AutoConfigurationImportEvent(this, Collections.emptyList(), + Collections.singleton("First")); this.listener.onAutoConfigurationImportEvent(anotherEvent); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); assertThat(report.getUnconditionalClasses()).containsExactly("Second"); assertThat(report.getExclusions()).containsExactly("First"); } @Test public void onAutoConfigurationImportEventShouldApplyExclusionsGloballyWhenExclusionIsAlreadyApplied() { - AutoConfigurationImportEvent excludeEvent = new AutoConfigurationImportEvent(this, - Collections.emptyList(), Collections.singleton("First")); + AutoConfigurationImportEvent excludeEvent = new AutoConfigurationImportEvent(this, Collections.emptyList(), + Collections.singleton("First")); this.listener.onAutoConfigurationImportEvent(excludeEvent); - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - Arrays.asList("First", "Second"), Collections.emptySet()); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, Arrays.asList("First", "Second"), + Collections.emptySet()); this.listener.onAutoConfigurationImportEvent(event); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); assertThat(report.getUnconditionalClasses()).containsExactly("Second"); assertThat(report.getExclusions()).containsExactly("First"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java index 4a7a2f4c8f6..46425c13a73 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java @@ -93,25 +93,21 @@ public class ConditionEvaluationReportTests { @Test public void parent() { this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); - ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()); + ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); assertThat(this.report).isNotEqualTo(nullValue()); assertThat(this.report.getParent()).isNotEqualTo(nullValue()); - ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()); + ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); assertThat(this.report.getParent()).isSameAs(ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory())); + .get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory())); } @Test public void parentBottomUp() { this.beanFactory = new DefaultListableBeanFactory(); // NB: overrides setup this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); - ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()); + ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); this.report = ConditionEvaluationReport.get(this.beanFactory); assertThat(this.report).isNotNull(); assertThat(this.report).isNotSameAs(this.report.getParent()); @@ -127,8 +123,7 @@ public class ConditionEvaluationReportTests { this.report.recordConditionEvaluation("a", this.condition1, this.outcome1); this.report.recordConditionEvaluation("a", this.condition2, this.outcome2); this.report.recordConditionEvaluation("b", this.condition3, this.outcome3); - Map map = this.report - .getConditionAndOutcomesBySource(); + Map map = this.report.getConditionAndOutcomesBySource(); assertThat(map.size()).isEqualTo(2); Iterator iterator = map.get("a").iterator(); ConditionAndOutcome conditionAndOutcome = iterator.next(); @@ -148,15 +143,13 @@ public class ConditionEvaluationReportTests { @Test public void fullMatch() { prepareMatches(true, true, true); - assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()) - .isTrue(); + assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()).isTrue(); } @Test public void notFullMatch() { prepareMatches(true, false, true); - assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()) - .isFalse(); + assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()).isFalse(); } private void prepareMatches(boolean m1, boolean m2, boolean m3) { @@ -171,8 +164,8 @@ public class ConditionEvaluationReportTests { @Test @SuppressWarnings("resource") public void springBootConditionPopulatesReport() { - ConditionEvaluationReport report = ConditionEvaluationReport.get( - new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); + ConditionEvaluationReport report = ConditionEvaluationReport + .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); assertThat(report.getConditionAndOutcomesBySource().size()).isNotEqualTo(0); } @@ -196,24 +189,19 @@ public class ConditionEvaluationReportTests { @Test public void duplicateOutcomes() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - DuplicateConfig.class); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DuplicateConfig.class); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); String autoconfigKey = MultipartAutoConfiguration.class.getName(); - ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource() - .get(autoconfigKey); + ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource().get(autoconfigKey); assertThat(outcomes).isNotEqualTo(nullValue()); assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2); List messages = new ArrayList<>(); for (ConditionAndOutcome outcome : outcomes) { messages.add(outcome.getOutcome().getMessage()); } - assertThat(messages).areAtLeastOne( - Matched.by(containsString("@ConditionalOnClass found required classes " - + "'javax.servlet.Servlet', 'org.springframework.web.multipart." - + "support.StandardServletMultipartResolver', " - + "'javax.servlet.MultipartConfigElement'"))); + assertThat(messages).areAtLeastOne(Matched.by(containsString("@ConditionalOnClass found required classes " + + "'javax.servlet.Servlet', 'org.springframework.web.multipart." + + "support.StandardServletMultipartResolver', " + "'javax.servlet.MultipartConfigElement'"))); context.close(); } @@ -223,10 +211,8 @@ public class ConditionEvaluationReportTests { TestPropertyValues.of("test.present=true").applyTo(context); context.register(NegativeOuterConfig.class); context.refresh(); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); - Map sourceOutcomes = report - .getConditionAndOutcomesBySource(); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); + Map sourceOutcomes = report.getConditionAndOutcomesBySource(); assertThat(context.containsBean("negativeOuterPositiveInnerBean")).isFalse(); String negativeConfig = NegativeOuterConfig.class.getName(); assertThat(sourceOutcomes.get(negativeConfig).isFullMatch()).isFalse(); @@ -241,8 +227,7 @@ public class ConditionEvaluationReportTests { org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration.class, org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration.class); context.refresh(); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); assertThat(report.getConditionAndOutcomesBySource()).containsKeys( "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration", @@ -257,14 +242,13 @@ public class ConditionEvaluationReportTests { org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration.class, org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration.class); context.refresh(); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); String reportMessage = new ConditionEvaluationReportMessage(report).toString(); assertThat(reportMessage).contains("WebMvcAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration"); - assertThat(reportMessage).doesNotContain( - "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); + assertThat(reportMessage) + .doesNotContain("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); context.close(); } @@ -308,8 +292,7 @@ public class ConditionEvaluationReportTests { } - static class TestMatchCondition extends SpringBootCondition - implements ConfigurationCondition { + static class TestMatchCondition extends SpringBootCondition implements ConfigurationCondition { private final ConfigurationPhase phase; @@ -326,8 +309,7 @@ public class ConditionEvaluationReportTests { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { return new ConditionOutcome(this.match, ClassUtils.getShortName(getClass())); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java index 2d7d38e6317..ad7afdde95d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java @@ -76,22 +76,19 @@ public class ConditionMessageTests { @Test public void andConditionWhenUsingClassShouldIncludeCondition() { - ConditionMessage message = ConditionMessage.empty().andCondition(Test.class) - .because("OK"); + ConditionMessage message = ConditionMessage.empty().andCondition(Test.class).because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test public void andConditionWhenUsingStringShouldIncludeCondition() { - ConditionMessage message = ConditionMessage.empty().andCondition("@Test") - .because("OK"); + ConditionMessage message = ConditionMessage.empty().andCondition("@Test").because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test public void andConditionWhenIncludingDetailsShouldIncludeCondition() { - ConditionMessage message = ConditionMessage.empty() - .andCondition(Test.class, "(a=b)").because("OK"); + ConditionMessage message = ConditionMessage.empty().andCondition(Test.class, "(a=b)").because("OK"); assertThat(message.toString()).isEqualTo("@Test (a=b) OK"); } @@ -124,78 +121,70 @@ public class ConditionMessageTests { @Test public void forConditionWhenClassShouldIncludeCondition() { - ConditionMessage message = ConditionMessage.forCondition(Test.class, "(a=b)") - .because("OK"); + ConditionMessage message = ConditionMessage.forCondition(Test.class, "(a=b)").because("OK"); assertThat(message.toString()).isEqualTo("@Test (a=b) OK"); } @Test public void foundExactlyShouldConstructMessage() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .foundExactly("abc"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).foundExactly("abc"); assertThat(message.toString()).isEqualTo("@Test found abc"); } @Test public void foundWhenSingleElementShouldUseSingular() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("bean", "beans").items("a"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a"); assertThat(message.toString()).isEqualTo("@Test found bean a"); } @Test public void foundNoneAtAllShouldConstructMessage() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("no beans").atAll(); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("no beans").atAll(); assertThat(message.toString()).isEqualTo("@Test found no beans"); } @Test public void foundWhenMultipleElementsShouldUsePlural() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("bean", "beans").items("a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a", "b", + "c"); assertThat(message.toString()).isEqualTo("@Test found beans a, b, c"); } @Test public void foundWhenQuoteStyleShouldQuote() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("bean", "beans").items(Style.QUOTE, "a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items(Style.QUOTE, + "a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test found beans 'a', 'b', 'c'"); } @Test public void didNotFindWhenSingleElementShouldUseSingular() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .didNotFind("class", "classes").items("a"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a"); assertThat(message.toString()).isEqualTo("@Test did not find class a"); } @Test public void didNotFindWhenMultipleElementsShouldUsePlural() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .didNotFind("class", "classes").items("a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a", + "b", "c"); assertThat(message.toString()).isEqualTo("@Test did not find classes a, b, c"); } @Test public void resultedInShouldConstructMessage() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .resultedIn("Green"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).resultedIn("Green"); assertThat(message.toString()).isEqualTo("@Test resulted in Green"); } @Test public void notAvailableShouldConstructMessage() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .notAvailable("JMX"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).notAvailable("JMX"); assertThat(message.toString()).isEqualTo("@Test JMX is not available"); } @Test public void availableShouldConstructMessage() { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .available("JMX"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).available("JMX"); assertThat(message.toString()).isEqualTo("@Test JMX is available"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java index 466a341215e..9307ae4002f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java @@ -56,43 +56,39 @@ public class ConditionalOnBeanTests { @Test public void testNameOnBeanCondition() { - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnBeanNameConfiguration.class).run(this::hasBarBean); + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) + .run(this::hasBarBean); } @Test public void testNameAndTypeOnBeanCondition() { - this.contextRunner - .withUserConfiguration(FooConfiguration.class, - OnBeanNameAndTypeConfiguration.class) + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test public void testNameOnBeanConditionReverseOrder() { // Ideally this should be true - this.contextRunner - .withUserConfiguration(OnBeanNameConfiguration.class, - FooConfiguration.class) + this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test public void testClassOnBeanCondition() { - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnBeanClassConfiguration.class).run(this::hasBarBean); + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassConfiguration.class) + .run(this::hasBarBean); } @Test public void testClassOnBeanClassNameCondition() { - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnBeanClassNameConfiguration.class).run(this::hasBarBean); + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassNameConfiguration.class) + .run(this::hasBarBean); } @Test public void testOnBeanConditionWithXml() { - this.contextRunner.withUserConfiguration(XmlConfiguration.class, - OnBeanNameConfiguration.class).run(this::hasBarBean); + this.contextRunner.withUserConfiguration(XmlConfiguration.class, OnBeanNameConfiguration.class) + .run(this::hasBarBean); } @Test @@ -104,15 +100,13 @@ public class ConditionalOnBeanTests { @Test public void testAnnotationOnBeanCondition() { - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnAnnotationConfiguration.class).run(this::hasBarBean); + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) + .run(this::hasBarBean); } @Test public void testOnMissingBeanType() { - this.contextRunner - .withUserConfiguration(FooConfiguration.class, - OnBeanMissingClassConfiguration.class) + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanMissingClassConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @@ -120,16 +114,16 @@ public class ConditionalOnBeanTests { public void withPropertyPlaceholderClassName() { this.contextRunner .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class, - WithPropertyPlaceholderClassName.class, - OnBeanClassConfiguration.class) + WithPropertyPlaceholderClassName.class, OnBeanClassConfiguration.class) .withPropertyValues("mybeanclass=java.lang.String") .run((context) -> assertThat(context).hasNotFailed()); } @Test public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { - this.contextRunner.withUserConfiguration(FactoryBeanConfiguration.class, - OnAnnotationWithFactoryBeanConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class) + .run((context) -> { assertThat(context).hasBean("bar"); assertThat(context).hasSingleBean(ExampleBean.class); }); @@ -142,10 +136,8 @@ public class ConditionalOnBeanTests { @Test public void conditionEvaluationConsidersChangeInTypeWhenBeanIsOverridden() { - this.contextRunner - .withUserConfiguration(OriginalDefinition.class, - OverridingDefinition.class, ConsumingConfiguration.class) - .run((context) -> { + this.contextRunner.withUserConfiguration(OriginalDefinition.class, OverridingDefinition.class, + ConsumingConfiguration.class).run((context) -> { assertThat(context).hasBean("testBean"); assertThat(context).hasSingleBean(Integer.class); assertThat(context).doesNotHaveBean(ConsumingConfiguration.class); @@ -157,17 +149,15 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("otherExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); } @Test public void parameterizedContainerWhenValueIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test @@ -175,8 +165,7 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("otherExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); } @Test @@ -184,8 +173,8 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "customExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test @@ -193,8 +182,8 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "customExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test @@ -202,8 +191,8 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "customExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test @@ -211,8 +200,8 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "customExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test @@ -220,18 +209,15 @@ public class ConditionalOnBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "customExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } - private Consumer exampleBeanRequirement( - String... names) { + private Consumer exampleBeanRequirement(String... names) { return (context) -> { String[] beans = context.getBeanNamesForType(ExampleBean.class); - String[] containers = context - .getBeanNamesForType(TestParameterizedContainer.class); - assertThat(StringUtils.concatenateStringArrays(beans, containers)) - .containsOnly(names); + String[] containers = context.getBeanNamesForType(TestParameterizedContainer.class); + assertThat(StringUtils.concatenateStringArrays(beans, containers)).containsOnly(names); }; } @@ -352,8 +338,7 @@ public class ConditionalOnBeanTests { } - protected static class WithPropertyPlaceholderClassNameRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class WithPropertyPlaceholderClassNameRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, @@ -458,8 +443,7 @@ public class ConditionalOnBeanTests { static class ParameterizedConditionWithValueConfig { @Bean - @ConditionalOnBean(value = CustomExampleBean.class, - parameterizedContainer = TestParameterizedContainer.class) + @ConditionalOnBean(value = CustomExampleBean.class, parameterizedContainer = TestParameterizedContainer.class) public CustomExampleBean conditionalCustomExampleBean() { return new CustomExampleBean(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java index d00590de9b3..2b49d7c1f80 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java @@ -41,47 +41,39 @@ public class ConditionalOnClassTests { @Test public void testVanillaOnClassCondition() { - this.contextRunner - .withUserConfiguration(BasicConfiguration.class, FooConfiguration.class) + this.contextRunner.withUserConfiguration(BasicConfiguration.class, FooConfiguration.class) .run(this::hasBarBean); } @Test public void testMissingOnClassCondition() { - this.contextRunner - .withUserConfiguration(MissingConfiguration.class, FooConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context).hasBean("foo"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + this.contextRunner.withUserConfiguration(MissingConfiguration.class, FooConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context).hasBean("foo"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test public void testOnClassConditionWithXml() { - this.contextRunner - .withUserConfiguration(BasicConfiguration.class, XmlConfiguration.class) + this.contextRunner.withUserConfiguration(BasicConfiguration.class, XmlConfiguration.class) .run(this::hasBarBean); } @Test public void testOnClassConditionWithCombinedXml() { - this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class) - .run(this::hasBarBean); + this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class).run(this::hasBarBean); } @Test public void onClassConditionOutputShouldNotContainConditionalOnMissingClassInMessage() { - this.contextRunner.withUserConfiguration(BasicConfiguration.class) - .run((context) -> { - Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()) - .getConditionAndOutcomesBySource().values(); - String message = conditionAndOutcomes.iterator().next().iterator() - .next().getOutcome().getMessage(); - assertThat(message).doesNotContain( - "@ConditionalOnMissingClass did not find unwanted class"); - }); + this.contextRunner.withUserConfiguration(BasicConfiguration.class).run((context) -> { + Collection conditionAndOutcomes = ConditionEvaluationReport + .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() + .values(); + String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); + assertThat(message).doesNotContain("@ConditionalOnMissingClass did not find unwanted class"); + }); } private void hasBarBean(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java index 88707dab241..dbff7efe2e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java @@ -41,15 +41,13 @@ public class ConditionalOnCloudPlatformTests { @Test public void outcomeWhenCloudfoundryPlatformPresentShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) - .withPropertyValues("VCAP_APPLICATION:---") - .run((context) -> assertThat(context).hasBean("foo")); + .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); } @Test public void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformOnMethodConfig.class) - .withPropertyValues("VCAP_APPLICATION:---") - .run((context) -> assertThat(context).hasBean("foo")); + .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java index 77b85cc45a7..c6158e08423 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java @@ -65,11 +65,9 @@ public class ConditionalOnExpressionTests { MockEnvironment environment = new MockEnvironment(); ConditionContext conditionContext = mock(ConditionContext.class); given(conditionContext.getEnvironment()).willReturn(environment); - ConditionOutcome outcome = condition.getMatchOutcome(conditionContext, - mockMetaData("invalid-spel")); + ConditionOutcome outcome = condition.getMatchOutcome(conditionContext, mockMetaData("invalid-spel")); assertThat(outcome.isMatch()).isFalse(); - assertThat(outcome.getMessage()).contains("invalid-spel") - .contains("no BeanFactory available"); + assertThat(outcome.getMessage()).contains("invalid-spel").contains("no BeanFactory available"); } private AnnotatedTypeMetadata mockMetaData(String value) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java index 766190b56f7..395aeb98573 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java @@ -77,18 +77,16 @@ public class ConditionalOnJavaTests { @Test public void equalOrNewerMessage() { - ConditionOutcome outcome = this.condition.getMatchOutcome(Range.EQUAL_OR_NEWER, - JavaVersion.NINE, JavaVersion.EIGHT); - assertThat(outcome.getMessage()) - .isEqualTo("@ConditionalOnJava (1.8 or newer) found 1.9"); + ConditionOutcome outcome = this.condition.getMatchOutcome(Range.EQUAL_OR_NEWER, JavaVersion.NINE, + JavaVersion.EIGHT); + assertThat(outcome.getMessage()).isEqualTo("@ConditionalOnJava (1.8 or newer) found 1.9"); } @Test public void olderThanMessage() { - ConditionOutcome outcome = this.condition.getMatchOutcome(Range.OLDER_THAN, - JavaVersion.NINE, JavaVersion.EIGHT); - assertThat(outcome.getMessage()) - .isEqualTo("@ConditionalOnJava (older than 1.8) found 1.9"); + ConditionOutcome outcome = this.condition.getMatchOutcome(Range.OLDER_THAN, JavaVersion.NINE, + JavaVersion.EIGHT); + assertThat(outcome.getMessage()).isEqualTo("@ConditionalOnJava (older than 1.8) found 1.9"); } @Test @@ -100,24 +98,20 @@ public class ConditionalOnJavaTests { @Test public void java8IsTheFallback() throws Exception { Assume.javaEight(); - assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class)) - .isEqualTo("1.8"); + assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class)).isEqualTo("1.8"); } private String getJavaVersion(Class... hiddenClasses) throws Exception { FilteredClassLoader classLoader = new FilteredClassLoader(hiddenClasses); Class javaVersionClass = classLoader.loadClass(JavaVersion.class.getName()); - Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass, - "getJavaVersion"); + Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass, "getJavaVersion"); Object javaVersion = ReflectionUtils.invokeMethod(getJavaVersionMethod, null); classLoader.close(); return javaVersion.toString(); } - private void testBounds(Range range, JavaVersion runningVersion, JavaVersion version, - boolean expected) { - ConditionOutcome outcome = this.condition.getMatchOutcome(range, runningVersion, - version); + private void testBounds(Range range, JavaVersion runningVersion, JavaVersion version, boolean expected) { + ConditionOutcome outcome = this.condition.getMatchOutcome(range, runningVersion, version); assertThat(outcome.isMatch()).as(outcome.getMessage()).isEqualTo(expected); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java index 1fb071770be..794fa68076f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java @@ -56,16 +56,14 @@ public class ConditionalOnJndiTests { @BeforeEach public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @AfterEach public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -75,18 +73,14 @@ public class ConditionalOnJndiTests { @Test public void jndiNotAvailable() { - this.contextRunner - .withUserConfiguration(JndiAvailableConfiguration.class, - JndiConditionConfiguration.class) + this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test public void jndiAvailable() { setupJndi(); - this.contextRunner - .withUserConfiguration(JndiAvailableConfiguration.class, - JndiConditionConfiguration.class) + this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(String.class)); } @@ -107,31 +101,27 @@ public class ConditionalOnJndiTests { @Test public void jndiLocationNotFound() { - ConditionOutcome outcome = this.condition.getMatchOutcome(null, - mockMetaData("java:/a")); + ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a")); assertThat(outcome.isMatch()).isFalse(); } @Test public void jndiLocationFound() { this.condition.setFoundLocation("java:/b"); - ConditionOutcome outcome = this.condition.getMatchOutcome(null, - mockMetaData("java:/a", "java:/b")); + ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a", "java:/b")); assertThat(outcome.isMatch()).isTrue(); } private void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } private AnnotatedTypeMetadata mockMetaData(String... value) { AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); Map attributes = new HashMap<>(); attributes.put("value", value); - given(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())) - .willReturn(attributes); + given(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())).willReturn(attributes); return metadata; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java index 1b419c14932..8a0be3def18 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java @@ -65,8 +65,8 @@ public class ConditionalOnMissingBeanTests { @Test public void testNameOnMissingBeanCondition() { - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnBeanNameConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean("bar"); assertThat(context.getBean("foo")).isEqualTo("foo"); }); @@ -74,8 +74,8 @@ public class ConditionalOnMissingBeanTests { @Test public void testNameOnMissingBeanConditionReverseOrder() { - this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, - FooConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) + .run((context) -> { // Ideally this would be doesNotHaveBean, but the ordering is a // problem assertThat(context).hasBean("bar"); @@ -88,9 +88,7 @@ public class ConditionalOnMissingBeanTests { // Arguably this should be hasBean, but as things are implemented the conditions // specified in the different attributes of @ConditionalOnBean are combined with // logical OR (not AND) so if any of them match the condition is true. - this.contextRunner - .withUserConfiguration(FooConfiguration.class, - OnBeanNameAndTypeConfiguration.class) + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @@ -99,8 +97,7 @@ public class ConditionalOnMissingBeanTests { this.contextRunner.withUserConfiguration(FooConfiguration.class) .run((parent) -> new ApplicationContextRunner().withParent(parent) .withUserConfiguration(HierarchyConsidered.class) - .run((context) -> assertThat(context.containsLocalBean("bar")) - .isFalse())); + .run((context) -> assertThat(context.containsLocalBean("bar")).isFalse())); } @Test @@ -108,22 +105,19 @@ public class ConditionalOnMissingBeanTests { this.contextRunner.withUserConfiguration(FooConfiguration.class) .run((parent) -> new ApplicationContextRunner().withParent(parent) .withUserConfiguration(HierarchyNotConsidered.class) - .run((context) -> assertThat(context.containsLocalBean("bar")) - .isTrue())); + .run((context) -> assertThat(context.containsLocalBean("bar")).isTrue())); } @Test public void impliedOnBeanMethod() { - this.contextRunner - .withUserConfiguration(ExampleBeanConfiguration.class, - ImpliedOnBeanMethod.class) + this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class, ImpliedOnBeanMethod.class) .run((context) -> assertThat(context).hasSingleBean(ExampleBean.class)); } @Test public void testAnnotationOnMissingBeanCondition() { - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnAnnotationConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean("bar"); assertThat(context.getBean("foo")).isEqualTo("foo"); }); @@ -132,9 +126,10 @@ public class ConditionalOnMissingBeanTests { @Test public void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { // Rigorous test for SPR-11069 - this.contextRunner.withUserConfiguration(FooConfiguration.class, - OnAnnotationConfiguration.class, FactoryBeanXmlConfiguration.class, - PropertyPlaceholderAutoConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class, + FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean("bar"); assertThat(context).hasBean("example"); assertThat(context.getBean("foo")).isEqualTo("foo"); @@ -144,123 +139,89 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithFactoryBean() { this.contextRunner - .withUserConfiguration(FactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + .withUserConfiguration(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithComponentScannedFactoryBean() { this.contextRunner - .withUserConfiguration( - ComponentScannedFactoryBeanBeanMethodConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { - this.contextRunner.withUserConfiguration( - ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + this.contextRunner + .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { this.contextRunner - .withUserConfiguration( - FactoryBeanWithBeanMethodArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) + .withUserConfiguration(FactoryBeanWithBeanMethodArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) .withPropertyValues("theValue=foo") - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithConcreteFactoryBean() { this.contextRunner - .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { // We could not tell that the FactoryBean would ultimately create an ExampleBean this.contextRunner - .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class) - .hasSize(2)); + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2)); } @Test public void testOnMissingBeanConditionWithRegisteredFactoryBean() { this.contextRunner - .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { this.contextRunner - .withUserConfiguration( - NonspecificFactoryBeanClassAttributeConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .withUserConfiguration(NonspecificFactoryBeanClassAttributeConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { this.contextRunner - .withUserConfiguration( - NonspecificFactoryBeanStringAttributeConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .withUserConfiguration(NonspecificFactoryBeanStringAttributeConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithFactoryBeanInXml() { this.contextRunner - .withUserConfiguration(FactoryBeanXmlConfiguration.class, - ConditionalOnFactoryBean.class, + .withUserConfiguration(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat( - context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory")); + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test public void testOnMissingBeanConditionWithIgnoredSubclass() { this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclass.class, - PropertyPlaceholderAutoConfiguration.class).run((context) -> { + ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { assertThat(context).getBeans(ExampleBean.class).hasSize(2); assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); }); @@ -269,8 +230,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithIgnoredSubclassByName() { this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclassByName.class, - PropertyPlaceholderAutoConfiguration.class).run((context) -> { + ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { assertThat(context).getBeans(ExampleBean.class).hasSize(2); assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); }); @@ -279,23 +239,18 @@ public class ConditionalOnMissingBeanTests { @Test public void grandparentIsConsideredWhenUsingAncestorsStrategy() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class) - .run((grandparent) -> new ApplicationContextRunner() - .withParent(grandparent) + .run((grandparent) -> new ApplicationContextRunner().withParent(grandparent) .run((parent) -> new ApplicationContextRunner().withParent(parent) .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) - .run((context) -> assertThat(context) - .getBeans(ExampleBean.class).hasSize(1)))); + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(1)))); } @Test public void currentContextIsIgnoredWhenUsingAncestorsStrategy() { - this.contextRunner - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class) - .hasSize(2))); + this.contextRunner.run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2))); } @Test @@ -312,17 +267,15 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "otherExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); } @Test public void parameterizedContainerWhenValueIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test @@ -330,8 +283,8 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement( - "otherExampleBean", "conditionalCustomExampleBean"))); + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); } @Test @@ -339,8 +292,7 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test @@ -348,8 +300,7 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test @@ -357,8 +308,7 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test @@ -366,8 +316,7 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test @@ -375,18 +324,14 @@ public class ConditionalOnMissingBeanTests { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean"))); + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } - private Consumer exampleBeanRequirement( - String... names) { + private Consumer exampleBeanRequirement(String... names) { return (context) -> { String[] beans = context.getBeanNamesForType(ExampleBean.class); - String[] containers = context - .getBeanNamesForType(TestParameterizedContainer.class); - assertThat(StringUtils.concatenateStringArrays(beans, containers)) - .containsOnly(names); + String[] containers = context.getBeanNamesForType(TestParameterizedContainer.class); + assertThat(StringUtils.concatenateStringArrays(beans, containers)).containsOnly(names); }; } @@ -454,8 +399,7 @@ public class ConditionalOnMissingBeanTests { protected static class FactoryBeanWithBeanMethodArgumentsConfiguration { @Bean - public FactoryBean exampleBeanFactoryBean( - @Value("${theValue}") String value) { + public FactoryBean exampleBeanFactoryBean(@Value("${theValue}") String value) { return new ExampleFactoryBean(value); } @@ -488,19 +432,14 @@ public class ConditionalOnMissingBeanTests { } - protected static class NonspecificFactoryBeanClassAttributeRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class NonspecificFactoryBeanClassAttributeRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata meta, - BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(NonspecificFactoryBean.class); + public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(NonspecificFactoryBean.class); builder.addConstructorArgValue("foo"); - builder.getBeanDefinition().setAttribute( - OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, ExampleBean.class); - registry.registerBeanDefinition("exampleBeanFactoryBean", - builder.getBeanDefinition()); + builder.getBeanDefinition().setAttribute(OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, ExampleBean.class); + registry.registerBeanDefinition("exampleBeanFactoryBean", builder.getBeanDefinition()); } } @@ -511,20 +450,15 @@ public class ConditionalOnMissingBeanTests { } - protected static class NonspecificFactoryBeanStringAttributeRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class NonspecificFactoryBeanStringAttributeRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata meta, - BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(NonspecificFactoryBean.class); + public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(NonspecificFactoryBean.class); builder.addConstructorArgValue("foo"); - builder.getBeanDefinition().setAttribute( - OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, + builder.getBeanDefinition().setAttribute(OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, ExampleBean.class.getName()); - registry.registerBeanDefinition("exampleBeanFactoryBean", - builder.getBeanDefinition()); + registry.registerBeanDefinition("exampleBeanFactoryBean", builder.getBeanDefinition()); } } @@ -538,13 +472,10 @@ public class ConditionalOnMissingBeanTests { protected static class FactoryBeanRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata meta, - BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(ExampleFactoryBean.class); + public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ExampleFactoryBean.class); builder.addConstructorArgValue("foo"); - registry.registerBeanDefinition("exampleBeanFactoryBean", - builder.getBeanDefinition()); + registry.registerBeanDefinition("exampleBeanFactoryBean", builder.getBeanDefinition()); } } @@ -570,8 +501,7 @@ public class ConditionalOnMissingBeanTests { protected static class ConditionalOnIgnoredSubclass { @Bean - @ConditionalOnMissingBean(value = ExampleBean.class, - ignored = CustomExampleBean.class) + @ConditionalOnMissingBean(value = ExampleBean.class, ignored = CustomExampleBean.class) public ExampleBean exampleBean() { return new ExampleBean("test"); } @@ -778,8 +708,7 @@ public class ConditionalOnMissingBeanTests { static class ParameterizedConditionWithReturnTypeConfig { @Bean - @ConditionalOnMissingBean( - parameterizedContainer = TestParameterizedContainer.class) + @ConditionalOnMissingBean(parameterizedContainer = TestParameterizedContainer.class) public CustomExampleBean conditionalCustomExampleBean() { return new CustomExampleBean(); } @@ -790,8 +719,7 @@ public class ConditionalOnMissingBeanTests { static class ParameterizedConditionWithReturnRegistrationTypeConfig { @Bean - @ConditionalOnMissingBean( - parameterizedContainer = TestParameterizedContainer.class) + @ConditionalOnMissingBean(parameterizedContainer = TestParameterizedContainer.class) public TestParameterizedContainer conditionalCustomExampleBean() { return new TestParameterizedContainer<>(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java index 2b45e5519d9..0baf4744b56 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java @@ -41,25 +41,21 @@ public class ConditionalOnNotWebApplicationTests { @Test public void testNotWebApplicationWithServletContext() { - new WebApplicationContextRunner() - .withUserConfiguration(NotWebApplicationConfiguration.class) + new WebApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test public void testNotWebApplicationWithReactiveContext() { new ReactiveWebApplicationContextRunner() - .withUserConfiguration(ReactiveApplicationConfig.class, - NotWebApplicationConfiguration.class) + .withUserConfiguration(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test public void testNotWebApplication() { - new ApplicationContextRunner() - .withUserConfiguration(NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).getBeans(String.class) - .containsExactly(entry("none", "none"))); + new ApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) + .run((context) -> assertThat(context).getBeans(String.class).containsExactly(entry("none", "none"))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index 4090ad6fb80..27b4c19ab20 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -60,8 +60,7 @@ public class ConditionalOnPropertyTests { @Test public void allPropertiesAreDefined() { - load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", - "property2=value2"); + load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -73,29 +72,25 @@ public class ConditionalOnPropertyTests { @Test public void propertyValueEqualsFalse() { - load(MultiplePropertiesRequiredConfiguration.class, "property1=false", - "property2=value2"); + load(MultiplePropertiesRequiredConfiguration.class, "property1=false", "property2=value2"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void propertyValueEqualsFALSE() { - load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", - "property2=value2"); + load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", "property2=value2"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void relaxedName() { - load(RelaxedPropertiesRequiredConfiguration.class, - "spring.theRelaxedProperty=value1"); + load(RelaxedPropertiesRequiredConfiguration.class, "spring.theRelaxedProperty=value1"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void prefixWithoutPeriod() { - load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, - "spring.property=value1"); + load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, "spring.property=value1"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -181,8 +176,7 @@ public class ConditionalOnPropertyTests { @Test public void multiValuesAllSet() { - load(MultiValuesConfig.class, "simple.my-property:bar", - "simple.my-another-property:bar"); + load(MultiValuesConfig.class, "simple.my-property:bar", "simple.my-another-property:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -200,16 +194,14 @@ public class ConditionalOnPropertyTests { @Test public void nameOrValueMustBeSpecified() { - assertThatIllegalStateException() - .isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) + assertThatIllegalStateException().isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) .satisfies(causeMessageContaining( "The name or value attribute of @ConditionalOnProperty must be specified")); } @Test public void nameAndValueMustNotBeSpecified() { - assertThatIllegalStateException() - .isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) + assertThatIllegalStateException().isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) .satisfies(causeMessageContaining( "The name and value attributes of @ConditionalOnProperty are exclusive")); } @@ -250,15 +242,14 @@ public class ConditionalOnPropertyTests { @Test public void metaAndDirectAnnotationConditionMatchesWhenBothPropertiesAreSet() { - load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true", - "my.other.feature.enabled=true"); + load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true", "my.other.feature.enabled=true"); assertThat(this.context.containsBean("foo")).isTrue(); } private void load(Class config, String... environment) { TestPropertyValues.of(environment).applyTo(this.environment); - this.context = new SpringApplicationBuilder(config).environment(this.environment) - .web(WebApplicationType.NONE).run(); + this.context = new SpringApplicationBuilder(config).environment(this.environment).web(WebApplicationType.NONE) + .run(); } @Configuration(proxyBeanMethods = false) @@ -296,8 +287,7 @@ public class ConditionalOnPropertyTests { @Configuration(proxyBeanMethods = false) // i.e ${simple.myProperty:true} - @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", matchIfMissing = true) static class EnabledIfNotConfiguredOtherwiseConfig { @Bean @@ -309,8 +299,7 @@ public class ConditionalOnPropertyTests { @Configuration(proxyBeanMethods = false) // i.e ${simple.myProperty:false} - @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", matchIfMissing = false) static class DisabledIfNotConfiguredOtherwiseConfig { @Bean @@ -332,8 +321,7 @@ public class ConditionalOnPropertyTests { } @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", - matchIfMissing = true) + @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", matchIfMissing = true) static class DefaultValueConfig { @Bean @@ -355,8 +343,7 @@ public class ConditionalOnPropertyTests { } @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "simple", - name = { "my-property", "my-another-property" }, havingValue = "bar") + @ConditionalOnProperty(prefix = "simple", name = { "my-property", "my-another-property" }, havingValue = "bar") static class MultiValuesConfig { @Bean @@ -412,8 +399,7 @@ public class ConditionalOnPropertyTests { @Configuration(proxyBeanMethods = false) @ConditionalOnMyFeature - @ConditionalOnProperty(prefix = "my.other.feature", name = "enabled", - havingValue = "true", matchIfMissing = false) + @ConditionalOnProperty(prefix = "my.other.feature", name = "enabled", havingValue = "true", matchIfMissing = false) protected static class MetaAnnotationAndDirectAnnotation { @Bean @@ -425,8 +411,7 @@ public class ConditionalOnPropertyTests { @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) - @ConditionalOnProperty(prefix = "my.feature", name = "enabled", havingValue = "true", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "my.feature", name = "enabled", havingValue = "true", matchIfMissing = false) public @interface ConditionalOnMyFeature { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index 77a532006c7..64ec1f556e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -61,8 +61,7 @@ public class ConditionalOnSingleCandidateTests { public void singleCandidateInAncestorsOneCandidateInCurrent() { load(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.register(FooConfiguration.class, - OnBeanSingleCandidateInAncestorsConfiguration.class); + child.register(FooConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class); child.setParent(this.context); child.refresh(); assertThat(child.containsBean("baz")).isFalse(); @@ -99,42 +98,35 @@ public class ConditionalOnSingleCandidateTests { @Test public void singleCandidateMultipleCandidates() { - load(FooConfiguration.class, BarConfiguration.class, - OnBeanSingleCandidateConfiguration.class); + load(FooConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @Test public void singleCandidateMultipleCandidatesOnePrimary() { - load(FooPrimaryConfiguration.class, BarConfiguration.class, - OnBeanSingleCandidateConfiguration.class); + load(FooPrimaryConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isTrue(); assertThat(this.context.getBean("baz")).isEqualTo("foo"); } @Test public void singleCandidateMultipleCandidatesMultiplePrimary() { - load(FooPrimaryConfiguration.class, BarPrimaryConfiguration.class, - OnBeanSingleCandidateConfiguration.class); + load(FooPrimaryConfiguration.class, BarPrimaryConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @Test public void invalidAnnotationTwoTypes() { - assertThatIllegalStateException() - .isThrownBy(() -> load(OnBeanSingleCandidateTwoTypesConfiguration.class)) + assertThatIllegalStateException().isThrownBy(() -> load(OnBeanSingleCandidateTwoTypesConfiguration.class)) .withCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining( - OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); + .withMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); } @Test public void invalidAnnotationNoType() { - assertThatIllegalStateException() - .isThrownBy(() -> load(OnBeanSingleCandidateNoTypeConfiguration.class)) + assertThatIllegalStateException().isThrownBy(() -> load(OnBeanSingleCandidateNoTypeConfiguration.class)) .withCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining( - OnBeanSingleCandidateNoTypeConfiguration.class.getName()); + .withMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java index d9a3b0b9717..8f148091e5e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java @@ -55,33 +55,30 @@ public class ConditionalOnWebApplicationTests { @Test public void testWebApplicationWithServletContext() { AnnotationConfigServletWebApplicationContext ctx = new AnnotationConfigServletWebApplicationContext(); - ctx.register(AnyWebApplicationConfiguration.class, - ServletWebApplicationConfiguration.class, + ctx.register(AnyWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class, ReactiveWebApplicationConfiguration.class); ctx.setServletContext(new MockServletContext()); ctx.refresh(); this.context = ctx; - assertThat(this.context.getBeansOfType(String.class)) - .containsExactly(entry("any", "any"), entry("servlet", "servlet")); + assertThat(this.context.getBeansOfType(String.class)).containsExactly(entry("any", "any"), + entry("servlet", "servlet")); } @Test public void testWebApplicationWithReactiveContext() { AnnotationConfigReactiveWebApplicationContext context = new AnnotationConfigReactiveWebApplicationContext(); - context.register(AnyWebApplicationConfiguration.class, - ServletWebApplicationConfiguration.class, + context.register(AnyWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class, ReactiveWebApplicationConfiguration.class); context.refresh(); this.context = context; - assertThat(this.context.getBeansOfType(String.class)) - .containsExactly(entry("any", "any"), entry("reactive", "reactive")); + assertThat(this.context.getBeansOfType(String.class)).containsExactly(entry("any", "any"), + entry("reactive", "reactive")); } @Test public void testNonWebApplication() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - ctx.register(AnyWebApplicationConfiguration.class, - ServletWebApplicationConfiguration.class, + ctx.register(AnyWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class, ReactiveWebApplicationConfiguration.class); ctx.refresh(); this.context = ctx; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java index 2fc5ed8917e..4649034311c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java @@ -44,18 +44,13 @@ public class OnBeanConditionTypeDeductionFailureTests { @Test public void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { - assertThatExceptionOfType(Exception.class).isThrownBy( - () -> new AnnotationConfigApplicationContext(ImportingConfiguration.class) - .close()) + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> new AnnotationConfigApplicationContext(ImportingConfiguration.class).close()) .satisfies((ex) -> { - Throwable beanTypeDeductionException = findNestedCause(ex, - BeanTypeDeductionException.class); - assertThat(beanTypeDeductionException) - .hasMessage("Failed to deduce bean type for " - + OnMissingBeanConfiguration.class.getName() - + ".objectMapper"); - assertThat(findNestedCause(beanTypeDeductionException, - NoClassDefFoundError.class)).isNotNull(); + Throwable beanTypeDeductionException = findNestedCause(ex, BeanTypeDeductionException.class); + assertThat(beanTypeDeductionException).hasMessage("Failed to deduce bean type for " + + OnMissingBeanConfiguration.class.getName() + ".objectMapper"); + assertThat(findNestedCause(beanTypeDeductionException, NoClassDefFoundError.class)).isNotNull(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java index d0222092374..aa86b9d45cf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java @@ -47,16 +47,14 @@ public class OnClassConditionAutoConfigurationImportFilterTests { @Test public void shouldBeRegistered() { - assertThat(SpringFactoriesLoader - .loadFactories(AutoConfigurationImportFilter.class, null)) - .hasAtLeastOneElementOfType(OnClassCondition.class); + assertThat(SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, null)) + .hasAtLeastOneElementOfType(OnClassCondition.class); } @Test public void matchShouldMatchClasses() { String[] autoConfigurationClasses = new String[] { "test.match", "test.nomatch" }; - boolean[] result = this.filter.match(autoConfigurationClasses, - getAutoConfigurationMetadata()); + boolean[] result = this.filter.match(autoConfigurationClasses, getAutoConfigurationMetadata()); assertThat(result).containsExactly(true, false); } @@ -64,20 +62,16 @@ public class OnClassConditionAutoConfigurationImportFilterTests { public void matchShouldRecordOutcome() { String[] autoConfigurationClasses = new String[] { "test.match", "test.nomatch" }; this.filter.match(autoConfigurationClasses, getAutoConfigurationMetadata()); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); - assertThat(report.getConditionAndOutcomesBySource()).hasSize(1) - .containsKey("test.nomatch"); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); + assertThat(report.getConditionAndOutcomesBySource()).hasSize(1).containsKey("test.nomatch"); } private AutoConfigurationMetadata getAutoConfigurationMetadata() { AutoConfigurationMetadata metadata = mock(AutoConfigurationMetadata.class); given(metadata.wasProcessed("test.match")).willReturn(true); - given(metadata.get("test.match", "ConditionalOnClass")) - .willReturn("java.io.InputStream"); + given(metadata.get("test.match", "ConditionalOnClass")).willReturn("java.io.InputStream"); given(metadata.wasProcessed("test.nomatch")).willReturn(true); - given(metadata.get("test.nomatch", "ConditionalOnClass")) - .willReturn("java.io.DoesNotExist"); + given(metadata.get("test.nomatch", "ConditionalOnClass")).willReturn("java.io.DoesNotExist"); return metadata; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java index 04f122c5135..1fd0a264fb6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java @@ -58,8 +58,7 @@ public class ResourceConditionTests { @Test public void unknownDefaultLocationAndExplicitKeyToResource() { - load(UnknownDefaultLocationConfiguration.class, - "spring.foo.test.config=logging.properties"); + load(UnknownDefaultLocationConfiguration.class, "spring.foo.test.config=logging.properties"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -101,12 +100,10 @@ public class ResourceConditionTests { } - private static class UnknownDefaultLocationResourceCondition - extends ResourceCondition { + private static class UnknownDefaultLocationResourceCondition extends ResourceCondition { UnknownDefaultLocationResourceCondition() { - super("test", "spring.foo.test.config", - "classpath:/this-file-does-not-exist.xml"); + super("test", "spring.foo.test.config", "classpath:/this-file-does-not-exist.xml"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java index 35b88425fa6..d7bbaa7de6a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java @@ -37,20 +37,14 @@ public class SpringBootConditionTests { @Test public void sensibleClassException() { - assertThatIllegalStateException() - .isThrownBy( - () -> new AnnotationConfigApplicationContext(ErrorOnClass.class)) - .withMessageContaining( - "Error processing condition on " + ErrorOnClass.class.getName()); + assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnClass.class)) + .withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName()); } @Test public void sensibleMethodException() { - assertThatIllegalStateException() - .isThrownBy( - () -> new AnnotationConfigApplicationContext(ErrorOnMethod.class)) - .withMessageContaining("Error processing condition on " - + ErrorOnMethod.class.getName() + ".myBean"); + assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnMethod.class)) + .withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); } @Configuration(proxyBeanMethods = false) @@ -73,8 +67,7 @@ public class SpringBootConditionTests { public static class AlwaysThrowsCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { throw new RuntimeException("Oh no!"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java index 155183bc4ae..3735076dc74 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java @@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest("spring.messages.basename:test/messages") -@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @DirtiesContext public class MessageSourceAutoConfigurationIntegrationTests { @@ -45,8 +44,7 @@ public class MessageSourceAutoConfigurationIntegrationTests { @Test public void testMessageSourceFromPropertySourceAnnotation() { - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java index 5a2ea9c5d3c..595ffc015d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java @@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest -@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @ActiveProfiles("switch-messages") @DirtiesContext public class MessageSourceAutoConfigurationProfileTests { @@ -47,8 +46,7 @@ public class MessageSourceAutoConfigurationProfileTests { @Test public void testMessageSourceFromPropertySourceAnnotation() { - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java index b8349700254..a27e7e022fe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java @@ -45,74 +45,64 @@ import static org.assertj.core.api.Assertions.assertThat; public class MessageSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(MessageSourceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MessageSourceAutoConfiguration.class)); @Test public void testDefaultMessageSource() { - this.contextRunner.run((context) -> assertThat( - context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Foo message")); + this.contextRunner.run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("Foo message")); } @Test public void propertiesBundleWithSlashIsDetected() { - this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> { - assertThat(context).hasSingleBean(MessageSource.class); - assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); - }); + this.contextRunner.withPropertyValues("spring.messages.basename:test/messages").run((context) -> { + assertThat(context).hasSingleBean(MessageSource.class); + assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); + }); } @Test public void propertiesBundleWithDotIsDetected() { - this.contextRunner.withPropertyValues("spring.messages.basename:test.messages") - .run((context) -> { - assertThat(context).hasSingleBean(MessageSource.class); - assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); - }); + this.contextRunner.withPropertyValues("spring.messages.basename:test.messages").run((context) -> { + assertThat(context).hasSingleBean(MessageSource.class); + assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); + }); } @Test public void testEncodingWorks() { this.contextRunner.withPropertyValues("spring.messages.basename:test/swedish") - .run((context) -> assertThat( - context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Some text with some swedish öäå!")); + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("Some text with some swedish öäå!")); } @Test public void testCacheDurationNoUnit() { - this.contextRunner.withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.cache-duration=10").run(assertCache(10 * 1000)); + this.contextRunner + .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=10") + .run(assertCache(10 * 1000)); } @Test public void testCacheDurationWithUnit() { - this.contextRunner.withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.cache-duration=1m").run(assertCache(60 * 1000)); + this.contextRunner + .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=1m") + .run(assertCache(60 * 1000)); } private ContextConsumer assertCache(long expected) { return (context) -> { assertThat(context).hasSingleBean(MessageSource.class); - assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("cacheMillis", expected); + assertThat(context.getBean(MessageSource.class)).hasFieldOrPropertyWithValue("cacheMillis", expected); }; } @Test public void testMultipleMessageSourceCreated() { - this.contextRunner - .withPropertyValues( - "spring.messages.basename:test/messages,test/messages2") + this.contextRunner.withPropertyValues("spring.messages.basename:test/messages,test/messages2") .run((context) -> { - assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); - assertThat(context.getMessage("foo-foo", null, "Foo-Foo message", - Locale.UK)).isEqualTo("bar-bar"); + assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); + assertThat(context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)).isEqualTo("bar-bar"); }); } @@ -120,18 +110,14 @@ public class MessageSourceAutoConfigurationTests { public void testBadEncoding() { // Bad encoding just means the messages are ignored this.contextRunner.withPropertyValues("spring.messages.encoding:rubbish") - .run((context) -> assertThat( - context.getMessage("foo", null, "blah", Locale.UK)) - .isEqualTo("blah")); + .run((context) -> assertThat(context.getMessage("foo", null, "blah", Locale.UK)).isEqualTo("blah")); } @Test @Disabled("Expected to fail per gh-1075") public void testMessageSourceFromPropertySourceAnnotation() { - this.contextRunner.withUserConfiguration(Config.class) - .run((context) -> assertThat( - context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar")); + this.contextRunner.withUserConfiguration(Config.class).run( + (context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar")); } @Test @@ -185,25 +171,22 @@ public class MessageSourceAutoConfigurationTests { @Test public void existingMessageSourceIsPreferred() { this.contextRunner.withUserConfiguration(CustomMessageSourceConfiguration.class) - .run((context) -> assertThat(context.getMessage("foo", null, null, null)) - .isEqualTo("foo")); + .run((context) -> assertThat(context.getMessage("foo", null, null, null)).isEqualTo("foo")); } @Test public void existingMessageSourceInParentIsIgnored() { this.contextRunner.run((parent) -> this.contextRunner.withParent(parent) .withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat( - context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"))); + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"))); } @Test public void messageSourceWithNonStandardBeanNameIsIgnored() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") .withUserConfiguration(CustomBeanNameMessageSourceConfiguration.class) - .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)) - .isEqualTo("bar")); + .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)).isEqualTo("bar")); } @Configuration(proxyBeanMethods = false) @@ -235,20 +218,17 @@ public class MessageSourceAutoConfigurationTests { private static class TestMessageSource implements MessageSource { @Override - public String getMessage(String code, Object[] args, String defaultMessage, - Locale locale) { + public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { return code; } @Override - public String getMessage(String code, Object[] args, Locale locale) - throws NoSuchMessageException { + public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { return code; } @Override - public String getMessage(MessageSourceResolvable resolvable, Locale locale) - throws NoSuchMessageException { + public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { return resolvable.getCodes()[0]; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java index 3c02c898d99..63a55d70769 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java @@ -47,22 +47,19 @@ public class PropertyPlaceholderAutoConfigurationTests { @Test public void propertyPlaceholders() { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - PlaceholderConfig.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, PlaceholderConfig.class); TestPropertyValues.of("foo:two").applyTo(this.context); this.context.refresh(); - assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()) - .isEqualTo("two"); + assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()).isEqualTo("two"); } @Test public void propertyPlaceholdersOverride() { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - PlaceholderConfig.class, PlaceholdersOverride.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, PlaceholderConfig.class, + PlaceholdersOverride.class); TestPropertyValues.of("foo:two").applyTo(this.context); this.context.refresh(); - assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()) - .isEqualTo("spam"); + assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()).isEqualTo("spam"); } @Configuration(proxyBeanMethods = false) @@ -83,8 +80,7 @@ public class PropertyPlaceholderAutoConfigurationTests { @Bean public static PropertySourcesPlaceholderConfigurer morePlaceholders() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); - configurer.setProperties(StringUtils - .splitArrayElementsIntoProperties(new String[] { "foo=spam" }, "=")); + configurer.setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "foo=spam" }, "=")); configurer.setLocalOverride(true); configurer.setOrder(0); return configurer; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java index 1f512f1612a..fcdac959b17 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java @@ -40,10 +40,8 @@ import static org.mockito.Mockito.mock; */ public class CouchbaseAutoConfigurationIntegrationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - CouchbaseAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class)); @Rule public final CouchbaseTestServer couchbase = new CouchbaseTestServer(); @@ -51,21 +49,17 @@ public class CouchbaseAutoConfigurationIntegrationTests { @Test public void defaultConfiguration() { this.contextRunner.withPropertyValues("spring.couchbase.bootstrapHosts=localhost") - .run((context) -> assertThat(context).hasSingleBean(Cluster.class) - .hasSingleBean(ClusterInfo.class) - .hasSingleBean(CouchbaseEnvironment.class) - .hasSingleBean(Bucket.class)); + .run((context) -> assertThat(context).hasSingleBean(Cluster.class).hasSingleBean(ClusterInfo.class) + .hasSingleBean(CouchbaseEnvironment.class).hasSingleBean(Bucket.class)); } @Test public void customConfiguration() { this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .withPropertyValues("spring.couchbase.bootstrapHosts=localhost") - .run((context) -> { + .withPropertyValues("spring.couchbase.bootstrapHosts=localhost").run((context) -> { assertThat(context.getBeansOfType(Cluster.class)).hasSize(2); assertThat(context.getBeansOfType(ClusterInfo.class)).hasSize(1); - assertThat(context.getBeansOfType(CouchbaseEnvironment.class)) - .hasSize(1); + assertThat(context.getBeansOfType(CouchbaseEnvironment.class)).hasSize(1); assertThat(context.getBeansOfType(Bucket.class)).hasSize(2); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java index 0c0f2459810..fcdaeeb3436 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java @@ -43,10 +43,8 @@ import static org.mockito.Mockito.mock; */ public class CouchbaseAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - CouchbaseAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class)); @Test public void bootstrapHostsIsRequired() { @@ -55,19 +53,17 @@ public class CouchbaseAutoConfigurationTests { @Test public void bootstrapHostsNotRequiredIfCouchbaseConfigurerIsSet() { - this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class) - .run((context) -> { - assertThat(context).hasSingleBean(CouchbaseTestConfigurer.class); - // No beans are going to be created - assertNoCouchbaseBeans(context); - }); + this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class).run((context) -> { + assertThat(context).hasSingleBean(CouchbaseTestConfigurer.class); + // No beans are going to be created + assertNoCouchbaseBeans(context); + }); } @Test public void bootstrapHostsIgnoredIfCouchbaseConfigurerIsSet() { this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class) - .withPropertyValues("spring.couchbase.bootstrapHosts=localhost") - .run((context) -> { + .withPropertyValues("spring.couchbase.bootstrapHosts=localhost").run((context) -> { assertThat(context).hasSingleBean(CouchbaseTestConfigurer.class); assertNoCouchbaseBeans(context); }); @@ -75,9 +71,8 @@ public class CouchbaseAutoConfigurationTests { private void assertNoCouchbaseBeans(AssertableApplicationContext context) { // No beans are going to be created - assertThat(context).doesNotHaveBean(CouchbaseEnvironment.class) - .doesNotHaveBean(ClusterInfo.class).doesNotHaveBean(Cluster.class) - .doesNotHaveBean(Bucket.class); + assertThat(context).doesNotHaveBean(CouchbaseEnvironment.class).doesNotHaveBean(ClusterInfo.class) + .doesNotHaveBean(Cluster.class).doesNotHaveBean(Bucket.class); } @Test @@ -89,8 +84,7 @@ public class CouchbaseAutoConfigurationTests { assertThat(env.queryServiceConfig().maxEndpoints()).isEqualTo(5); assertThat(env.viewServiceConfig().minEndpoints()).isEqualTo(4); assertThat(env.viewServiceConfig().maxEndpoints()).isEqualTo(6); - }, "spring.couchbase.env.endpoints.key-value=2", - "spring.couchbase.env.endpoints.queryservice.min-endpoints=3", + }, "spring.couchbase.env.endpoints.key-value=2", "spring.couchbase.env.endpoints.queryservice.min-endpoints=3", "spring.couchbase.env.endpoints.queryservice.max-endpoints=5", "spring.couchbase.env.endpoints.viewservice.min-endpoints=4", "spring.couchbase.env.endpoints.viewservice.max-endpoints=6"); @@ -128,10 +122,8 @@ public class CouchbaseAutoConfigurationTests { assertThat(env.queryTimeout()).isEqualTo(300); assertThat(env.socketConnectTimeout()).isEqualTo(400); assertThat(env.viewTimeout()).isEqualTo(500); - }, "spring.couchbase.env.timeouts.connect=100", - "spring.couchbase.env.timeouts.keyValue=200", - "spring.couchbase.env.timeouts.query=300", - "spring.couchbase.env.timeouts.socket-connect=400", + }, "spring.couchbase.env.timeouts.connect=100", "spring.couchbase.env.timeouts.keyValue=200", + "spring.couchbase.env.timeouts.query=300", "spring.couchbase.env.timeouts.socket-connect=400", "spring.couchbase.env.timeouts.view=500"); } @@ -141,8 +133,7 @@ public class CouchbaseAutoConfigurationTests { assertThat(env.sslEnabled()).isTrue(); assertThat(env.sslKeystoreFile()).isEqualTo("foo"); assertThat(env.sslKeystorePassword()).isEqualTo("secret"); - }, "spring.couchbase.env.ssl.keyStore=foo", - "spring.couchbase.env.ssl.keyStorePassword=secret"); + }, "spring.couchbase.env.ssl.keyStore=foo", "spring.couchbase.env.ssl.keyStorePassword=secret"); } @Test @@ -151,20 +142,16 @@ public class CouchbaseAutoConfigurationTests { assertThat(env.sslEnabled()).isFalse(); assertThat(env.sslKeystoreFile()).isNull(); assertThat(env.sslKeystorePassword()).isNull(); - }, "spring.couchbase.env.ssl.enabled=false", - "spring.couchbase.env.ssl.keyStore=foo", + }, "spring.couchbase.env.ssl.enabled=false", "spring.couchbase.env.ssl.keyStore=foo", "spring.couchbase.env.ssl.keyStorePassword=secret"); } - private void testCouchbaseEnv( - Consumer environmentConsumer, - String... environment) { - this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class) - .withPropertyValues(environment).run((context) -> { - CouchbaseProperties properties = context - .getBean(CouchbaseProperties.class); - DefaultCouchbaseEnvironment env = new CouchbaseConfiguration( - properties).initializeEnvironmentBuilder(properties).build(); + private void testCouchbaseEnv(Consumer environmentConsumer, String... environment) { + this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class).withPropertyValues(environment) + .run((context) -> { + CouchbaseProperties properties = context.getBean(CouchbaseProperties.class); + DefaultCouchbaseEnvironment env = new CouchbaseConfiguration(properties) + .initializeEnvironmentBuilder(properties).build(); environmentConsumer.accept(env); }); } @@ -176,8 +163,7 @@ public class CouchbaseAutoConfigurationTests { "spring.couchbase.env.timeouts.connect=100") .run((context) -> { assertThat(context).hasSingleBean(CouchbaseConfiguration.class); - DefaultCouchbaseEnvironment env = context - .getBean(DefaultCouchbaseEnvironment.class); + DefaultCouchbaseEnvironment env = context.getBean(DefaultCouchbaseEnvironment.class); assertThat(env.socketConnectTimeout()).isEqualTo(5000); assertThat(env.connectTimeout()).isEqualTo(2000); }); @@ -191,10 +177,8 @@ public class CouchbaseAutoConfigurationTests { } @Override - protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder( - CouchbaseProperties properties) { - return super.initializeEnvironmentBuilder(properties) - .socketConnectTimeout(5000).connectTimeout(2000); + protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder(CouchbaseProperties properties) { + return super.initializeEnvironmentBuilder(properties).socketConnectTimeout(5000).connectTimeout(2000); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java index 1cb9322ae70..c9509ede890 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,8 +87,7 @@ public class CouchbaseTestServer implements TestRule { private final Cluster cluster; - CouchbaseStatement(Statement base, CouchbaseEnvironment environment, - Cluster cluster) { + CouchbaseStatement(Statement base, CouchbaseEnvironment environment, Cluster cluster) { this.base = base; this.environment = environment; this.cluster = cluster; @@ -101,8 +100,7 @@ public class CouchbaseTestServer implements TestRule { } catch (BeanCreationException ex) { if ("couchbaseClient".equals(ex.getBeanName())) { - throw new AssumptionViolatedException( - "Skipping test due to Couchbase error " + ex.getMessage(), + throw new AssumptionViolatedException("Skipping test due to Couchbase error " + ex.getMessage(), ex); } } @@ -112,8 +110,7 @@ public class CouchbaseTestServer implements TestRule { this.environment.shutdownAsync(); } catch (Exception ex) { - logger.warn("Exception while trying to cleanup couchbase resource", - ex); + logger.warn("Exception while trying to cleanup couchbase resource", ex); } } } @@ -124,8 +121,7 @@ public class CouchbaseTestServer implements TestRule { @Override public void evaluate() throws Throwable { - throw new AssumptionViolatedException( - "Skipping test due to Couchbase not being available"); + throw new AssumptionViolatedException("Skipping test due to Couchbase not being available"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java index 9dc709a9442..1acd126a267 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java @@ -48,8 +48,7 @@ public class OnBootstrapHostsConditionTests { @Test public void bootstrapHostsDefinedAsList() { - this.contextRunner - .withPropertyValues("spring.couchbase.bootstrap-hosts[0]=value1") + this.contextRunner.withPropertyValues("spring.couchbase.bootstrap-hosts[0]=value1") .run((context) -> assertThat(context).hasBean("foo")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java index b6d6a4717a9..a9c525cd064 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java @@ -56,8 +56,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void exceptionTranslationPostProcessorUsesCglibByDefault() { - this.context = new AnnotationConfigApplicationContext( - PersistenceExceptionTranslationAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(PersistenceExceptionTranslationAutoConfiguration.class); Map beans = this.context .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).hasSize(1); @@ -67,8 +66,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void exceptionTranslationPostProcessorCanBeConfiguredToUseJdkProxy() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.aop.proxy-target-class=false") - .applyTo(this.context); + TestPropertyValues.of("spring.aop.proxy-target-class=false").applyTo(this.context); this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context @@ -80,8 +78,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void exceptionTranslationPostProcessorCanBeDisabled() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.dao.exceptiontranslation.enabled=false") - .applyTo(this.context); + TestPropertyValues.of("spring.dao.exceptiontranslation.enabled=false").applyTo(this.context); this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context @@ -101,12 +98,11 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void persistOfNullThrowsInvalidDataAccessApiUsageExceptionWithExceptionTranslation() { - this.context = new AnnotationConfigApplicationContext( - EmbeddedDataSourceConfiguration.class, + this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, TestConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class); - assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy( - () -> this.context.getBean(TestRepository.class).doSomething()); + assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) + .isThrownBy(() -> this.context.getBean(TestRepository.class).doSomething()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java index a5130f45fe0..a9da8bc1ca1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java @@ -35,78 +35,69 @@ public class ConditionalOnRepositoryTypeTests { @Test public void imperativeRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .run((context) -> assertThat(context) - .hasSingleBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test public void reactiveRepositoryMatchesWithNoConfiguredType() { - this.contextRunner.withUserConfiguration(ReactiveRepository.class).run( - (context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + this.contextRunner.withUserConfiguration(ReactiveRepository.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test public void imperativeRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:auto") - .run((context) -> assertThat(context) - .hasSingleBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test public void reactiveRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:auto") - .run((context) -> assertThat(context) - .hasSingleBean(ReactiveRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test public void imperativeRepositoryMatchesWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:imperative") - .run((context) -> assertThat(context) - .hasSingleBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test public void reactiveRepositoryMatchesWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:reactive") - .run((context) -> assertThat(context) - .hasSingleBean(ReactiveRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test public void imperativeRepositoryDoesNotMatchWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:reactive") - .run((context) -> assertThat(context) - .doesNotHaveBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test public void reactiveRepositoryDoesNotMatchWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:imperative") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test public void imperativeRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:none") - .run((context) -> assertThat(context) - .doesNotHaveBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test public void reactiveRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:none") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/cassandra/ReactiveCityCassandraRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/cassandra/ReactiveCityCassandraRepository.java index 0ed904a1410..5747f244c33 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/cassandra/ReactiveCityCassandraRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/cassandra/ReactiveCityCassandraRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.data.alt.cassandra; import org.springframework.boot.autoconfigure.data.cassandra.city.City; import org.springframework.data.repository.reactive.ReactiveCrudRepository; -public interface ReactiveCityCassandraRepository - extends ReactiveCrudRepository { +public interface ReactiveCityCassandraRepository extends ReactiveCrudRepository { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/couchbase/ReactiveCityCouchbaseRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/couchbase/ReactiveCityCouchbaseRepository.java index 88f0f1e4020..62c9296c868 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/couchbase/ReactiveCityCouchbaseRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/couchbase/ReactiveCityCouchbaseRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.data.alt.couchbase; import org.springframework.boot.autoconfigure.data.couchbase.city.City; import org.springframework.data.repository.reactive.ReactiveCrudRepository; -public interface ReactiveCityCouchbaseRepository - extends ReactiveCrudRepository { +public interface ReactiveCityCouchbaseRepository extends ReactiveCrudRepository { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/elasticsearch/CityReactiveElasticsearchDbRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/elasticsearch/CityReactiveElasticsearchDbRepository.java index a216b15e851..b9a95a66b45 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/elasticsearch/CityReactiveElasticsearchDbRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/elasticsearch/CityReactiveElasticsearchDbRepository.java @@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.data.alt.elasticsearch; import org.springframework.boot.autoconfigure.data.elasticsearch.city.City; import org.springframework.data.elasticsearch.repository.ReactiveElasticsearchRepository; -public interface CityReactiveElasticsearchDbRepository - extends ReactiveElasticsearchRepository { +public interface CityReactiveElasticsearchDbRepository extends ReactiveElasticsearchRepository { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/mongo/ReactiveCityMongoDbRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/mongo/ReactiveCityMongoDbRepository.java index ebb5215a29c..8540299508f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/mongo/ReactiveCityMongoDbRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/alt/mongo/ReactiveCityMongoDbRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.data.alt.mongo; import org.springframework.boot.autoconfigure.data.mongo.city.City; import org.springframework.data.repository.reactive.ReactiveCrudRepository; -public interface ReactiveCityMongoDbRepository - extends ReactiveCrudRepository { +public interface ReactiveCityMongoDbRepository extends ReactiveCrudRepository { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java index fdb6276db1e..950a351f384 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java @@ -55,10 +55,8 @@ public class CassandraDataAutoConfigurationIntegrationTests { public void setUp() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.data.cassandra.port=" - + cassandra.getContainer().getFirstMappedPort(), - "spring.data.cassandra.read-timeout=24000", - "spring.data.cassandra.connect-timeout=10000") + .of("spring.data.cassandra.port=" + cassandra.getContainer().getFirstMappedPort(), + "spring.data.cassandra.read-timeout=24000", "spring.data.cassandra.connect-timeout=10000") .applyTo(this.context.getEnvironment()); } @@ -73,12 +71,10 @@ public class CassandraDataAutoConfigurationIntegrationTests { public void hasDefaultSchemaActionSet() { String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); - this.context.register(CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class); + this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); this.context.refresh(); - CassandraSessionFactoryBean bean = this.context - .getBean(CassandraSessionFactoryBean.class); + CassandraSessionFactoryBean bean = this.context.getBean(CassandraSessionFactoryBean.class); assertThat(bean.getSchemaAction()).isEqualTo(SchemaAction.NONE); } @@ -87,23 +83,18 @@ public class CassandraDataAutoConfigurationIntegrationTests { createTestKeyspaceIfNotExists(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); - TestPropertyValues - .of("spring.data.cassandra.schemaAction=recreate_drop_unused", - "spring.data.cassandra.keyspaceName=boot_test") - .applyTo(this.context); - this.context.register(CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class); + TestPropertyValues.of("spring.data.cassandra.schemaAction=recreate_drop_unused", + "spring.data.cassandra.keyspaceName=boot_test").applyTo(this.context); + this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); this.context.refresh(); - CassandraSessionFactoryBean bean = this.context - .getBean(CassandraSessionFactoryBean.class); + CassandraSessionFactoryBean bean = this.context.getBean(CassandraSessionFactoryBean.class); assertThat(bean.getSchemaAction()).isEqualTo(SchemaAction.RECREATE_DROP_UNUSED); } private void createTestKeyspaceIfNotExists() { Cluster cluster = Cluster.builder().withoutJMXReporting() .withPort(cassandra.getContainer().getFirstMappedPort()) - .addContactPoint(cassandra.getContainer().getContainerIpAddress()) - .build(); + .addContactPoint(cassandra.getContainer().getContainerIpAddress()).build(); try (Session session = cluster.connect()) { session.execute("CREATE KEYSPACE IF NOT EXISTS boot_test" + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java index 1eaa6d0b164..1e44f0e39ff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java @@ -64,26 +64,23 @@ public class CassandraDataAutoConfigurationTests { @Test public void templateExists() { load(TestExcludeConfiguration.class); - assertThat(this.context.getBeanNamesForType(CassandraTemplate.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(CassandraTemplate.class).length).isEqualTo(1); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class); - CassandraMappingContext mappingContext = this.context - .getBean(CassandraMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class); } @Test public void userTypeResolverShouldBeSet() { load(); - CassandraMappingContext mappingContext = this.context - .getBean(CassandraMappingContext.class); + CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); assertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")) .isInstanceOf(SimpleUserTypeResolver.class); } @@ -92,42 +89,37 @@ public class CassandraDataAutoConfigurationTests { public void defaultConversions() { load(); CassandraTemplate template = this.context.getBean(CassandraTemplate.class); - assertThat(template.getConverter().getConversionService().canConvert(Person.class, - String.class)).isFalse(); + assertThat(template.getConverter().getConversionService().canConvert(Person.class, String.class)).isFalse(); } @Test public void customConversions() { load(CustomConversionConfig.class); CassandraTemplate template = this.context.getBean(CassandraTemplate.class); - assertThat(template.getConverter().getConversionService().canConvert(Person.class, - String.class)).isTrue(); + assertThat(template.getConverter().getConversionService().canConvert(Person.class, String.class)).isTrue(); } @Test public void clusterDoesNotExist() { - this.context = new AnnotationConfigApplicationContext( - CassandraDataAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(CassandraDataAutoConfiguration.class); assertThat(this.context.getBeansOfType(Session.class)).isEmpty(); } public void load(Class... config) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.data.cassandra.keyspaceName:boot_test") - .applyTo(ctx); + TestPropertyValues.of("spring.data.cassandra.keyspaceName:boot_test").applyTo(ctx); if (!ObjectUtils.isEmpty(config)) { ctx.register(config); } - ctx.register(TestConfiguration.class, CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class); + ctx.register(TestConfiguration.class, CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); ctx.refresh(); this.context = ctx; } @Configuration(proxyBeanMethods = false) - @ComponentScan(excludeFilters = @ComponentScan.Filter(classes = { Session.class }, - type = FilterType.ASSIGNABLE_TYPE)) + @ComponentScan( + excludeFilters = @ComponentScan.Filter(classes = { Session.class }, type = FilterType.ASSIGNABLE_TYPE)) static class TestExcludeConfiguration { } @@ -153,8 +145,7 @@ public class CassandraDataAutoConfigurationTests { @Bean public CassandraCustomConversions myCassandraCustomConversions() { - return new CassandraCustomConversions( - Collections.singletonList(new MyConverter())); + return new CassandraCustomConversions(Collections.singletonList(new MyConverter())); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java index ba162e35a23..4783309a14f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java @@ -58,26 +58,23 @@ public class CassandraReactiveDataAutoConfigurationTests { @Test public void templateExists() { load("spring.data.cassandra.keyspaceName:boot_test"); - assertThat(this.context.getBeanNamesForType(ReactiveCassandraTemplate.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(ReactiveCassandraTemplate.class)).hasSize(1); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class, "spring.data.cassandra.keyspaceName:boot_test"); - CassandraMappingContext mappingContext = this.context - .getBean(CassandraMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class); } @Test public void userTypeResolverShouldBeSet() { load("spring.data.cassandra.keyspaceName:boot_test"); - CassandraMappingContext mappingContext = this.context - .getBean(CassandraMappingContext.class); + CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); assertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")) .isInstanceOf(SimpleUserTypeResolver.class); } @@ -92,8 +89,7 @@ public class CassandraReactiveDataAutoConfigurationTests { if (config != null) { ctx.register(config); } - ctx.register(TestConfiguration.class, CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class, + ctx.register(TestConfiguration.class, CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, CassandraReactiveDataAutoConfiguration.class); ctx.refresh(); this.context = ctx; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java index 3ecf2f5b134..bf65a0a44f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java @@ -55,42 +55,35 @@ import static org.mockito.Mockito.mock; */ public class CassandraReactiveRepositoriesAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class, - CassandraRepositoriesAutoConfiguration.class, - CassandraDataAutoConfiguration.class, - CassandraReactiveDataAutoConfiguration.class, - CassandraReactiveRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraRepositoriesAutoConfiguration.class, + CassandraDataAutoConfiguration.class, CassandraReactiveDataAutoConfiguration.class, + CassandraReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveCityRepository.class); - assertThat(context).hasSingleBean(Cluster.class); - assertThat(getInitialEntitySet(context)).hasSize(1); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(ReactiveCityRepository.class); + assertThat(context).hasSingleBean(Cluster.class); + assertThat(getInitialEntitySet(context)).hasSize(1); + }); } @Test public void testNoRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, - EmptyConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, EmptyConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(Cluster.class); - assertThat(getInitialEntitySet(context)).hasSize(1) - .containsOnly(City.class); + assertThat(getInitialEntitySet(context)).hasSize(1).containsOnly(City.class); }); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { - this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, - CustomizedConfiguration.class).run((context) -> { - assertThat(context) - .hasSingleBean(ReactiveCityCassandraRepository.class); - assertThat(getInitialEntitySet(context)).hasSize(1) - .containsOnly(City.class); + this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, CustomizedConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveCityCassandraRepository.class); + assertThat(getInitialEntitySet(context)).hasSize(1).containsOnly(City.class); }); } @@ -98,24 +91,20 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { public void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=imperative") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test public void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=none") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @SuppressWarnings("unchecked") private Set> getInitialEntitySet(ApplicationContext context) { - CassandraMappingContext mappingContext = context - .getBean(CassandraMappingContext.class); - return (Set>) ReflectionTestUtils.getField(mappingContext, - "initialEntitySet"); + CassandraMappingContext mappingContext = context.getBean(CassandraMappingContext.class); + return (Set>) ReflectionTestUtils.getField(mappingContext, "initialEntitySet"); } @Configuration(proxyBeanMethods = false) @@ -137,15 +126,13 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(CassandraReactiveRepositoriesAutoConfigurationTests.class) - @EnableReactiveCassandraRepositories( - basePackageClasses = ReactiveCityCassandraRepository.class) + @EnableReactiveCassandraRepositories(basePackageClasses = ReactiveCityCassandraRepository.class) static class CustomizedConfiguration { } @Configuration(proxyBeanMethods = false) - @ComponentScan(excludeFilters = @Filter(classes = { ReactiveSession.class }, - type = FilterType.ASSIGNABLE_TYPE)) + @ComponentScan(excludeFilters = @Filter(classes = { ReactiveSession.class }, type = FilterType.ASSIGNABLE_TYPE)) static class TestExcludeConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java index ec604fe2fbc..37f327a8291 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java @@ -52,39 +52,34 @@ import static org.mockito.Mockito.mock; */ public class CassandraRepositoriesAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class, - CassandraRepositoriesAutoConfiguration.class, - CassandraDataAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraRepositoriesAutoConfiguration.class, + CassandraDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context).hasSingleBean(Cluster.class); - assertThat(getInitialEntitySet(context)).hasSize(1); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context).hasSingleBean(Cluster.class); + assertThat(getInitialEntitySet(context)).hasSize(1); + }); } @Test public void testNoRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, - EmptyConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, EmptyConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(Cluster.class); - assertThat(getInitialEntitySet(context)).hasSize(1) - .containsOnly(City.class); + assertThat(getInitialEntitySet(context)).hasSize(1).containsOnly(City.class); }); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { - this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, - CustomizedConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, CustomizedConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(CityCassandraRepository.class); - assertThat(getInitialEntitySet(context)).hasSize(1) - .containsOnly(City.class); + assertThat(getInitialEntitySet(context)).hasSize(1).containsOnly(City.class); }); } @@ -92,24 +87,20 @@ public class CassandraRepositoriesAutoConfigurationTests { public void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=reactive") - .run((context) -> assertThat(context) - .doesNotHaveBean(CityCassandraRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } @Test public void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=none") - .run((context) -> assertThat(context) - .doesNotHaveBean(CityCassandraRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } @SuppressWarnings("unchecked") private Set> getInitialEntitySet(AssertableApplicationContext context) { - CassandraMappingContext mappingContext = context - .getBean(CassandraMappingContext.class); - return (Set>) ReflectionTestUtils.getField(mappingContext, - "initialEntitySet"); + CassandraMappingContext mappingContext = context.getBean(CassandraMappingContext.class); + return (Set>) ReflectionTestUtils.getField(mappingContext, "initialEntitySet"); } @Configuration(proxyBeanMethods = false) @@ -137,8 +128,8 @@ public class CassandraRepositoriesAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @ComponentScan(excludeFilters = @ComponentScan.Filter(classes = { Session.class }, - type = FilterType.ASSIGNABLE_TYPE)) + @ComponentScan( + excludeFilters = @ComponentScan.Filter(classes = { Session.class }, type = FilterType.ASSIGNABLE_TYPE)) static class TestExcludeConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java index c35c62e6400..207459c1246 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java @@ -73,17 +73,14 @@ public class CouchbaseDataAutoConfigurationTests { @Test public void customConfiguration() { load(CustomCouchbaseConfiguration.class); - CouchbaseTemplate couchbaseTemplate = this.context - .getBean(CouchbaseTemplate.class); - assertThat(couchbaseTemplate.getDefaultConsistency()) - .isEqualTo(Consistency.STRONGLY_CONSISTENT); + CouchbaseTemplate couchbaseTemplate = this.context.getBean(CouchbaseTemplate.class); + assertThat(couchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT); } @Test public void validatorIsPresent() { load(CouchbaseTestConfigurer.class); - assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)).hasSize(1); } @Test @@ -106,22 +103,19 @@ public class CouchbaseDataAutoConfigurationTests { @Test public void changeConsistency() { - load(CouchbaseTestConfigurer.class, - "spring.data.couchbase.consistency=eventually-consistent"); + load(CouchbaseTestConfigurer.class, "spring.data.couchbase.consistency=eventually-consistent"); SpringBootCouchbaseDataConfiguration configuration = this.context .getBean(SpringBootCouchbaseDataConfiguration.class); - assertThat(configuration.getDefaultConsistency()) - .isEqualTo(Consistency.EVENTUALLY_CONSISTENT); + assertThat(configuration.getDefaultConsistency()).isEqualTo(Consistency.EVENTUALLY_CONSISTENT); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class); - CouchbaseMappingContext mappingContext = this.context - .getBean(CouchbaseMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class); } @@ -129,8 +123,8 @@ public class CouchbaseDataAutoConfigurationTests { public void customConversions() { load(CustomConversionsConfig.class); CouchbaseTemplate template = this.context.getBean(CouchbaseTemplate.class); - assertThat(template.getConverter().getConversionService() - .canConvert(CouchbaseProperties.class, Boolean.class)).isTrue(); + assertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) + .isTrue(); } private void load(Class config, String... environment) { @@ -139,9 +133,8 @@ public class CouchbaseDataAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, ValidationAutoConfiguration.class, + CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class); context.refresh(); this.context = context; } @@ -167,8 +160,7 @@ public class CouchbaseDataAutoConfigurationTests { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) public CouchbaseCustomConversions myCustomConversions() { - return new CouchbaseCustomConversions( - Collections.singletonList(new MyConverter())); + return new CouchbaseCustomConversions(Collections.singletonList(new MyConverter())); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java index 6a2dec731e9..6f96b241b62 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java @@ -58,10 +58,8 @@ public class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { @Test public void shouldCreateInstancesForReactiveAndImperativeRepositories() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.initialization-mode:never") - .applyTo(this.context); - this.context.register(ImperativeAndReactiveConfiguration.class, - BaseConfiguration.class); + TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); + this.context.register(ImperativeAndReactiveConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); assertThat(this.context.getBean(ReactiveCityRepository.class)).isNotNull(); @@ -70,8 +68,7 @@ public class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(CouchbaseAutoConfigurationTests.class) @EnableCouchbaseRepositories(basePackageClasses = CityRepository.class) - @EnableReactiveCouchbaseRepositories( - basePackageClasses = ReactiveCityRepository.class) + @EnableReactiveCouchbaseRepositories(basePackageClasses = ReactiveCityRepository.class) protected static class ImperativeAndReactiveConfiguration { } @@ -88,8 +85,7 @@ public class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { public String[] selectImports(AnnotationMetadata importingClassMetadata) { List names = new ArrayList<>(); for (Class type : new Class[] { CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class, - CouchbaseRepositoriesAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class, CouchbaseRepositoriesAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class, CouchbaseReactiveRepositoriesAutoConfiguration.class }) { names.add(type.getName()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java index c99798f9bf5..e5a83cb3a7a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java @@ -73,37 +73,32 @@ public class CouchbaseReactiveDataAutoConfigurationTests { @Test public void customConfiguration() { load(CustomCouchbaseConfiguration.class); - RxJavaCouchbaseTemplate rxJavaCouchbaseTemplate = this.context - .getBean(RxJavaCouchbaseTemplate.class); - assertThat(rxJavaCouchbaseTemplate.getDefaultConsistency()) - .isEqualTo(Consistency.STRONGLY_CONSISTENT); + RxJavaCouchbaseTemplate rxJavaCouchbaseTemplate = this.context.getBean(RxJavaCouchbaseTemplate.class); + assertThat(rxJavaCouchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT); } @Test public void validatorIsPresent() { load(CouchbaseTestConfigurer.class); - assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)).hasSize(1); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class); - CouchbaseMappingContext mappingContext = this.context - .getBean(CouchbaseMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class); } @Test public void customConversions() { load(CustomConversionsConfig.class); - RxJavaCouchbaseTemplate template = this.context - .getBean(RxJavaCouchbaseTemplate.class); - assertThat(template.getConverter().getConversionService() - .canConvert(CouchbaseProperties.class, Boolean.class)).isTrue(); + RxJavaCouchbaseTemplate template = this.context.getBean(RxJavaCouchbaseTemplate.class); + assertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) + .isTrue(); } private void load(Class config, String... environment) { @@ -112,17 +107,15 @@ public class CouchbaseReactiveDataAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class, + context.register(PropertyPlaceholderAutoConfiguration.class, ValidationAutoConfiguration.class, + CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class); context.refresh(); this.context = context; } @Configuration - static class CustomCouchbaseConfiguration - extends AbstractReactiveCouchbaseDataConfiguration { + static class CustomCouchbaseConfiguration extends AbstractReactiveCouchbaseDataConfiguration { @Override protected CouchbaseConfigurer couchbaseConfigurer() { @@ -142,8 +135,7 @@ public class CouchbaseReactiveDataAutoConfigurationTests { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) public CouchbaseCustomConversions myCustomConversions() { - return new CouchbaseCustomConversions( - Collections.singletonList(new MyConverter())); + return new CouchbaseCustomConversions(Collections.singletonList(new MyConverter())); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java index caf9f319cbe..6080ae7bd4d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java @@ -66,8 +66,7 @@ public class CouchbaseReactiveRepositoriesAutoConfigurationTests { @Test public void imperativeRepositories() { - load(DefaultConfiguration.class, - "spring.data.couchbase.repositories.type=imperative"); + load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=imperative"); assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0); } @@ -86,8 +85,7 @@ public class CouchbaseReactiveRepositoriesAutoConfigurationTests { @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { load(CustomizedConfiguration.class); - assertThat(this.context.getBeansOfType(ReactiveCityCouchbaseRepository.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(ReactiveCityCouchbaseRepository.class)).isEmpty(); } private void load(Class config, String... environment) { @@ -96,11 +94,9 @@ public class CouchbaseReactiveRepositoriesAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, - CouchbaseRepositoriesAutoConfiguration.class, - CouchbaseReactiveDataAutoConfiguration.class, - CouchbaseReactiveRepositoriesAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class, CouchbaseRepositoriesAutoConfiguration.class, + CouchbaseReactiveDataAutoConfiguration.class, CouchbaseReactiveRepositoriesAutoConfiguration.class); context.refresh(); this.context = context; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java index 19b82ec1d7f..cf8a2da1637 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java @@ -64,8 +64,7 @@ public class CouchbaseRepositoriesAutoConfigurationTests { @Test public void reactiveRepositories() { - load(DefaultConfiguration.class, - "spring.data.couchbase.repositories.type=reactive"); + load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=reactive"); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(0); } @@ -87,9 +86,8 @@ public class CouchbaseRepositoriesAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, - CouchbaseRepositoriesAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class, CouchbaseRepositoriesAutoConfiguration.class); context.refresh(); this.context = context; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java index 9e61ac08b9d..f499fca35ab 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java @@ -59,28 +59,23 @@ public class ElasticsearchAutoConfigurationTests { @Test public void useExistingClient() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, + this.context.register(CustomConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); - assertThat(this.context.getBean("myClient")) - .isSameAs(this.context.getBean(Client.class)); + assertThat(this.context.getBean("myClient")).isSameAs(this.context.getBean(Client.class)); } @Test public void createTransportClient() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.data.elasticsearch.cluster-nodes:localhost:" - + elasticsearch.getMappedTransportPort(), + .of("spring.data.elasticsearch.cluster-nodes:localhost:" + elasticsearch.getMappedTransportPort(), "spring.data.elasticsearch.cluster-name:docker-cluster") .applyTo(this.context); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); - List connectedNodes = this.context.getBean(TransportClient.class) - .connectedNodes(); + List connectedNodes = this.context.getBean(TransportClient.class).connectedNodes(); assertThat(connectedNodes).hasSize(1); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java index 0c2ead20e8f..44a6d531fc4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java @@ -49,63 +49,50 @@ public class ElasticsearchDataAutoConfigurationTests { @Container public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchAutoConfiguration.class, - RestClientAutoConfiguration.class, - ReactiveRestClientAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(ElasticsearchAutoConfiguration.class, RestClientAutoConfiguration.class, + ReactiveRestClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)); @Test public void defaultTransportBeansAreRegistered() { this.contextRunner .withPropertyValues( - "spring.data.elasticsearch.cluster-nodes:localhost:" - + elasticsearch.getMappedTransportPort(), + "spring.data.elasticsearch.cluster-nodes:localhost:" + elasticsearch.getMappedTransportPort(), "spring.data.elasticsearch.cluster-name:docker-cluster") - .run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchTemplate.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchTemplate.class) .hasSingleBean(SimpleElasticsearchMappingContext.class) .hasSingleBean(ElasticsearchConverter.class)); } @Test public void defaultTransportBeansNotRegisteredIfNoTransportClient() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ElasticsearchTemplate.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchTemplate.class)); } @Test public void defaultRestBeansRegistered() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchRestTemplate.class) - .hasSingleBean(ReactiveElasticsearchTemplate.class) - .hasSingleBean(ElasticsearchConverter.class) - .hasSingleBean(SimpleElasticsearchMappingContext.class) - .hasSingleBean(EntityMapper.class) + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class) + .hasSingleBean(ReactiveElasticsearchTemplate.class).hasSingleBean(ElasticsearchConverter.class) + .hasSingleBean(SimpleElasticsearchMappingContext.class).hasSingleBean(EntityMapper.class) .hasSingleBean(ElasticsearchConverter.class)); } @Test public void customTransportTemplateShouldBeUsed() { - this.contextRunner.withUserConfiguration(CustomTransportTemplate.class) - .run((context) -> assertThat(context) - .getBeanNames(ElasticsearchTemplate.class).hasSize(1) - .contains("elasticsearchTemplate")); + this.contextRunner.withUserConfiguration(CustomTransportTemplate.class).run((context) -> assertThat(context) + .getBeanNames(ElasticsearchTemplate.class).hasSize(1).contains("elasticsearchTemplate")); } @Test public void customRestTemplateShouldBeUsed() { - this.contextRunner.withUserConfiguration(CustomRestTemplate.class) - .run((context) -> assertThat(context) - .getBeanNames(ElasticsearchRestTemplate.class).hasSize(1) - .contains("elasticsearchTemplate")); + this.contextRunner.withUserConfiguration(CustomRestTemplate.class).run((context) -> assertThat(context) + .getBeanNames(ElasticsearchRestTemplate.class).hasSize(1).contains("elasticsearchTemplate")); } @Test public void customReactiveRestTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomReactiveRestTemplate.class) - .run((context) -> assertThat(context) - .getBeanNames(ReactiveElasticsearchTemplate.class).hasSize(1) + .run((context) -> assertThat(context).getBeanNames(ReactiveElasticsearchTemplate.class).hasSize(1) .contains("reactiveElasticsearchTemplate")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java index d68bf5b50ef..988d1f60fd7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java @@ -49,32 +49,27 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchAutoConfiguration.class, - RestClientAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues("spring.elasticsearch.rest.uris=localhost:" - + elasticsearch.getMappedHttpPort()); + .withConfiguration( + AutoConfigurations.of(ElasticsearchAutoConfiguration.class, RestClientAutoConfiguration.class, + ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) + .withPropertyValues("spring.elasticsearch.rest.uris=localhost:" + elasticsearch.getMappedHttpPort()); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) - .hasSingleBean(ElasticsearchRestTemplate.class)); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(CityRepository.class).hasSingleBean(ElasticsearchRestTemplate.class)); } @Test public void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchRestTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class)); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(CityElasticsearchDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityElasticsearchDbRepository.class)); } @Configuration(proxyBeanMethods = false) @@ -91,8 +86,7 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(ElasticsearchRepositoriesAutoConfigurationTests.class) - @EnableElasticsearchRepositories( - basePackageClasses = CityElasticsearchDbRepository.class) + @EnableElasticsearchRepositories(basePackageClasses = CityElasticsearchDbRepository.class) static class CustomizedConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java index b2183d75110..d2c52057923 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java @@ -48,34 +48,27 @@ public class ReactiveElasticsearchRepositoriesAutoConfigurationTests { public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ReactiveRestClientAutoConfiguration.class, - ReactiveElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues( - "spring.data.elasticsearch.client.reactive.endpoints=localhost:" - + elasticsearch.getMappedHttpPort()); + .withConfiguration(AutoConfigurations.of(ReactiveRestClientAutoConfiguration.class, + ReactiveElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) + .withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=localhost:" + + elasticsearch.getMappedHttpPort()); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ReactiveCityRepository.class) - .hasSingleBean(ReactiveElasticsearchTemplate.class)); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(ReactiveCityRepository.class).hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test public void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ReactiveElasticsearchTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(CityReactiveElasticsearchDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityReactiveElasticsearchDbRepository.class)); } @Configuration(proxyBeanMethods = false) @@ -92,8 +85,7 @@ public class ReactiveElasticsearchRepositoriesAutoConfigurationTests { @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(ReactiveElasticsearchRepositoriesAutoConfigurationTests.class) - @EnableReactiveElasticsearchRepositories( - basePackageClasses = CityReactiveElasticsearchDbRepository.class) + @EnableReactiveElasticsearchRepositories(basePackageClasses = CityReactiveElasticsearchDbRepository.class) static class CustomizedConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java index b11e5343a1e..85695a16ce6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java @@ -49,49 +49,39 @@ public class ReactiveRestClientAutoConfigurationTests { public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ReactiveRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveRestClientAutoConfiguration.class)); @Test public void configureShouldCreateDefaultBeans() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(ClientConfiguration.class) - .hasSingleBean(ReactiveElasticsearchClient.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ClientConfiguration.class) + .hasSingleBean(ReactiveElasticsearchClient.class)); } @Test public void configureWhenCustomClientShouldBackOff() { - this.contextRunner.withUserConfiguration(CustomClientConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ReactiveElasticsearchClient.class) - .hasBean("customClient")); + this.contextRunner.withUserConfiguration(CustomClientConfiguration.class).run((context) -> assertThat(context) + .hasSingleBean(ReactiveElasticsearchClient.class).hasBean("customClient")); } @Test public void configureWhenCustomClientConfig() { this.contextRunner.withUserConfiguration(CustomClientConfigConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(ReactiveElasticsearchClient.class) - .hasSingleBean(ClientConfiguration.class) - .hasBean("customClientConfiguration")); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) + .hasSingleBean(ClientConfiguration.class).hasBean("customClientConfiguration")); } @Test public void restClientCanQueryElasticsearchNode() { this.contextRunner.withPropertyValues( - "spring.data.elasticsearch.client.reactive.endpoints=localhost:" - + elasticsearch.getMappedPort()) + "spring.data.elasticsearch.client.reactive.endpoints=localhost:" + elasticsearch.getMappedPort()) .run((context) -> { - ReactiveElasticsearchClient client = context - .getBean(ReactiveElasticsearchClient.class); + ReactiveElasticsearchClient client = context.getBean(ReactiveElasticsearchClient.class); Map source = new HashMap<>(); source.put("a", "alpha"); source.put("b", "bravo"); - IndexRequest index = new IndexRequest("foo", "bar", "1") - .source(source); + IndexRequest index = new IndexRequest("foo", "bar", "1").source(source); GetRequest getRequest = new GetRequest("foo", "bar", "1"); - GetResult getResult = client.index(index).then(client.get(getRequest)) - .block(); + GetResult getResult = client.index(index).then(client.get(getRequest)).block(); assertThat(getResult.isExists()).isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java index ffaa5252731..9b7fe46755e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java @@ -21,8 +21,7 @@ import java.io.Serializable; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; -@Document(indexName = "city", type = "city", shards = 1, replicas = 0, - refreshInterval = "-1") +@Document(indexName = "city", type = "city", shards = 1, replicas = 0, refreshInterval = "-1") public class City implements Serializable { private static final long serialVersionUID = 1L; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java index ad9f673aab6..021b53cc828 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ public interface CityRepository extends Repository { Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java index 11f147565ff..e2585edb801 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java @@ -45,23 +45,20 @@ import static org.assertj.core.api.Assertions.assertThat; public class JdbcRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); @Test public void backsOffWithNoDataSource() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(JdbcRepositoryConfigExtension.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JdbcRepositoryConfigExtension.class)); } @Test public void backsOffWithNoJdbcOperations() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - TestConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, TestConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(DataSource.class); - assertThat(context) - .doesNotHaveBean(JdbcRepositoryConfigExtension.class); + assertThat(context).doesNotHaveBean(JdbcRepositoryConfigExtension.class); }); } @@ -69,29 +66,21 @@ public class JdbcRepositoriesAutoConfigurationTests { public void basicAutoConfiguration() { this.contextRunner .withConfiguration( - AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.datasource.schema=classpath:data-jdbc-schema.sql", - "spring.datasource.data=classpath:city.sql", - "spring.datasource.generate-unique-name:true") + AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.datasource.schema=classpath:data-jdbc-schema.sql", + "spring.datasource.data=classpath:city.sql", "spring.datasource.generate-unique-name:true") .run((context) -> { assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context.getBean(CityRepository.class).findById(2000L)) - .isPresent(); + assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); }); } @Test public void autoConfigurationWithNoRepositories() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - EmptyConfiguration.class) + this.contextRunner.withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, EmptyConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); assertThat(context).doesNotHaveBean(Repository.class); @@ -102,19 +91,14 @@ public class JdbcRepositoriesAutoConfigurationTests { public void honoursUsersEnableJdbcRepositoriesConfiguration() { this.contextRunner .withConfiguration( - AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withUserConfiguration(EnableRepositoriesConfiguration.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.datasource.schema=classpath:data-jdbc-schema.sql", - "spring.datasource.data=classpath:city.sql", - "spring.datasource.generate-unique-name:true") + AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withUserConfiguration(EnableRepositoriesConfiguration.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.datasource.schema=classpath:data-jdbc-schema.sql", + "spring.datasource.data=classpath:city.sql", "spring.datasource.generate-unique-name:true") .run((context) -> { assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context.getBean(CityRepository.class).findById(2000L)) - .isPresent(); + assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index 69960f4e80b..2052ddc3c5e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java @@ -56,91 +56,72 @@ public class JpaRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)) + JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) .withUserConfiguration(EmbeddedDataSourceConfiguration.class); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context).hasSingleBean(PlatformTransactionManager.class); - assertThat(context).hasSingleBean(EntityManagerFactory.class); - assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getBootstrapExecutor()).isNull(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context).hasSingleBean(PlatformTransactionManager.class); + assertThat(context).hasSingleBean(EntityManagerFactory.class); + assertThat(context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()).isNull(); + }); } @Test public void testOverrideRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(CityJpaRepository.class); - assertThat(context).hasSingleBean(PlatformTransactionManager.class); - assertThat(context).hasSingleBean(EntityManagerFactory.class); - }); + this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(CityJpaRepository.class); + assertThat(context).hasSingleBean(PlatformTransactionManager.class); + assertThat(context).hasSingleBean(EntityManagerFactory.class); + }); } @Test public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test public void whenBootstrappingModeIsLazyWithMultipleAsyncExecutorBootstrapExecutorIsConfigured() { - this.contextRunner - .withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration( - AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) + this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, + TaskSchedulingAutoConfiguration.class)) .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getBootstrapExecutor()).isEqualTo( - context.getBean("applicationTaskExecutor"))); + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("applicationTaskExecutor"))); } @Test public void whenBootstrappingModeIsLazyWithSingleAsyncExecutorBootstrapExecutorIsConfigured() { - this.contextRunner - .withUserConfiguration(SingleAsyncTaskExecutorConfiguration.class) + this.contextRunner.withUserConfiguration(SingleAsyncTaskExecutorConfiguration.class) .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getBootstrapExecutor()).isEqualTo( - context.getBean("testAsyncTaskExecutor"))); + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("testAsyncTaskExecutor"))); } @Test public void whenBootstrappingModeIsDeferredBootstrapExecutorIsConfigured() { - this.contextRunner - .withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration( - AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues( - "spring.data.jpa.repositories.bootstrap-mode=deferred") + this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, + TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=deferred") .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getBootstrapExecutor()).isEqualTo( - context.getBean("applicationTaskExecutor"))); + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("applicationTaskExecutor"))); } @Test public void whenBootstrappingModeIsDefaultBootstrapExecutorIsNotConfigured() { - this.contextRunner - .withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration( - AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=default") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getBootstrapExecutor()).isNull()); + this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, + TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=default").run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()).isNull()); } @Configuration(proxyBeanMethods = false) @@ -170,11 +151,8 @@ public class JpaRepositoriesAutoConfigurationTests { @Configuration(proxyBeanMethods = false) @EnableJpaRepositories( basePackageClasses = org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class, - excludeFilters = { - @Filter(type = FilterType.ASSIGNABLE_TYPE, - value = CityMongoDbRepository.class), - @Filter(type = FilterType.ASSIGNABLE_TYPE, - value = CitySolrRepository.class) }) + excludeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = CityMongoDbRepository.class), + @Filter(type = FilterType.ASSIGNABLE_TYPE, value = CitySolrRepository.class) }) @TestAutoConfigurationPackage(City.class) protected static class CustomConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java index 1c3df911b7d..15b825fd091 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java @@ -54,18 +54,13 @@ public class JpaWebAutoConfigurationTests { public void testDefaultRepositoryConfiguration() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - SpringDataWebAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + SpringDataWebAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); - assertThat(this.context.getBean(PageableHandlerMethodArgumentResolver.class)) - .isNotNull(); - assertThat(this.context.getBean(FormattingConversionService.class) - .canConvert(Long.class, City.class)).isTrue(); + assertThat(this.context.getBean(PageableHandlerMethodArgumentResolver.class)).isNotNull(); + assertThat(this.context.getBean(FormattingConversionService.class).canConvert(Long.class, City.class)).isTrue(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java index d755d763a8a..5180e96a9c3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ public interface CityRepository extends JpaRepository { @Override Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java index f3bd8f563c2..1d4a43377bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java @@ -69,11 +69,9 @@ public class LdapRepositoriesAutoConfigurationTests { private void load(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.ldap.urls:ldap://localhost:389") - .applyTo(this.context); + TestPropertyValues.of("spring.ldap.urls:ldap://localhost:389").applyTo(this.context); this.context.register(configurationClasses); - this.context.register(LdapAutoConfiguration.class, - LdapRepositoriesAutoConfiguration.class, + this.context.register(LdapAutoConfiguration.class, LdapRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java index 77bf3351d15..5d58a0ed179 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java @@ -63,8 +63,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.initialization-mode:never") - .applyTo(this.context); + TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(TestConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); @@ -73,8 +72,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testMixedRepositoryConfiguration() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.initialization-mode:never") - .applyTo(this.context); + TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(MixedConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); @@ -84,8 +82,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testJpaRepositoryConfigurationWithMongoTemplate() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.initialization-mode:never") - .applyTo(this.context); + TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(JpaConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); @@ -94,8 +91,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testJpaRepositoryConfigurationWithMongoOverlap() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.initialization-mode:never") - .applyTo(this.context); + TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); @@ -105,8 +101,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { public void testJpaRepositoryConfigurationWithMongoOverlapDisabled() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.datasource.initialization-mode:never", - "spring.data.mongodb.repositories.type:none") + .of("spring.datasource.initialization-mode:never", "spring.data.mongodb.repositories.type:none") .applyTo(this.context); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); @@ -159,9 +154,8 @@ public class MixedMongoRepositoriesAutoConfigurationTests { public String[] selectImports(AnnotationMetadata importingClassMetadata) { List names = new ArrayList<>(); for (Class type : new Class[] { DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, + HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class }) { names.add(type.getName()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index b439207c1d6..81d14d73f99 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -62,31 +62,27 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)); @Test public void templateExists() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); } @Test public void gridFsTemplateExists() { this.contextRunner.withPropertyValues("spring.data.mongodb.gridFsDatabase:grid") - .run((context) -> assertThat(context) - .hasSingleBean(GridFsTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(GridFsTemplate.class)); } @Test public void customConversions() { - this.contextRunner.withUserConfiguration(CustomConversionsConfig.class) - .run((context) -> { - MongoTemplate template = context.getBean(MongoTemplate.class); - assertThat(template.getConverter().getConversionService() - .canConvert(MongoClient.class, Boolean.class)).isTrue(); - }); + this.contextRunner.withUserConfiguration(CustomConversionsConfig.class).run((context) -> { + MongoTemplate template = context.getBean(MongoTemplate.class); + assertThat(template.getConverter().getConversionService().canConvert(MongoClient.class, Boolean.class)) + .isTrue(); + }); } @Test @@ -97,8 +93,7 @@ public class MongoDataAutoConfigurationTests { context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); try { context.refresh(); - assertDomainTypesDiscovered(context.getBean(MongoMappingContext.class), - City.class); + assertDomainTypesDiscovered(context.getBean(MongoMappingContext.class), City.class); } finally { context.close(); @@ -108,23 +103,19 @@ public class MongoDataAutoConfigurationTests { @Test public void defaultFieldNamingStrategy() { this.contextRunner.run((context) -> { - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); - FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils - .getField(mappingContext, "fieldNamingStrategy"); - assertThat(fieldNamingStrategy.getClass()) - .isEqualTo(PropertyNameFieldNamingStrategy.class); + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils.getField(mappingContext, + "fieldNamingStrategy"); + assertThat(fieldNamingStrategy.getClass()).isEqualTo(PropertyNameFieldNamingStrategy.class); }); } @Test public void customFieldNamingStrategy() { - this.contextRunner - .withPropertyValues("spring.data.mongodb.field-naming-strategy:" - + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) + this.contextRunner.withPropertyValues( + "spring.data.mongodb.field-naming-strategy:" + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) .run((context) -> { - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils .getField(mappingContext, "fieldNamingStrategy"); assertThat(fieldNamingStrategy.getClass()) @@ -134,45 +125,36 @@ public class MongoDataAutoConfigurationTests { @Test public void customAutoIndexCreation() { - this.contextRunner - .withPropertyValues("spring.data.mongodb.autoIndexCreation:false") - .run((context) -> { - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); - assertThat(mappingContext.isAutoIndexCreation()).isFalse(); - }); + this.contextRunner.withPropertyValues("spring.data.mongodb.autoIndexCreation:false").run((context) -> { + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + assertThat(mappingContext.isAutoIndexCreation()).isFalse(); + }); } @Test public void interfaceFieldNamingStrategy() { this.contextRunner - .withPropertyValues("spring.data.mongodb.field-naming-strategy:" - + FieldNamingStrategy.class.getName()) - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class)); + .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() { - this.contextRunner.withUserConfiguration(EntityScanConfig.class) - .run((context) -> { - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); - assertThat(initialEntitySet).containsOnly(City.class, Country.class); - }); + this.contextRunner.withUserConfiguration(EntityScanConfig.class).run((context) -> { + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); + assertThat(initialEntitySet).containsOnly(City.class, Country.class); + }); } @Test public void registersDefaultSimpleTypesWithMappingContext() { this.contextRunner.run((context) -> { - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); - BasicMongoPersistentEntity entity = mappingContext - .getPersistentEntity(Sample.class); + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + BasicMongoPersistentEntity entity = mappingContext.getPersistentEntity(Sample.class); MongoPersistentProperty dateProperty = entity.getPersistentProperty("date"); assertThat(dateProperty.isEntity()).isFalse(); }); @@ -182,10 +164,8 @@ public class MongoDataAutoConfigurationTests { @Test public void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(MongoDataAutoConfiguration.class)); - runner.run((context) -> assertThat(context) - .doesNotHaveBean(MongoDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoDataAutoConfiguration.class)); + runner.run((context) -> assertThat(context).doesNotHaveBean(MongoDataAutoConfiguration.class)); } @Test @@ -198,18 +178,15 @@ public class MongoDataAutoConfigurationTests { @Test public void createsMongoDbFactoryForFallbackMongoClient() { - this.contextRunner.withUserConfiguration(FallbackMongoClientConfiguration.class) - .run((context) -> { - MongoDbFactory dbFactory = context.getBean(MongoDbFactory.class); - assertThat(dbFactory).isInstanceOf(SimpleMongoClientDbFactory.class); - }); + this.contextRunner.withUserConfiguration(FallbackMongoClientConfiguration.class).run((context) -> { + MongoDbFactory dbFactory = context.getBean(MongoDbFactory.class); + assertThat(dbFactory).isInstanceOf(SimpleMongoClientDbFactory.class); + }); } @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void assertDomainTypesDiscovered(MongoMappingContext mappingContext, - Class... types) { - Set initialEntitySet = (Set) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + private static void assertDomainTypesDiscovered(MongoMappingContext mappingContext, Class... types) { + Set initialEntitySet = (Set) ReflectionTestUtils.getField(mappingContext, "initialEntitySet"); assertThat(initialEntitySet).containsOnly(types); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java index 7317c710255..e9d26d4eff3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java @@ -58,10 +58,8 @@ public class MongoReactiveAndBlockingRepositoriesAutoConfigurationTests { @Test public void shouldCreateInstancesForReactiveAndBlockingRepositories() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.initialization-mode:never") - .applyTo(this.context); - this.context.register(BlockingAndReactiveConfiguration.class, - BaseConfiguration.class); + TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); + this.context.register(BlockingAndReactiveConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); assertThat(this.context.getBean(ReactiveCityRepository.class)).isNotNull(); @@ -86,12 +84,9 @@ public class MongoReactiveAndBlockingRepositoriesAutoConfigurationTests { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { List names = new ArrayList<>(); - for (Class type : new Class[] { MongoAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoRepositoriesAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, - MongoReactiveRepositoriesAutoConfiguration.class }) { + for (Class type : new Class[] { MongoAutoConfiguration.class, MongoReactiveAutoConfiguration.class, + MongoDataAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class, + MongoReactiveDataAutoConfiguration.class, MongoReactiveRepositoriesAutoConfiguration.class }) { names.add(type.getName()); } return StringUtils.toStringArray(names); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java index ddeecbeb448..5666200ea14 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java @@ -36,31 +36,24 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); @Test public void templateExists() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ReactiveMongoTemplate.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ReactiveMongoTemplate.class)); } @Test public void gridFsTemplateExists() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ReactiveGridFsTemplate.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ReactiveGridFsTemplate.class)); } @Test public void backsOffIfMongoClientBeanIsNotPresent() { - ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class)); - runner.run((context) -> assertThat(context) - .doesNotHaveBean(MongoReactiveDataAutoConfiguration.class)); + ApplicationContextRunner runner = new ApplicationContextRunner().withConfiguration(AutoConfigurations + .of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); + runner.run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveDataAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java index bff7a812502..6d3698451a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java @@ -49,26 +49,21 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, - MongoReactiveRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveCityRepository.class); - assertThat(context).hasSingleBean(MongoClient.class); - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); - @SuppressWarnings("unchecked") - Set> entities = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); - assertThat(entities).hasSize(1); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(ReactiveCityRepository.class); + assertThat(context).hasSingleBean(MongoClient.class); + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + @SuppressWarnings("unchecked") + Set> entities = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); + assertThat(entities).hasSize(1); + }); } @Test @@ -80,31 +75,27 @@ public class MongoReactiveRepositoriesAutoConfigurationTests { @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveCityMongoDbRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityMongoDbRepository.class)); } @Test public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test public void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=imperative") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test public void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=none") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java index ebdaadc8bff..609447fa677 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java @@ -46,24 +46,20 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test public void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context).hasSingleBean(MongoClient.class); - MongoMappingContext mappingContext = context - .getBean(MongoMappingContext.class); - @SuppressWarnings("unchecked") - Set> entities = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); - assertThat(entities).hasSize(1); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context).hasSingleBean(MongoClient.class); + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + @SuppressWarnings("unchecked") + Set> entities = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); + assertThat(entities).hasSize(1); + }); } @Test @@ -75,31 +71,27 @@ public class MongoRepositoriesAutoConfigurationTests { @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(CityMongoDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityMongoDbRepository.class)); } @Test public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test public void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=reactive") - .run((context) -> assertThat(context) - .doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test public void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=none") - .run((context) -> assertThat(context) - .doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java index 9ecd43d14c8..494d76b6c07 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ public interface CityRepository extends Repository { Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java index bf25b75dd93..955b3bbe94f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java @@ -95,11 +95,9 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { private void load(Class config, String... environment) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.setClassLoader(new FilteredClassLoader(EmbeddedDriver.class)); - TestPropertyValues.of(environment) - .and("spring.datasource.initialization-mode=never").applyTo(context); + TestPropertyValues.of(environment).and("spring.datasource.initialization-mode=never").applyTo(context); context.register(config); - context.register(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, + context.register(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class); context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java index 0bd36d8f0f2..459deea99ba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java @@ -67,32 +67,25 @@ public class Neo4jDataAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withClassLoader(new FilteredClassLoader(EmbeddedDriver.class)) - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - TransactionAutoConfiguration.class)); + .withUserConfiguration(TestConfiguration.class).withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test public void defaultConfiguration() { - this.contextRunner - .withPropertyValues("spring.data.neo4j.uri=http://localhost:8989") - .run((context) -> { - assertThat(context) - .hasSingleBean(org.neo4j.ogm.config.Configuration.class); - assertThat(context).hasSingleBean(SessionFactory.class); - assertThat(context).hasSingleBean(Neo4jTransactionManager.class); - assertThat(context).hasSingleBean(OpenSessionInViewInterceptor.class); - assertThat(context).doesNotHaveBean(BookmarkManager.class); - }); + this.contextRunner.withPropertyValues("spring.data.neo4j.uri=http://localhost:8989").run((context) -> { + assertThat(context).hasSingleBean(org.neo4j.ogm.config.Configuration.class); + assertThat(context).hasSingleBean(SessionFactory.class); + assertThat(context).hasSingleBean(Neo4jTransactionManager.class); + assertThat(context).hasSingleBean(OpenSessionInViewInterceptor.class); + assertThat(context).doesNotHaveBean(BookmarkManager.class); + }); } @Test public void customNeo4jTransactionManagerUsingProperties() { - this.contextRunner - .withPropertyValues("spring.transaction.default-timeout=30", - "spring.transaction.rollback-on-commit-failure:true") - .run((context) -> { - Neo4jTransactionManager transactionManager = context - .getBean(Neo4jTransactionManager.class); + this.contextRunner.withPropertyValues("spring.transaction.default-timeout=30", + "spring.transaction.rollback-on-commit-failure:true").run((context) -> { + Neo4jTransactionManager transactionManager = context.getBean(Neo4jTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); }); @@ -100,24 +93,20 @@ public class Neo4jDataAutoConfigurationTests { @Test public void customSessionFactory() { - this.contextRunner.withUserConfiguration(CustomSessionFactory.class) - .run((context) -> { - assertThat(context) - .doesNotHaveBean(org.neo4j.ogm.config.Configuration.class); - assertThat(context).hasSingleBean(SessionFactory.class); - }); + this.contextRunner.withUserConfiguration(CustomSessionFactory.class).run((context) -> { + assertThat(context).doesNotHaveBean(org.neo4j.ogm.config.Configuration.class); + assertThat(context).hasSingleBean(SessionFactory.class); + }); } @Test public void customConfiguration() { - this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> { - assertThat(context.getBean(org.neo4j.ogm.config.Configuration.class)) - .isSameAs(context.getBean("myConfiguration")); - assertThat(context).hasSingleBean(SessionFactory.class); - assertThat(context) - .hasSingleBean(org.neo4j.ogm.config.Configuration.class); - }); + this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { + assertThat(context.getBean(org.neo4j.ogm.config.Configuration.class)) + .isSameAs(context.getBean("myConfiguration")); + assertThat(context).hasSingleBean(SessionFactory.class); + assertThat(context).hasSingleBean(org.neo4j.ogm.config.Configuration.class); + }); } @Test @@ -126,12 +115,10 @@ public class Neo4jDataAutoConfigurationTests { context.setClassLoader(new FilteredClassLoader(EmbeddedDriver.class)); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(context, cityPackage); - context.register(Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class); + context.register(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class); try { context.refresh(); - assertDomainTypesDiscovered(context.getBean(Neo4jMappingContext.class), - City.class); + assertDomainTypesDiscovered(context.getBean(Neo4jMappingContext.class), City.class); } finally { context.close(); @@ -141,8 +128,7 @@ public class Neo4jDataAutoConfigurationTests { @Test public void openSessionInViewInterceptorCanBeDisabled() { this.contextRunner.withPropertyValues("spring.data.neo4j.open-in-view:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(OpenSessionInViewInterceptor.class)); + .run((context) -> assertThat(context).doesNotHaveBean(OpenSessionInViewInterceptor.class)); } @Test @@ -150,26 +136,23 @@ public class Neo4jDataAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.data.neo4j.uri=bolt://localhost:7687", "spring.data.neo4j.use-native-types:true") - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - TransactionAutoConfiguration.class)) - .run((context) -> assertThat(context) - .getBean(org.neo4j.ogm.config.Configuration.class) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(org.neo4j.ogm.config.Configuration.class) .hasFieldOrPropertyWithValue("useNativeTypes", true)); } @Test public void shouldFailWhenNativeTypesAreNotAvailable() { - this.contextRunner - .withClassLoader( - new FilteredClassLoader("org.neo4j.ogm.drivers.bolt.types")) + this.contextRunner.withClassLoader(new FilteredClassLoader("org.neo4j.ogm.drivers.bolt.types")) .withPropertyValues("spring.data.neo4j.uri=bolt://localhost:7687", "spring.data.neo4j.use-native-types:true") - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - TransactionAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class)) .run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasRootCauseInstanceOf( - NativeTypesNotAvailableException.class); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(NativeTypesNotAvailableException.class); }); } @@ -178,68 +161,54 @@ public class Neo4jDataAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.data.neo4j.uri=http://localhost:7474", "spring.data.neo4j.use-native-types:true") - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - TransactionAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class)) .run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasRootCauseInstanceOf( - NativeTypesNotSupportedException.class); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(NativeTypesNotSupportedException.class); }); } @Test public void eventListenersAreAutoRegistered() { - this.contextRunner.withUserConfiguration(EventListenerConfiguration.class) - .run((context) -> { - Session session = context.getBean(SessionFactory.class).openSession(); - session.notifyListeners( - new PersistenceEvent(null, Event.TYPE.PRE_SAVE)); - verify(context.getBean("eventListenerOne", EventListener.class)) - .onPreSave(any(Event.class)); - verify(context.getBean("eventListenerTwo", EventListener.class)) - .onPreSave(any(Event.class)); - }); + this.contextRunner.withUserConfiguration(EventListenerConfiguration.class).run((context) -> { + Session session = context.getBean(SessionFactory.class).openSession(); + session.notifyListeners(new PersistenceEvent(null, Event.TYPE.PRE_SAVE)); + verify(context.getBean("eventListenerOne", EventListener.class)).onPreSave(any(Event.class)); + verify(context.getBean("eventListenerTwo", EventListener.class)).onPreSave(any(Event.class)); + }); } @Test public void providesARequestScopedBookmarkManagerIfNecessaryAndPossible() { - this.contextRunner - .withUserConfiguration(BookmarkManagementEnabledConfiguration.class) - .run((context) -> { - BeanDefinition bookmarkManagerBean = context.getBeanFactory() - .getBeanDefinition("scopedTarget.bookmarkManager"); - assertThat(bookmarkManagerBean.getScope()) - .isEqualTo(WebApplicationContext.SCOPE_REQUEST); - }); + this.contextRunner.withUserConfiguration(BookmarkManagementEnabledConfiguration.class).run((context) -> { + BeanDefinition bookmarkManagerBean = context.getBeanFactory() + .getBeanDefinition("scopedTarget.bookmarkManager"); + assertThat(bookmarkManagerBean.getScope()).isEqualTo(WebApplicationContext.SCOPE_REQUEST); + }); } @Test public void providesASingletonScopedBookmarkManagerIfNecessaryAndPossible() { - new ApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(EmbeddedDriver.class)) - .withUserConfiguration(TestConfiguration.class, - BookmarkManagementEnabledConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - TransactionAutoConfiguration.class)) + new ApplicationContextRunner().withClassLoader(new FilteredClassLoader(EmbeddedDriver.class)) + .withUserConfiguration(TestConfiguration.class, BookmarkManagementEnabledConfiguration.class) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class)) .run((context) -> { assertThat(context).hasSingleBean(BookmarkManager.class); - assertThat(context.getBeanDefinitionNames()) - .doesNotContain("scopedTarget.bookmarkManager"); + assertThat(context.getBeanDefinitionNames()).doesNotContain("scopedTarget.bookmarkManager"); }); } @Test public void doesNotProvideABookmarkManagerIfNotPossible() { - this.contextRunner - .withClassLoader( - new FilteredClassLoader(Caffeine.class, EmbeddedDriver.class)) + this.contextRunner.withClassLoader(new FilteredClassLoader(Caffeine.class, EmbeddedDriver.class)) .withUserConfiguration(BookmarkManagementEnabledConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(BookmarkManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BookmarkManager.class)); } - private static void assertDomainTypesDiscovered(Neo4jMappingContext mappingContext, - Class... types) { + private static void assertDomainTypesDiscovered(Neo4jMappingContext mappingContext, Class... types) { for (Class type : types) { assertThat(mappingContext.getPersistentEntity(type)).isNotNull(); } @@ -266,8 +235,7 @@ public class Neo4jDataAutoConfigurationTests { @Bean public org.neo4j.ogm.config.Configuration myConfiguration() { - return new org.neo4j.ogm.config.Configuration.Builder() - .uri("http://localhost:12345").build(); + return new org.neo4j.ogm.config.Configuration.Builder().uri("http://localhost:12345").build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java index 67bda705f46..f3b5d1a555b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java @@ -59,48 +59,40 @@ public class Neo4jPropertiesTests { public void defaultUseBoltDriverIfEmbeddedDriverIsNotAvailable() { Neo4jProperties properties = load(false); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, - Neo4jProperties.DEFAULT_BOLT_URI); + assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, Neo4jProperties.DEFAULT_BOLT_URI); } @Test public void httpUriUseHttpDriver() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=http://localhost:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474"); } @Test public void httpsUriUseHttpDriver() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=https://localhost:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=https://localhost:7474"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, - "https://localhost:7474"); + assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "https://localhost:7474"); } @Test public void boltUriUseBoltDriver() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=bolt://localhost:7687"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=bolt://localhost:7687"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, "bolt://localhost:7687"); } @Test public void fileUriUseEmbeddedServer() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=file://var/tmp/graph.db"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file://var/tmp/graph.db"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, - "file://var/tmp/graph.db"); + assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file://var/tmp/graph.db"); } @Test public void credentialsAreSet() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=http://localhost:7474", + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474", "spring.data.neo4j.username=user", "spring.data.neo4j.password=secret"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474"); @@ -109,11 +101,9 @@ public class Neo4jPropertiesTests { @Test public void credentialsAreSetFromUri() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=https://user:secret@my-server:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=https://user:secret@my-server:7474"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, - "https://my-server:7474"); + assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "https://my-server:7474"); assertCredentials(configuration, "user", "secret"); } @@ -133,20 +123,16 @@ public class Neo4jPropertiesTests { @Test public void embeddedModeDisabledUseBoltUri() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.embedded.enabled=false"); + Neo4jProperties properties = load(true, "spring.data.neo4j.embedded.enabled=false"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, - Neo4jProperties.DEFAULT_BOLT_URI); + assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, Neo4jProperties.DEFAULT_BOLT_URI); } @Test public void embeddedModeWithRelativeLocation() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=file:relative/path/to/my.db"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file:relative/path/to/my.db"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, - "file:relative/path/to/my.db"); + assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file:relative/path/to/my.db"); } @Test @@ -158,8 +144,7 @@ public class Neo4jPropertiesTests { @Test public void nativeTypesCanBeConfigured() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.use-native-types=true"); + Neo4jProperties properties = load(true, "spring.data.neo4j.use-native-types=true"); Configuration configuration = properties.createConfiguration(); assertThat(configuration.getUseNativeTypes()).isTrue(); } @@ -170,8 +155,7 @@ public class Neo4jPropertiesTests { assertThat(actual.getURI()).isEqualTo(uri); } - private static void assertCredentials(Configuration actual, String username, - String password) { + private static void assertCredentials(Configuration actual, String username, String password) { Credentials credentials = actual.getCredentials(); if (username == null && password == null) { assertThat(credentials).isNull(); @@ -180,8 +164,7 @@ public class Neo4jPropertiesTests { assertThat(credentials).isNotNull(); Object content = credentials.credentials(); assertThat(content).isInstanceOf(String.class); - String[] auth = new String(Base64.decode(((String) content).getBytes())) - .split(":"); + String[] auth = new String(Base64.decode(((String) content).getBytes())).split(":"); assertThat(auth[0]).isEqualTo(username); assertThat(auth[1]).isEqualTo(password); assertThat(auth).hasSize(2); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java index be013f355cd..13fa35e70e9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java @@ -58,8 +58,7 @@ public class Neo4jRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() { prepareApplicationContext(TestConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); - Neo4jMappingContext mappingContext = this.context - .getBean(Neo4jMappingContext.class); + Neo4jMappingContext mappingContext = this.context.getBean(Neo4jMappingContext.class); assertThat(mappingContext.getPersistentEntity(City.class)).isNotNull(); } @@ -84,11 +83,9 @@ public class Neo4jRepositoriesAutoConfigurationTests { private void prepareApplicationContext(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.data.neo4j.uri=http://localhost:9797") - .applyTo(this.context); + TestPropertyValues.of("spring.data.neo4j.uri=http://localhost:9797").applyTo(this.context); this.context.register(configurationClasses); - this.context.register(Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class, + this.context.register(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java index 050d94625f9..310ad8875f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java @@ -47,36 +47,29 @@ public class RedisAutoConfigurationJedisTests { @Test public void testOverrideRedisConfiguration() { - this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.database:1") - .run((context) -> { - JedisConnectionFactory cf = context - .getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getDatabase()).isEqualTo(1); - assertThat(cf.getPassword()).isNull(); - assertThat(cf.isUseSsl()).isFalse(); - }); + this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.database:1").run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getDatabase()).isEqualTo(1); + assertThat(cf.getPassword()).isNull(); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test public void testCustomizeRedisConfiguration() { - this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> { - JedisConnectionFactory cf = context - .getBean(JedisConnectionFactory.class); - assertThat(cf.isUseSsl()).isTrue(); - }); + this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test public void testRedisUrlConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", - "spring.redis.url:redis://user:password@example:33") + .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") .run((context) -> { - JedisConnectionFactory cf = context - .getBean(JedisConnectionFactory.class); + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("example"); assertThat(cf.getPort()).isEqualTo(33); assertThat(cf.getPassword()).isEqualTo("password"); @@ -87,12 +80,10 @@ public class RedisAutoConfigurationJedisTests { @Test public void testOverrideUrlRedisConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", - "spring.redis.port:1000", "spring.redis.ssl:false", - "spring.redis.url:rediss://user:password@example:33") + .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", + "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") .run((context) -> { - JedisConnectionFactory cf = context - .getBean(JedisConnectionFactory.class); + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("example"); assertThat(cf.getPort()).isEqualTo(33); assertThat(cf.getPassword()).isEqualTo("password"); @@ -102,68 +93,45 @@ public class RedisAutoConfigurationJedisTests { @Test public void testPasswordInUrlWithColon() { - this.contextRunner - .withPropertyValues("spring.redis.url:redis://:pass:word@example:33") - .run((context) -> { - assertThat( - context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("example"); - assertThat(context.getBean(JedisConnectionFactory.class).getPort()) - .isEqualTo(33); - assertThat( - context.getBean(JedisConnectionFactory.class).getPassword()) - .isEqualTo("pass:word"); - }); + this.contextRunner.withPropertyValues("spring.redis.url:redis://:pass:word@example:33").run((context) -> { + assertThat(context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); + assertThat(context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); + assertThat(context.getBean(JedisConnectionFactory.class).getPassword()).isEqualTo("pass:word"); + }); } @Test public void testPasswordInUrlStartsWithColon() { - this.contextRunner - .withPropertyValues("spring.redis.url:redis://user::pass:word@example:33") - .run((context) -> { - assertThat( - context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("example"); - assertThat(context.getBean(JedisConnectionFactory.class).getPort()) - .isEqualTo(33); - assertThat( - context.getBean(JedisConnectionFactory.class).getPassword()) - .isEqualTo(":pass:word"); - }); + this.contextRunner.withPropertyValues("spring.redis.url:redis://user::pass:word@example:33").run((context) -> { + assertThat(context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); + assertThat(context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); + assertThat(context.getBean(JedisConnectionFactory.class).getPassword()).isEqualTo(":pass:word"); + }); } @Test public void testRedisConfigurationWithPool() { - this.contextRunner - .withPropertyValues("spring.redis.host:foo", - "spring.redis.jedis.pool.min-idle:1", - "spring.redis.jedis.pool.max-idle:4", - "spring.redis.jedis.pool.max-active:16", - "spring.redis.jedis.pool.max-wait:2000", - "spring.redis.jedis.pool.time-between-eviction-runs:30000") + this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.jedis.pool.min-idle:1", + "spring.redis.jedis.pool.max-idle:4", "spring.redis.jedis.pool.max-active:16", + "spring.redis.jedis.pool.max-wait:2000", "spring.redis.jedis.pool.time-between-eviction-runs:30000") .run((context) -> { - JedisConnectionFactory cf = context - .getBean(JedisConnectionFactory.class); + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); assertThat(cf.getPoolConfig().getMinIdle()).isEqualTo(1); assertThat(cf.getPoolConfig().getMaxIdle()).isEqualTo(4); assertThat(cf.getPoolConfig().getMaxTotal()).isEqualTo(16); assertThat(cf.getPoolConfig().getMaxWaitMillis()).isEqualTo(2000); - assertThat(cf.getPoolConfig().getTimeBetweenEvictionRunsMillis()) - .isEqualTo(30000); + assertThat(cf.getPoolConfig().getTimeBetweenEvictionRunsMillis()).isEqualTo(30000); }); } @Test public void testRedisConfigurationWithTimeout() { - this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:100") - .run((context) -> { - JedisConnectionFactory cf = context - .getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(100); - }); + this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:100").run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(100); + }); } @Test @@ -171,38 +139,29 @@ public class RedisAutoConfigurationJedisTests { this.contextRunner .withPropertyValues("spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) - .run((context) -> { + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(JedisConnectionFactoryCaptor.connectionFactory - .isRedisSentinelAware()).isTrue(); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); }); } @Test public void testRedisConfigurationWithSentinelAndPassword() { this.contextRunner - .withPropertyValues("spring.redis.password=password", - "spring.redis.sentinel.master:mymaster", + .withPropertyValues("spring.redis.password=password", "spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) - .run((context) -> { + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(JedisConnectionFactoryCaptor.connectionFactory - .isRedisSentinelAware()).isTrue(); - assertThat( - JedisConnectionFactoryCaptor.connectionFactory.getPassword()) - .isEqualTo("password"); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.getPassword()).isEqualTo("password"); }); } @Test public void testRedisConfigurationWithCluster() { - this.contextRunner - .withPropertyValues( - "spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") - .run((context) -> assertThat(context.getBean(JedisConnectionFactory.class) - .getClusterConnection()).isNotNull()); + this.contextRunner.withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") + .run((context) -> assertThat(context.getBean(JedisConnectionFactory.class).getClusterConnection()) + .isNotNull()); } @Configuration(proxyBeanMethods = false) @@ -230,8 +189,7 @@ public class RedisAutoConfigurationJedisTests { static JedisConnectionFactory connectionFactory; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof JedisConnectionFactory) { connectionFactory = (JedisConnectionFactory) bean; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index dc1b43a4f4e..1cb7c4e523c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -60,19 +60,16 @@ public class RedisAutoConfigurationTests { @Test public void testDefaultRedisConfiguration() { this.contextRunner.run((context) -> { - assertThat(context.getBean("redisTemplate", RedisOperations.class)) - .isNotNull(); + assertThat(context.getBean("redisTemplate", RedisOperations.class)).isNotNull(); assertThat(context.getBean(StringRedisTemplate.class)).isNotNull(); }); } @Test public void testOverrideRedisConfiguration() { - this.contextRunner.withPropertyValues("spring.redis.host:foo", - "spring.redis.database:1", "spring.redis.lettuce.shutdown-timeout:500") - .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); + this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.database:1", + "spring.redis.lettuce.shutdown-timeout:500").run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); assertThat(cf.getDatabase()).isEqualTo(1); assertThat(cf.getPassword()).isNull(); @@ -83,22 +80,18 @@ public class RedisAutoConfigurationTests { @Test public void testCustomizeRedisConfiguration() { - this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.isUseSsl()).isTrue(); - }); + this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test public void testRedisUrlConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", - "spring.redis.url:redis://user:password@example:33") + .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("example"); assertThat(cf.getPort()).isEqualTo(33); assertThat(cf.getPassword()).isEqualTo("password"); @@ -109,12 +102,10 @@ public class RedisAutoConfigurationTests { @Test public void testOverrideUrlRedisConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", - "spring.redis.port:1000", "spring.redis.ssl:false", - "spring.redis.url:rediss://user:password@example:33") + .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", + "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("example"); assertThat(cf.getPort()).isEqualTo(33); assertThat(cf.getPassword()).isEqualTo("password"); @@ -124,64 +115,49 @@ public class RedisAutoConfigurationTests { @Test public void testPasswordInUrlWithColon() { - this.contextRunner - .withPropertyValues("spring.redis.url:redis://:pass:word@example:33") - .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(cf.getPassword()).isEqualTo("pass:word"); - }); + this.contextRunner.withPropertyValues("spring.redis.url:redis://:pass:word@example:33").run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(cf.getPassword()).isEqualTo("pass:word"); + }); } @Test public void testPasswordInUrlStartsWithColon() { - this.contextRunner - .withPropertyValues("spring.redis.url:redis://user::pass:word@example:33") - .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(cf.getPassword()).isEqualTo(":pass:word"); - }); + this.contextRunner.withPropertyValues("spring.redis.url:redis://user::pass:word@example:33").run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(cf.getPassword()).isEqualTo(":pass:word"); + }); } @Test public void testRedisConfigurationWithPool() { - this.contextRunner.withPropertyValues("spring.redis.host:foo", - "spring.redis.lettuce.pool.min-idle:1", - "spring.redis.lettuce.pool.max-idle:4", - "spring.redis.lettuce.pool.max-active:16", - "spring.redis.lettuce.pool.max-wait:2000", - "spring.redis.lettuce.pool.time-between-eviction-runs:30000", + this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.lettuce.pool.min-idle:1", + "spring.redis.lettuce.pool.max-idle:4", "spring.redis.lettuce.pool.max-active:16", + "spring.redis.lettuce.pool.max-wait:2000", "spring.redis.lettuce.pool.time-between-eviction-runs:30000", "spring.redis.lettuce.shutdown-timeout:1000").run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); - GenericObjectPoolConfig poolConfig = getPoolingClientConfiguration( - cf).getPoolConfig(); + GenericObjectPoolConfig poolConfig = getPoolingClientConfiguration(cf).getPoolConfig(); assertThat(poolConfig.getMinIdle()).isEqualTo(1); assertThat(poolConfig.getMaxIdle()).isEqualTo(4); assertThat(poolConfig.getMaxTotal()).isEqualTo(16); assertThat(poolConfig.getMaxWaitMillis()).isEqualTo(2000); - assertThat(poolConfig.getTimeBetweenEvictionRunsMillis()) - .isEqualTo(30000); + assertThat(poolConfig.getTimeBetweenEvictionRunsMillis()).isEqualTo(30000); assertThat(cf.getShutdownTimeout()).isEqualTo(1000); }); } @Test public void testRedisConfigurationWithTimeout() { - this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:100") - .run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(100); - }); + this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:100").run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(100); + }); } @Test @@ -189,22 +165,16 @@ public class RedisAutoConfigurationTests { List sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380"); this.contextRunner .withPropertyValues("spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:" - + StringUtils.collectionToCommaDelimitedString(sentinels)) - .run((context) -> assertThat(context - .getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) - .isTrue()); + "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) + .isTrue()); } @Test public void testRedisConfigurationWithSentinelAndDatabase() { - this.contextRunner - .withPropertyValues("spring.redis.database:1", - "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run((context) -> { - LettuceConnectionFactory connectionFactory = context - .getBean(LettuceConnectionFactory.class); + this.contextRunner.withPropertyValues("spring.redis.database:1", "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380").run((context) -> { + LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); assertThat(connectionFactory.getDatabase()).isEqualTo(1); assertThat(connectionFactory.isRedisSentinelAware()).isTrue(); }); @@ -212,38 +182,27 @@ public class RedisAutoConfigurationTests { @Test public void testRedisConfigurationWithSentinelAndPassword() { - this.contextRunner - .withPropertyValues("spring.redis.password=password", - "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run((context) -> { - LettuceConnectionFactory connectionFactory = context - .getBean(LettuceConnectionFactory.class); + this.contextRunner.withPropertyValues("spring.redis.password=password", "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380").run((context) -> { + LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); assertThat(connectionFactory.getPassword()).isEqualTo("password"); - Set sentinels = connectionFactory - .getSentinelConfiguration().getSentinels(); - assertThat(sentinels.stream().map(Object::toString) - .collect(Collectors.toSet())).contains("127.0.0.1:26379", - "127.0.0.1:26380"); + Set sentinels = connectionFactory.getSentinelConfiguration().getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); }); } @Test public void testRedisConfigurationWithCluster() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - this.contextRunner - .withPropertyValues( - "spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) - .run((context) -> { - RedisClusterConfiguration clusterConfiguration = context - .getBean(LettuceConnectionFactory.class) + this.contextRunner.withPropertyValues("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)).run((context) -> { + RedisClusterConfiguration clusterConfiguration = context.getBean(LettuceConnectionFactory.class) .getClusterConfiguration(); assertThat(clusterConfiguration.getClusterNodes()).hasSize(2); assertThat(clusterConfiguration.getClusterNodes()) .extracting((node) -> node.getHost() + ":" + node.getPort()) - .containsExactlyInAnyOrder("127.0.0.1:27379", - "127.0.0.1:27380"); + .containsExactlyInAnyOrder("127.0.0.1:27379", "127.0.0.1:27380"); }); } @@ -255,17 +214,14 @@ public class RedisAutoConfigurationTests { .withPropertyValues("spring.redis.password=password", "spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) - .run((context) -> assertThat( - context.getBean(LettuceConnectionFactory.class).getPassword()) - .isEqualTo("password") + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).getPassword()) + .isEqualTo("password") ); } - private LettucePoolingClientConfiguration getPoolingClientConfiguration( - LettuceConnectionFactory factory) { - return (LettucePoolingClientConfiguration) ReflectionTestUtils.getField(factory, - "clientConfiguration"); + private LettucePoolingClientConfiguration getPoolingClientConfiguration(LettuceConnectionFactory factory) { + return (LettucePoolingClientConfiguration) ReflectionTestUtils.getField(factory, "clientConfiguration"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java index 62a7f9759a6..d84e5282d70 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java @@ -33,16 +33,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class RedisReactiveAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); @Test public void testDefaultRedisConfiguration() { this.contextRunner.run((context) -> { Map beans = context.getBeansOfType(ReactiveRedisTemplate.class); - assertThat(beans).containsOnlyKeys("reactiveRedisTemplate", - "reactiveStringRedisTemplate"); + assertThat(beans).containsOnlyKeys("reactiveRedisTemplate", "reactiveStringRedisTemplate"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java index 40e914508af..63edce3cf1c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java @@ -51,8 +51,7 @@ public class RedisRepositoriesAutoConfigurationTests { @BeforeEach public void setUp() { - TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) - .applyTo(this.context.getEnvironment()); + TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()).applyTo(this.context.getEnvironment()); } @AfterEach @@ -63,8 +62,7 @@ public class RedisRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() { this.context.register(TestConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @@ -72,8 +70,7 @@ public class RedisRepositoriesAutoConfigurationTests { @Test public void testNoRepositoryConfiguration() { this.context.register(EmptyConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean("redisTemplate")).isNotNull(); } @@ -81,8 +78,7 @@ public class RedisRepositoriesAutoConfigurationTests { @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.context.register(CustomizedConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRedisRepository.class)).isNotNull(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java index 6fb5c472791..e0561aee866 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ public interface CityRepository extends Repository { Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java index 2f694b55d2d..2ce3ac9b5df 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java @@ -67,50 +67,37 @@ public class RepositoryRestMvcAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() { load(TestConfiguration.class); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); } @Test public void testWithCustomBasePath() { load(TestConfiguration.class, "spring.data.rest.base-path:foo"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); URI expectedUri = URI.create("/foo"); - assertThat(bean.getBaseUri()).as("Custom basePath not set") - .isEqualTo(expectedUri); + assertThat(bean.getBaseUri()).as("Custom basePath not set").isEqualTo(expectedUri); BaseUri baseUri = this.context.getBean(BaseUri.class); - assertThat(expectedUri).as("Custom basePath has not been applied to BaseUri bean") - .isEqualTo(baseUri.getUri()); + assertThat(expectedUri).as("Custom basePath has not been applied to BaseUri bean").isEqualTo(baseUri.getUri()); } @Test public void testWithCustomSettings() { - load(TestConfiguration.class, "spring.data.rest.default-page-size:42", - "spring.data.rest.max-page-size:78", - "spring.data.rest.page-param-name:_page", - "spring.data.rest.limit-param-name:_limit", - "spring.data.rest.sort-param-name:_sort", - "spring.data.rest.detection-strategy=visibility", + load(TestConfiguration.class, "spring.data.rest.default-page-size:42", "spring.data.rest.max-page-size:78", + "spring.data.rest.page-param-name:_page", "spring.data.rest.limit-param-name:_limit", + "spring.data.rest.sort-param-name:_sort", "spring.data.rest.detection-strategy=visibility", "spring.data.rest.default-media-type:application/my-json", - "spring.data.rest.return-body-on-create:false", - "spring.data.rest.return-body-on-update:false", + "spring.data.rest.return-body-on-create:false", "spring.data.rest.return-body-on-update:false", "spring.data.rest.enable-enum-translation:true"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); assertThat(bean.getDefaultPageSize()).isEqualTo(42); assertThat(bean.getMaxPageSize()).isEqualTo(78); assertThat(bean.getPageParamName()).isEqualTo("_page"); assertThat(bean.getLimitParamName()).isEqualTo("_limit"); assertThat(bean.getSortParamName()).isEqualTo("_sort"); - assertThat(bean.getRepositoryDetectionStrategy()) - .isEqualTo(RepositoryDetectionStrategies.VISIBILITY); - assertThat(bean.getDefaultMediaType()) - .isEqualTo(MediaType.parseMediaType("application/my-json")); + assertThat(bean.getRepositoryDetectionStrategy()).isEqualTo(RepositoryDetectionStrategies.VISIBILITY); + assertThat(bean.getDefaultMediaType()).isEqualTo(MediaType.parseMediaType("application/my-json")); assertThat(bean.returnBodyOnCreate(null)).isFalse(); assertThat(bean.returnBodyOnUpdate(null)).isFalse(); assertThat(bean.isEnableEnumTranslation()).isTrue(); @@ -118,27 +105,20 @@ public class RepositoryRestMvcAutoConfigurationTests { @Test public void testWithCustomConfigurer() { - load(TestConfigurationWithConfigurer.class, - "spring.data.rest.detection-strategy=visibility", + load(TestConfigurationWithConfigurer.class, "spring.data.rest.detection-strategy=visibility", "spring.data.rest.default-media-type:application/my-json"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); - assertThat(bean.getRepositoryDetectionStrategy()) - .isEqualTo(RepositoryDetectionStrategies.ALL); - assertThat(bean.getDefaultMediaType()) - .isEqualTo(MediaType.parseMediaType("application/my-custom-json")); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); + assertThat(bean.getRepositoryDetectionStrategy()).isEqualTo(RepositoryDetectionStrategies.ALL); + assertThat(bean.getDefaultMediaType()).isEqualTo(MediaType.parseMediaType("application/my-custom-json")); assertThat(bean.getMaxPageSize()).isEqualTo(78); } @Test public void backOffWithCustomConfiguration() { load(TestConfigurationWithRestMvcConfig.class, "spring.data.rest.base-path:foo"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); assertThat(bean.getBaseUri()).isEqualTo(URI.create("")); } @@ -153,10 +133,9 @@ public class RepositoryRestMvcAutoConfigurationTests { @Configuration(proxyBeanMethods = false) @Import(EmbeddedDataSourceConfiguration.class) - @ImportAutoConfiguration({ HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class, JacksonAutoConfiguration.class }) + @ImportAutoConfiguration({ HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class, + JacksonAutoConfiguration.class }) protected static class BaseConfiguration { } @@ -195,11 +174,9 @@ public class RepositoryRestMvcAutoConfigurationTests { static class TestRepositoryRestConfigurer implements RepositoryRestConfigurer { @Override - public void configureRepositoryRestConfiguration( - RepositoryRestConfiguration config) { + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.setRepositoryDetectionStrategy(RepositoryDetectionStrategies.ALL); - config.setDefaultMediaType( - MediaType.parseMediaType("application/my-custom-json")); + config.setDefaultMediaType(MediaType.parseMediaType("application/my-custom-json")); config.setMaxPageSize(78); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java index 9359c59d2fb..9c76329c894 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java @@ -55,15 +55,13 @@ public class SolrRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() { initContext(TestConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); - assertThat(this.context.getBean(SolrClient.class)) - .isInstanceOf(HttpSolrClient.class); + assertThat(this.context.getBean(SolrClient.class)).isInstanceOf(HttpSolrClient.class); } @Test public void testNoRepositoryConfiguration() { initContext(EmptyConfiguration.class); - assertThat(this.context.getBean(SolrClient.class)) - .isInstanceOf(HttpSolrClient.class); + assertThat(this.context.getBean(SolrClient.class)).isInstanceOf(HttpSolrClient.class); } @Test @@ -82,8 +80,7 @@ public class SolrRepositoriesAutoConfigurationTests { private void initContext(Class configClass) { this.context = new AnnotationConfigApplicationContext(); - this.context.register(configClass, SolrAutoConfiguration.class, - SolrRepositoriesAutoConfiguration.class, + this.context.register(configClass, SolrAutoConfiguration.class, SolrRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java index 0e3ec05ec92..f7f68b051ba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java @@ -37,87 +37,67 @@ import static org.assertj.core.api.Assertions.assertThat; public class SpringDataWebAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); @Test public void webSupportIsAutoConfiguredInWebApplicationContexts() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(PageableHandlerMethodArgumentResolver.class)); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class)); } @Test public void autoConfigurationBacksOffInNonWebApplicationContexts() { - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(SpringDataWebAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); + new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); } @Test public void customizePageable() { - this.contextRunner - .withPropertyValues("spring.data.web.pageable.page-parameter=p", - "spring.data.web.pageable.size-parameter=s", - "spring.data.web.pageable.default-page-size=10", - "spring.data.web.pageable.prefix=abc", - "spring.data.web.pageable.qualifier-delimiter=__", - "spring.data.web.pageable.max-page-size=100", - "spring.data.web.pageable.one-indexed-parameters=true") + this.contextRunner.withPropertyValues("spring.data.web.pageable.page-parameter=p", + "spring.data.web.pageable.size-parameter=s", "spring.data.web.pageable.default-page-size=10", + "spring.data.web.pageable.prefix=abc", "spring.data.web.pageable.qualifier-delimiter=__", + "spring.data.web.pageable.max-page-size=100", "spring.data.web.pageable.one-indexed-parameters=true") .run((context) -> { PageableHandlerMethodArgumentResolver argumentResolver = context .getBean(PageableHandlerMethodArgumentResolver.class); - assertThat(argumentResolver) - .hasFieldOrPropertyWithValue("pageParameterName", "p"); - assertThat(argumentResolver) - .hasFieldOrPropertyWithValue("sizeParameterName", "s"); - assertThat(argumentResolver) - .hasFieldOrPropertyWithValue("oneIndexedParameters", true); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", - "abc"); - assertThat(argumentResolver) - .hasFieldOrPropertyWithValue("qualifierDelimiter", "__"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue( - "fallbackPageable", PageRequest.of(0, 10)); - assertThat(argumentResolver) - .hasFieldOrPropertyWithValue("maxPageSize", 100); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", "p"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", "s"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("oneIndexedParameters", true); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", "abc"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("qualifierDelimiter", "__"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("fallbackPageable", PageRequest.of(0, 10)); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", 100); }); } @Test public void defaultPageable() { this.contextRunner.run((context) -> { - SpringDataWebProperties.Pageable properties = new SpringDataWebProperties() - .getPageable(); + SpringDataWebProperties.Pageable properties = new SpringDataWebProperties().getPageable(); PageableHandlerMethodArgumentResolver argumentResolver = context .getBean(PageableHandlerMethodArgumentResolver.class); assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", properties.getPageParameter()); assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", properties.getSizeParameter()); - assertThat(argumentResolver).hasFieldOrPropertyWithValue( - "oneIndexedParameters", properties.isOneIndexedParameters()); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", - properties.getPrefix()); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("oneIndexedParameters", + properties.isOneIndexedParameters()); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", properties.getPrefix()); assertThat(argumentResolver).hasFieldOrPropertyWithValue("qualifierDelimiter", properties.getQualifierDelimiter()); assertThat(argumentResolver).hasFieldOrPropertyWithValue("fallbackPageable", PageRequest.of(0, properties.getDefaultPageSize())); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", - properties.getMaxPageSize()); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", properties.getMaxPageSize()); }); } @Test public void customizeSort() { - this.contextRunner.withPropertyValues("spring.data.web.sort.sort-parameter=s") - .run((context) -> { - SortHandlerMethodArgumentResolver argumentResolver = context - .getBean(SortHandlerMethodArgumentResolver.class); - assertThat(argumentResolver) - .hasFieldOrPropertyWithValue("sortParameter", "s"); - }); + this.contextRunner.withPropertyValues("spring.data.web.sort.sort-parameter=s").run((context) -> { + SortHandlerMethodArgumentResolver argumentResolver = context + .getBean(SortHandlerMethodArgumentResolver.class); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("sortParameter", "s"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java index dd25eab9671..bd8065cf02c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java @@ -53,56 +53,45 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { @Test public void failureAnalysisForMultipleBeans() { - FailureAnalysis analysis = analyzeFailure( - new NoUniqueBeanDefinitionException(String.class, 2, "Test")); + FailureAnalysis analysis = analyzeFailure(new NoUniqueBeanDefinitionException(String.class, 2, "Test")); assertThat(analysis).isNull(); } @Test public void failureAnalysisForNoMatchType() { FailureAnalysis analysis = analyzeFailure(createFailure(StringHandler.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertThat(analysis.getDescription()).doesNotContain( - "No matching auto-configuration has been found for this type."); - assertThat(analysis.getAction()).startsWith(String.format( - "Consider defining a bean of type '%s' in your configuration.", - String.class.getName())); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertThat(analysis.getDescription()) + .doesNotContain("No matching auto-configuration has been found for this type."); + assertThat(analysis.getAction()).startsWith( + String.format("Consider defining a bean of type '%s' in your configuration.", String.class.getName())); } @Test public void failureAnalysisForMissingPropertyExactType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringPropertyTypeConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(StringPropertyTypeConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForMissingPropertySubType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(IntegerPropertyTypeConfiguration.class)); + FailureAnalysis analysis = analyzeFailure(createFailure(IntegerPropertyTypeConfiguration.class)); assertThat(analysis).isNotNull(); - assertDescriptionConstructorMissingType(analysis, NumberHandler.class, 0, - Number.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.integer.enabled'", + assertDescriptionConstructorMissingType(analysis, NumberHandler.class, 0, Number.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.integer.enabled'", TestPropertyAutoConfiguration.class, "integer"); assertActionMissingType(analysis, Number.class); } @Test public void failureAnalysisForMissingClassOnAutoConfigurationType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(MissingClassOnAutoConfigurationConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", - "string", ClassUtils.getShortName(TestTypeClassAutoConfiguration.class)); + FailureAnalysis analysis = analyzeFailure(createFailure(MissingClassOnAutoConfigurationConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", "string", + ClassUtils.getShortName(TestTypeClassAutoConfiguration.class)); assertActionMissingType(analysis, String.class); } @@ -111,48 +100,40 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { FatalBeanException failure = createFailure(StringHandler.class); addExclusions(this.analyzer, TestPropertyAutoConfiguration.class); FailureAnalysis analysis = analyzeFailure(failure); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - String configClass = ClassUtils - .getShortName(TestPropertyAutoConfiguration.class.getName()); - assertClassDisabled(analysis, - String.format("auto-configuration '%s' was excluded", configClass), - "string", ClassUtils.getShortName(TestPropertyAutoConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + String configClass = ClassUtils.getShortName(TestPropertyAutoConfiguration.class.getName()); + assertClassDisabled(analysis, String.format("auto-configuration '%s' was excluded", configClass), "string", + ClassUtils.getShortName(TestPropertyAutoConfiguration.class)); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForSeveralConditionsType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(SeveralAutoConfigurationTypeConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(SeveralAutoConfigurationTypeConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); - assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", - "string", ClassUtils.getShortName(TestPropertyAutoConfiguration.class)); + assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", "string", + ClassUtils.getShortName(TestPropertyAutoConfiguration.class)); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForNoMatchName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringNameHandler.class)); - assertThat(analysis.getDescription()).startsWith(String.format( - "Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); - assertThat(analysis.getAction()).startsWith(String.format( - "Consider defining a bean named '%s' in your configuration.", - "test-string")); + assertThat(analysis.getDescription()) + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); + assertThat(analysis.getAction()) + .startsWith(String.format("Consider defining a bean named '%s' in your configuration.", "test-string")); } @Test public void failureAnalysisForMissingBeanName() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringMissingBeanNameConfiguration.class)); - assertThat(analysis.getDescription()).startsWith(String.format( - "Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); + FailureAnalysis analysis = analyzeFailure(createFailure(StringMissingBeanNameConfiguration.class)); + assertThat(analysis.getDescription()) + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); assertBeanMethodDisabled(analysis, "@ConditionalOnBean (types: java.lang.Integer; SearchStrategy: all) did not find any beans", TestMissingBeanAutoConfiguration.class, "string"); @@ -161,74 +142,64 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { @Test public void failureAnalysisForNullBeanByType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringNullBeanConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertUserDefinedBean(analysis, "as the bean value is null", - TestNullBeanConfiguration.class, "string"); + FailureAnalysis analysis = analyzeFailure(createFailure(StringNullBeanConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertUserDefinedBean(analysis, "as the bean value is null", TestNullBeanConfiguration.class, "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForUnmatchedQualifier() { - FailureAnalysis analysis = analyzeFailure( - createFailure(QualifiedBeanConfiguration.class)); - assertThat(analysis.getDescription()).containsPattern( - "@org.springframework.beans.factory.annotation.Qualifier\\(value=\"*alpha\"*\\)"); + FailureAnalysis analysis = analyzeFailure(createFailure(QualifiedBeanConfiguration.class)); + assertThat(analysis.getDescription()) + .containsPattern("@org.springframework.beans.factory.annotation.Qualifier\\(value=\"*alpha\"*\\)"); } - private void assertDescriptionConstructorMissingType(FailureAnalysis analysis, - Class component, int index, Class type) { + private void assertDescriptionConstructorMissingType(FailureAnalysis analysis, Class component, int index, + Class type) { String expected = String.format( - "Parameter %s of constructor in %s required a bean of " - + "type '%s' that could not be found.", - index, component.getName(), type.getName()); + "Parameter %s of constructor in %s required a bean of " + "type '%s' that could not be found.", index, + component.getName(), type.getName()); assertThat(analysis.getDescription()).startsWith(expected); } private void assertActionMissingType(FailureAnalysis analysis, Class type) { assertThat(analysis.getAction()).startsWith(String.format( - "Consider revisiting the entries above or defining a bean of type '%s' " - + "in your configuration.", + "Consider revisiting the entries above or defining a bean of type '%s' " + "in your configuration.", type.getName())); } private void assertActionMissingName(FailureAnalysis analysis, String name) { assertThat(analysis.getAction()).startsWith(String.format( - "Consider revisiting the entries above or defining a bean named '%s' " - + "in your configuration.", + "Consider revisiting the entries above or defining a bean named '%s' " + "in your configuration.", name)); } - private void assertBeanMethodDisabled(FailureAnalysis analysis, String description, - Class target, String methodName) { - String expected = String.format("Bean method '%s' in '%s' not loaded because", - methodName, ClassUtils.getShortName(target)); + private void assertBeanMethodDisabled(FailureAnalysis analysis, String description, Class target, + String methodName) { + String expected = String.format("Bean method '%s' in '%s' not loaded because", methodName, + ClassUtils.getShortName(target)); assertThat(analysis.getDescription()).contains(expected); assertThat(analysis.getDescription()).contains(description); } - private void assertClassDisabled(FailureAnalysis analysis, String description, - String methodName, String className) { - String expected = String.format("Bean method '%s' in '%s' not loaded because", - methodName, className); + private void assertClassDisabled(FailureAnalysis analysis, String description, String methodName, + String className) { + String expected = String.format("Bean method '%s' in '%s' not loaded because", methodName, className); assertThat(analysis.getDescription()).contains(expected); assertThat(analysis.getDescription()).contains(description); } - private void assertUserDefinedBean(FailureAnalysis analysis, String description, - Class target, String methodName) { - String expected = String.format("User-defined bean method '%s' in '%s' ignored", - methodName, ClassUtils.getShortName(target)); + private void assertUserDefinedBean(FailureAnalysis analysis, String description, Class target, + String methodName) { + String expected = String.format("User-defined bean method '%s' in '%s' ignored", methodName, + ClassUtils.getShortName(target)); assertThat(analysis.getDescription()).contains(expected); assertThat(analysis.getDescription()).contains(description); } - private static void addExclusions(NoSuchBeanDefinitionFailureAnalyzer analyzer, - Class... classes) { - ConditionEvaluationReport report = (ConditionEvaluationReport) ReflectionTestUtils - .getField(analyzer, "report"); + private static void addExclusions(NoSuchBeanDefinitionFailureAnalyzer analyzer, Class... classes) { + ConditionEvaluationReport report = (ConditionEvaluationReport) ReflectionTestUtils.getField(analyzer, "report"); List exclusions = new ArrayList<>(report.getExclusions()); for (Class c : classes) { exclusions.add(c.getName()); @@ -279,8 +250,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ TestPropertyAutoConfiguration.class, - TestTypeClassAutoConfiguration.class }) + @ImportAutoConfiguration({ TestPropertyAutoConfiguration.class, TestTypeClassAutoConfiguration.class }) @Import(StringHandler.class) protected static class SeveralAutoConfigurationTypeConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java index a0314c3ec7a..fde2d791450 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java @@ -68,8 +68,7 @@ public class EntityScanPackagesTests { @Test public void registerFromArrayWhenRegistryIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(null)) + assertThatIllegalArgumentException().isThrownBy(() -> EntityScanPackages.register(null)) .withMessageContaining("Registry must not be null"); } @@ -78,16 +77,14 @@ public class EntityScanPackagesTests { public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() - .isThrownBy( - () -> EntityScanPackages.register(this.context, (String[]) null)) + .isThrownBy(() -> EntityScanPackages.register(this.context, (String[]) null)) .withMessageContaining("PackageNames must not be null"); } @Test public void registerFromCollectionWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> EntityScanPackages.register(null, Collections.emptyList())) + .isThrownBy(() -> EntityScanPackages.register(null, Collections.emptyList())) .withMessageContaining("Registry must not be null"); } @@ -95,15 +92,13 @@ public class EntityScanPackagesTests { public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(this.context, - (Collection) null)) + .isThrownBy(() -> EntityScanPackages.register(this.context, (Collection) null)) .withMessageContaining("PackageNames must not be null"); } @Test public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackages() { - this.context = new AnnotationConfigApplicationContext( - EntityScanValueConfig.class); + this.context = new AnnotationConfigApplicationContext(EntityScanValueConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly("a"); } @@ -120,8 +115,7 @@ public class EntityScanPackagesTests { @Test public void entityScanAnnotationWhenHasBasePackagesAttributeShouldSetupPackages() { - this.context = new AnnotationConfigApplicationContext( - EntityScanBasePackagesConfig.class); + this.context = new AnnotationConfigApplicationContext(EntityScanBasePackagesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly("b"); } @@ -135,20 +129,16 @@ public class EntityScanPackagesTests { @Test public void entityScanAnnotationWhenHasBasePackageClassesAttributeShouldSetupPackages() { - this.context = new AnnotationConfigApplicationContext( - EntityScanBasePackageClassesConfig.class); + this.context = new AnnotationConfigApplicationContext(EntityScanBasePackageClassesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); - assertThat(packages.getPackageNames()) - .containsExactly(getClass().getPackage().getName()); + assertThat(packages.getPackageNames()).containsExactly(getClass().getPackage().getName()); } @Test public void entityScanAnnotationWhenNoAttributesShouldSetupPackages() { - this.context = new AnnotationConfigApplicationContext( - EntityScanNoAttributesConfig.class); + this.context = new AnnotationConfigApplicationContext(EntityScanNoAttributesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); - assertThat(packages.getPackageNames()) - .containsExactly(getClass().getPackage().getName()); + assertThat(packages.getPackageNames()).containsExactly(getClass().getPackage().getName()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java index c187b7c293e..98c97559082 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java @@ -50,8 +50,7 @@ public class EntityScannerTests { @Test public void scanShouldScanFromSinglePackage() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ScanConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); EntityScanner scanner = new EntityScanner(context); Set> scanned = scanner.scan(Entity.class); assertThat(scanned).containsOnly(EntityA.class, EntityB.class, EntityC.class); @@ -60,8 +59,8 @@ public class EntityScannerTests { @Test public void scanShouldScanFromMultiplePackages() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ScanAConfig.class, ScanBConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanAConfig.class, + ScanBConfig.class); EntityScanner scanner = new EntityScanner(context); Set> scanned = scanner.scan(Entity.class); assertThat(scanned).containsOnly(EntityA.class, EntityB.class); @@ -70,16 +69,13 @@ public class EntityScannerTests { @Test public void scanShouldFilterOnAnnotation() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ScanConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); EntityScanner scanner = new EntityScanner(context); - assertThat(scanner.scan(Entity.class)).containsOnly(EntityA.class, EntityB.class, - EntityC.class); - assertThat(scanner.scan(Embeddable.class)).containsOnly(EmbeddableA.class, - EmbeddableB.class, EmbeddableC.class); - assertThat(scanner.scan(Entity.class, Embeddable.class)).containsOnly( - EntityA.class, EntityB.class, EntityC.class, EmbeddableA.class, - EmbeddableB.class, EmbeddableC.class); + assertThat(scanner.scan(Entity.class)).containsOnly(EntityA.class, EntityB.class, EntityC.class); + assertThat(scanner.scan(Embeddable.class)).containsOnly(EmbeddableA.class, EmbeddableB.class, + EmbeddableC.class); + assertThat(scanner.scan(Entity.class, Embeddable.class)).containsOnly(EntityA.class, EntityB.class, + EntityC.class, EmbeddableA.class, EmbeddableB.class, EmbeddableC.class); context.close(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java index 388f59ae62e..28d114088d6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java @@ -57,31 +57,25 @@ public class JestAutoConfigurationTests { public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, - JestAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, JestAutoConfiguration.class)); @Test public void jestClientOnLocalhostByDefault() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(JestClient.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JestClient.class)); } @Test public void customJestClient() { this.contextRunner.withUserConfiguration(CustomJestClient.class) - .withPropertyValues( - "spring.elasticsearch.jest.uris[0]=http://localhost:9200") + .withPropertyValues("spring.elasticsearch.jest.uris[0]=http://localhost:9200") .run((context) -> assertThat(context).hasSingleBean(JestClient.class)); } @Test public void customGson() { this.contextRunner.withUserConfiguration(CustomGson.class) - .withPropertyValues( - "spring.elasticsearch.jest.uris=http://localhost:9200") - .run((context) -> { - JestHttpClient client = (JestHttpClient) context - .getBean(JestClient.class); + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200").run((context) -> { + JestHttpClient client = (JestHttpClient) context.getBean(JestClient.class); assertThat(client.getGson()).isSameAs(context.getBean("customGson")); }); } @@ -89,43 +83,34 @@ public class JestAutoConfigurationTests { @Test public void customizerOverridesAutoConfig() { this.contextRunner.withUserConfiguration(BuilderCustomizer.class) - .withPropertyValues( - "spring.elasticsearch.jest.uris=http://localhost:9200") - .run((context) -> { - JestHttpClient client = (JestHttpClient) context - .getBean(JestClient.class); - assertThat(client.getGson()) - .isSameAs(context.getBean(BuilderCustomizer.class).getGson()); + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200").run((context) -> { + JestHttpClient client = (JestHttpClient) context.getBean(JestClient.class); + assertThat(client.getGson()).isSameAs(context.getBean(BuilderCustomizer.class).getGson()); }); } @Test public void proxyHostWithoutPort() { this.contextRunner - .withPropertyValues( - "spring.elasticsearch.jest.uris=http://localhost:9200", + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200", "spring.elasticsearch.jest.proxy.host=proxy.example.com") - .run((context) -> assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class) + .run((context) -> assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) .hasMessageContaining("Proxy port must not be null")); } @Test public void jestCanCommunicateWithElasticsearchInstance() { this.contextRunner - .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:" - + elasticsearch.getMappedPort()) + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:" + elasticsearch.getMappedPort()) .run((context) -> { JestClient client = context.getBean(JestClient.class); Map source = new HashMap<>(); source.put("a", "alpha"); source.put("b", "bravo"); - Index index = new Index.Builder(source).index("foo").type("bar") - .id("1").build(); + Index index = new Index.Builder(source).index("foo").type("bar").id("1").build(); execute(client, index); Get getRequest = new Get.Builder("foo", "1").build(); - assertThat(execute(client, getRequest).getResponseCode()) - .isEqualTo(200); + assertThat(execute(client, getRequest).getResponseCode()).isEqualTo(200); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java index ba18393fb3a..e5c2b1dc77d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java @@ -56,27 +56,23 @@ public class RestClientAutoConfigurationTests { @Test public void configureShouldCreateBothRestClientVariants() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(RestClient.class) - .hasSingleBean(RestHighLevelClient.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RestClient.class) + .hasSingleBean(RestHighLevelClient.class)); } @Test public void configureWhenCustomClientShouldBackOff() { this.contextRunner.withUserConfiguration(CustomRestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(RestClient.class) - .hasBean("customRestClient")); + .run((context) -> assertThat(context).hasSingleBean(RestClient.class).hasBean("customRestClient")); } @Test public void configureWhenBuilderCustomizerShouldApply() { - this.contextRunner.withUserConfiguration(BuilderCustomizerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(RestClient.class); - RestClient restClient = context.getBean(RestClient.class); - assertThat(restClient).hasFieldOrPropertyWithValue("pathPrefix", - "/test"); - }); + this.contextRunner.withUserConfiguration(BuilderCustomizerConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(RestClient.class); + RestClient restClient = context.getBean(RestClient.class); + assertThat(restClient).hasFieldOrPropertyWithValue("pathPrefix", "/test"); + }); } @Test @@ -84,52 +80,40 @@ public class RestClientAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(RestClient.class); RestClient restClient = context.getBean(RestClient.class); - assertTimeouts(restClient, - Duration.ofMillis(RestClientBuilder.DEFAULT_CONNECT_TIMEOUT_MILLIS), + assertTimeouts(restClient, Duration.ofMillis(RestClientBuilder.DEFAULT_CONNECT_TIMEOUT_MILLIS), Duration.ofMillis(RestClientBuilder.DEFAULT_SOCKET_TIMEOUT_MILLIS)); }); } @Test public void configureWithCustomTimeouts() { - this.contextRunner - .withPropertyValues("spring.elasticsearch.rest.connection-timeout=15s", - "spring.elasticsearch.rest.read-timeout=1m") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.elasticsearch.rest.connection-timeout=15s", + "spring.elasticsearch.rest.read-timeout=1m").run((context) -> { assertThat(context).hasSingleBean(RestClient.class); RestClient restClient = context.getBean(RestClient.class); - assertTimeouts(restClient, Duration.ofSeconds(15), - Duration.ofMinutes(1)); + assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); }); } - private static void assertTimeouts(RestClient restClient, Duration connectTimeout, - Duration readTimeout) { + private static void assertTimeouts(RestClient restClient, Duration connectTimeout, Duration readTimeout) { Object client = ReflectionTestUtils.getField(restClient, "client"); Object config = ReflectionTestUtils.getField(client, "defaultConfig"); - assertThat(config).hasFieldOrPropertyWithValue("socketTimeout", - Math.toIntExact(readTimeout.toMillis())); - assertThat(config).hasFieldOrPropertyWithValue("connectTimeout", - Math.toIntExact(connectTimeout.toMillis())); + assertThat(config).hasFieldOrPropertyWithValue("socketTimeout", Math.toIntExact(readTimeout.toMillis())); + assertThat(config).hasFieldOrPropertyWithValue("connectTimeout", Math.toIntExact(connectTimeout.toMillis())); } @Test public void restClientCanQueryElasticsearchNode() { - this.contextRunner - .withPropertyValues("spring.elasticsearch.rest.uris=http://localhost:" - + RestClientAutoConfigurationTests.elasticsearch.getMappedPort()) - .run((context) -> { - RestHighLevelClient client = context - .getBean(RestHighLevelClient.class); + this.contextRunner.withPropertyValues("spring.elasticsearch.rest.uris=http://localhost:" + + RestClientAutoConfigurationTests.elasticsearch.getMappedPort()).run((context) -> { + RestHighLevelClient client = context.getBean(RestHighLevelClient.class); Map source = new HashMap<>(); source.put("a", "alpha"); source.put("b", "bravo"); - IndexRequest index = new IndexRequest("foo", "bar", "1") - .source(source); + IndexRequest index = new IndexRequest("foo", "bar", "1").source(source); client.index(index, RequestOptions.DEFAULT); GetRequest getRequest = new GetRequest("foo", "bar", "1"); - assertThat(client.get(getRequest, RequestOptions.DEFAULT).isExists()) - .isTrue(); + assertThat(client.get(getRequest, RequestOptions.DEFAULT).isExists()).isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java index 2140ee6cdca..8692d614313 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java @@ -80,15 +80,12 @@ public class FlywayAutoConfigurationTests { @Test public void backsOffWithNoDataSourceBeanAndNoFlywayUrl() { - this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); } @Test public void createsDataSourceWithNoDataSourceBeanAndFlywayUrl() { - this.contextRunner - .withPropertyValues( - "spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) + this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getDataSource()).isNotNull(); @@ -98,8 +95,7 @@ public class FlywayAutoConfigurationTests { @Test public void createDataSourceWithUrl() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest") - .run((context) -> { + .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getDataSource()).isNotNull(); }); @@ -108,8 +104,7 @@ public class FlywayAutoConfigurationTests { @Test public void createDataSourceWithUser() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), "spring.flyway.user:sa") .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -119,8 +114,9 @@ public class FlywayAutoConfigurationTests { @Test public void flywayDataSource() { - this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class, - EmbeddedDataSourceConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getDataSource()) .isEqualTo(context.getBean("flywayDataSource")); @@ -129,50 +125,44 @@ public class FlywayAutoConfigurationTests { @Test public void flywayDataSourceWithoutDataSourceAutoConfiguration() { - this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); - }); + this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getDataSource()).isEqualTo(context.getBean("flywayDataSource")); + }); } @Test public void schemaManagementProviderDetectsDataSource() { - this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class, - EmbeddedDataSourceConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { FlywaySchemaManagementProvider schemaManagementProvider = context .getBean(FlywaySchemaManagementProvider.class); + assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(DataSource.class))) + .isEqualTo(SchemaManagement.UNMANAGED); assertThat(schemaManagementProvider - .getSchemaManagement(context.getBean(DataSource.class))) - .isEqualTo(SchemaManagement.UNMANAGED); - assertThat(schemaManagementProvider.getSchemaManagement( - context.getBean("flywayDataSource", DataSource.class))) + .getSchemaManagement(context.getBean("flywayDataSource", DataSource.class))) .isEqualTo(SchemaManagement.MANAGED); }); } @Test public void defaultFlyway() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getLocations()) - .containsExactly(new Location("classpath:db/migration")); - }); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getLocations()).containsExactly(new Location("classpath:db/migration")); + }); } @Test public void overrideLocations() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.flyway.locations:classpath:db/changelog,classpath:db/migration") + .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactly( - new Location("classpath:db/changelog"), + assertThat(flyway.getLocations()).containsExactly(new Location("classpath:db/changelog"), new Location("classpath:db/migration")); }); } @@ -185,8 +175,7 @@ public class FlywayAutoConfigurationTests { .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactly( - new Location("classpath:db/changelog"), + assertThat(flyway.getLocations()).containsExactly(new Location("classpath:db/changelog"), new Location("classpath:db/migration")); }); } @@ -197,41 +186,34 @@ public class FlywayAutoConfigurationTests { .withPropertyValues("spring.flyway.schemas:public").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(Arrays.asList(flyway.getSchemas()).toString()) - .isEqualTo("[public]"); + assertThat(Arrays.asList(flyway.getSchemas()).toString()).isEqualTo("[public]"); }); } @Test public void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations:filesystem:no-such-dir") - .run((context) -> { + .withPropertyValues("spring.flyway.locations:filesystem:no-such-dir").run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); }); } @Test public void checkLocationsAllMissing() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") + .withPropertyValues("spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") .run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class); - assertThat(context).getFailure() - .hasMessageContaining("Cannot find migration scripts in"); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + assertThat(context).getFailure().hasMessageContaining("Cannot find migration scripts in"); }); } @Test public void checkLocationsAllExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.flyway.locations:classpath:db/changelog,classpath:db/migration") + .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") .run((context) -> assertThat(context).hasNotFailed()); } @@ -245,15 +227,15 @@ public class FlywayAutoConfigurationTests { @Test public void checkLocationsAllExistWithFilesystemPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.flyway.locations:filesystem:src/test/resources/db/migration") + .withPropertyValues("spring.flyway.locations:filesystem:src/test/resources/db/migration") .run((context) -> assertThat(context).hasNotFailed()); } @Test public void customFlywayMigrationStrategy() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - MockFlywayMigrationStrategy.class).run((context) -> { + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MockFlywayMigrationStrategy.class) + .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); }); @@ -261,21 +243,19 @@ public class FlywayAutoConfigurationTests { @Test public void customFlywayMigrationInitializer() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CustomFlywayMigrationInitializer.class).run((context) -> { + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) + .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); - FlywayMigrationInitializer initializer = context - .getBean(FlywayMigrationInitializer.class); - assertThat(initializer.getOrder()) - .isEqualTo(Ordered.HIGHEST_PRECEDENCE); + FlywayMigrationInitializer initializer = context.getBean(FlywayMigrationInitializer.class); + assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); }); } @Test public void customFlywayWithJpa() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CustomFlywayWithJpaConfiguration.class) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJpaConfiguration.class) .run((context) -> assertThat(context).hasNotFailed()); } @@ -285,8 +265,7 @@ public class FlywayAutoConfigurationTests { .withPropertyValues("spring.flyway.baseline-version=0").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("0")); + assertThat(flyway.getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("0")); }); } @@ -296,21 +275,18 @@ public class FlywayAutoConfigurationTests { .withPropertyValues("spring.flyway.baseline-version=1").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("1")); + assertThat(flyway.getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("1")); }); } @Test public void useVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") + .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactlyInAnyOrder( - new Location("classpath:db/vendors/h2"), + assertThat(flyway.getLocations()).containsExactlyInAnyOrder(new Location("classpath:db/vendors/h2"), new Location("classpath:db/changelog")); }); } @@ -318,63 +294,52 @@ public class FlywayAutoConfigurationTests { @Test public void useOneLocationWithVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.flyway.locations=classpath:db/vendors/{vendor}") - .run((context) -> { + .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor}").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getLocations()) - .containsExactly(new Location("classpath:db/vendors/h2")); + assertThat(flyway.getLocations()).containsExactly(new Location("classpath:db/vendors/h2")); }); } @Test public void callbacksAreConfiguredAndOrdered() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CallbackConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, CallbackConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); Callback callbackOne = context.getBean("callbackOne", Callback.class); Callback callbackTwo = context.getBean("callbackTwo", Callback.class); assertThat(flyway.getCallbacks()).hasSize(2); - assertThat(flyway.getCallbacks()).containsExactly(callbackTwo, - callbackOne); + assertThat(flyway.getCallbacks()).containsExactly(callbackTwo, callbackOne); InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); - orderedCallbacks.verify(callbackTwo).handle(any(Event.class), - any(Context.class)); - orderedCallbacks.verify(callbackOne).handle(any(Event.class), - any(Context.class)); + orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); + orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); }); } @Test public void legacyCallbacksAreConfiguredAndOrdered() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - LegacyCallbackConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, LegacyCallbackConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - FlywayCallback callbackOne = context.getBean("legacyCallbackOne", - FlywayCallback.class); - FlywayCallback callbackTwo = context.getBean("legacyCallbackTwo", - FlywayCallback.class); + FlywayCallback callbackOne = context.getBean("legacyCallbackOne", FlywayCallback.class); + FlywayCallback callbackTwo = context.getBean("legacyCallbackTwo", FlywayCallback.class); assertThat(flyway.getCallbacks()).hasSize(2); InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); - orderedCallbacks.verify(callbackTwo) - .beforeMigrate(any(Connection.class)); - orderedCallbacks.verify(callbackOne) - .beforeMigrate(any(Connection.class)); + orderedCallbacks.verify(callbackTwo).beforeMigrate(any(Connection.class)); + orderedCallbacks.verify(callbackOne).beforeMigrate(any(Connection.class)); }); } @Test public void callbacksAndLegacyCallbacksCannotBeMixed() { - this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - LegacyCallbackConfiguration.class, CallbackConfiguration.class) - .run((context) -> { + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + LegacyCallbackConfiguration.class, CallbackConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasMessageContaining( - "Found a mixture of Callback and FlywayCallback beans." + assertThat(context.getStartupFailure()) + .hasMessageContaining("Found a mixture of Callback and FlywayCallback beans." + " One type must be used exclusively."); }); } @@ -385,12 +350,9 @@ public class FlywayAutoConfigurationTests { ConfigurationCustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getConnectRetries()) - .isEqualTo(5); - assertThat(flyway.getConfiguration().isIgnoreMissingMigrations()) - .isTrue(); - assertThat(flyway.getConfiguration().isIgnorePendingMigrations()) - .isTrue(); + assertThat(flyway.getConfiguration().getConnectRetries()).isEqualTo(5); + assertThat(flyway.getConfiguration().isIgnoreMissingMigrations()).isTrue(); + assertThat(flyway.getConfiguration().isIgnorePendingMigrations()).isTrue(); }); } @@ -400,8 +362,7 @@ public class FlywayAutoConfigurationTests { .withPropertyValues("spring.flyway.batch=true").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" batch "); }); } @@ -409,12 +370,10 @@ public class FlywayAutoConfigurationTests { @Test public void dryRunOutputIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql") - .run((context) -> { + .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" dryRunOutput "); }); } @@ -422,12 +381,10 @@ public class FlywayAutoConfigurationTests { @Test public void errorOverridesIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.errorOverrides=D12345") - .run((context) -> { + .withPropertyValues("spring.flyway.errorOverrides=D12345").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" errorOverrides "); }); } @@ -435,12 +392,10 @@ public class FlywayAutoConfigurationTests { @Test public void licenseKeyIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.license-key=<>") - .run((context) -> { + .withPropertyValues("spring.flyway.license-key=<>").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" licenseKey "); }); } @@ -448,12 +403,10 @@ public class FlywayAutoConfigurationTests { @Test public void oracleSqlplusIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus=true") - .run((context) -> { + .withPropertyValues("spring.flyway.oracle-sqlplus=true").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" oracle.sqlplus "); }); } @@ -464,8 +417,7 @@ public class FlywayAutoConfigurationTests { .withPropertyValues("spring.flyway.stream=true").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" stream "); }); } @@ -473,24 +425,22 @@ public class FlywayAutoConfigurationTests { @Test public void undoSqlMigrationPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo") - .run((context) -> { + .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo").run((context) -> { assertThat(context).hasFailed(); Throwable failure = context.getStartupFailure(); - assertThat(failure).hasRootCauseInstanceOf( - FlywayProUpgradeRequiredException.class); + assertThat(failure).hasRootCauseInstanceOf(FlywayProUpgradeRequiredException.class); assertThat(failure).hasMessageContaining(" undoSqlMigrationPrefix "); }); } @Test public void customFlywayClassLoader() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - ResourceLoaderConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ResourceLoaderConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getClassLoader()) - .isInstanceOf(CustomClassLoader.class); + assertThat(flyway.getConfiguration().getClassLoader()).isInstanceOf(CustomClassLoader.class); }); } @@ -500,15 +450,13 @@ public class FlywayAutoConfigurationTests { @Bean @Primary public DataSource normalDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa") - .build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa").build(); } @FlywayDataSource @Bean public DataSource flywayDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:flywaytest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:flywaytest").username("sa").build(); } } @@ -519,8 +467,7 @@ public class FlywayAutoConfigurationTests { @Bean @Primary public ResourceLoader customClassLoader() { - return new DefaultResourceLoader( - new CustomClassLoader(getClass().getClassLoader())); + return new DefaultResourceLoader(new CustomClassLoader(getClass().getClassLoader())); } } @@ -530,8 +477,7 @@ public class FlywayAutoConfigurationTests { @Bean public FlywayMigrationInitializer flywayMigrationInitializer(Flyway flyway) { - FlywayMigrationInitializer initializer = new FlywayMigrationInitializer( - flyway); + FlywayMigrationInitializer initializer = new FlywayMigrationInitializer(flyway); initializer.setOrder(Ordered.HIGHEST_PRECEDENCE); return initializer; } @@ -557,15 +503,14 @@ public class FlywayAutoConfigurationTests { Map properties = new HashMap<>(); properties.put("configured", "manually"); properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE); - return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), - properties, null).dataSource(this.dataSource).build(); + return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), properties, null) + .dataSource(this.dataSource).build(); } } @Component - protected static class MockFlywayMigrationStrategy - implements FlywayMigrationStrategy { + protected static class MockFlywayMigrationStrategy implements FlywayMigrationStrategy { private boolean called = false; @@ -597,8 +542,7 @@ public class FlywayAutoConfigurationTests { private Callback mockCallback() { Callback callback = mock(Callback.class); - given(callback.supports(any(Event.class), any(Context.class))) - .willReturn(true); + given(callback.supports(any(Event.class), any(Context.class))).willReturn(true); return callback; } @@ -627,15 +571,13 @@ public class FlywayAutoConfigurationTests { @Bean @Order(1) public FlywayConfigurationCustomizer customizerOne() { - return (configuration) -> configuration.connectRetries(5) - .ignorePendingMigrations(true); + return (configuration) -> configuration.connectRetries(5).ignorePendingMigrations(true); } @Bean @Order(0) public FlywayConfigurationCustomizer customizerTwo() { - return (configuration) -> configuration.connectRetries(10) - .ignoreMissingMigrations(true); + return (configuration) -> configuration.connectRetries(10).ignoreMissingMigrations(true); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java index 7e986697052..60b4355c038 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java @@ -34,20 +34,18 @@ public class FlywayMigrationScriptMissingFailureAnalyzerTests { @Test public void analysisForMissingScriptLocation() { FailureAnalysis failureAnalysis = performAnalysis(); - assertThat(failureAnalysis.getDescription()) - .contains("no migration scripts location is configured"); - assertThat(failureAnalysis.getAction()) - .contains("Check your Flyway configuration"); + assertThat(failureAnalysis.getDescription()).contains("no migration scripts location is configured"); + assertThat(failureAnalysis.getAction()).contains("Check your Flyway configuration"); } @Test public void analysisForScriptLocationsNotFound() { FailureAnalysis failureAnalysis = performAnalysis("classpath:db/migration"); - assertThat(failureAnalysis.getDescription()).contains( - "none of the following migration scripts locations could be found") + assertThat(failureAnalysis.getDescription()) + .contains("none of the following migration scripts locations could be found") .contains("classpath:db/migration"); - assertThat(failureAnalysis.getAction()).contains( - "Review the locations above or check your Flyway configuration"); + assertThat(failureAnalysis.getAction()) + .contains("Review the locations above or check your Flyway configuration"); } private FailureAnalysis performAnalysis(String... locations) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java index 8dbecb5d236..7dc9dbaf2ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java @@ -47,62 +47,43 @@ public class FlywayPropertiesTests { public void defaultValuesAreConsistent() { FlywayProperties properties = new FlywayProperties(); Configuration configuration = new FluentConfiguration(); - assertThat(properties.getLocations().stream().map(Location::new) - .toArray(Location[]::new)).isEqualTo(configuration.getLocations()); + assertThat(properties.getLocations().stream().map(Location::new).toArray(Location[]::new)) + .isEqualTo(configuration.getLocations()); assertThat(properties.getEncoding()).isEqualTo(configuration.getEncoding()); - assertThat(properties.getConnectRetries()) - .isEqualTo(configuration.getConnectRetries()); - assertThat(properties.getSchemas()) - .isEqualTo(Arrays.asList(configuration.getSchemas())); + assertThat(properties.getConnectRetries()).isEqualTo(configuration.getConnectRetries()); + assertThat(properties.getSchemas()).isEqualTo(Arrays.asList(configuration.getSchemas())); assertThat(properties.getTable()).isEqualTo(configuration.getTable()); - assertThat(properties.getBaselineDescription()) - .isEqualTo(configuration.getBaselineDescription()); + assertThat(properties.getBaselineDescription()).isEqualTo(configuration.getBaselineDescription()); assertThat(MigrationVersion.fromVersion(properties.getBaselineVersion())) .isEqualTo(configuration.getBaselineVersion()); assertThat(properties.getInstalledBy()).isEqualTo(configuration.getInstalledBy()); - assertThat(properties.getPlaceholders()) - .isEqualTo(configuration.getPlaceholders()); - assertThat(properties.getPlaceholderPrefix()) - .isEqualToIgnoringWhitespace(configuration.getPlaceholderPrefix()); - assertThat(properties.getPlaceholderSuffix()) - .isEqualTo(configuration.getPlaceholderSuffix()); - assertThat(properties.isPlaceholderReplacement()) - .isEqualTo(configuration.isPlaceholderReplacement()); - assertThat(properties.getSqlMigrationPrefix()) - .isEqualTo(configuration.getSqlMigrationPrefix()); + assertThat(properties.getPlaceholders()).isEqualTo(configuration.getPlaceholders()); + assertThat(properties.getPlaceholderPrefix()).isEqualToIgnoringWhitespace(configuration.getPlaceholderPrefix()); + assertThat(properties.getPlaceholderSuffix()).isEqualTo(configuration.getPlaceholderSuffix()); + assertThat(properties.isPlaceholderReplacement()).isEqualTo(configuration.isPlaceholderReplacement()); + assertThat(properties.getSqlMigrationPrefix()).isEqualTo(configuration.getSqlMigrationPrefix()); assertThat(properties.getSqlMigrationSuffixes()) .isEqualTo(Arrays.asList(configuration.getSqlMigrationSuffixes())); - assertThat(properties.getSqlMigrationSeparator()) - .isEqualTo(properties.getSqlMigrationSeparator()); + assertThat(properties.getSqlMigrationSeparator()).isEqualTo(properties.getSqlMigrationSeparator()); assertThat(properties.getRepeatableSqlMigrationPrefix()) .isEqualTo(properties.getRepeatableSqlMigrationPrefix()); assertThat(properties.getTarget()).isNull(); assertThat(configuration.getTarget()).isNull(); assertThat(configuration.getInitSql()).isNull(); assertThat(properties.getInitSqls()).isEmpty(); - assertThat(configuration.isBaselineOnMigrate()) - .isEqualTo(properties.isBaselineOnMigrate()); - assertThat(configuration.isCleanDisabled()) - .isEqualTo(properties.isCleanDisabled()); - assertThat(configuration.isCleanOnValidationError()) - .isEqualTo(properties.isCleanOnValidationError()); + assertThat(configuration.isBaselineOnMigrate()).isEqualTo(properties.isBaselineOnMigrate()); + assertThat(configuration.isCleanDisabled()).isEqualTo(properties.isCleanDisabled()); + assertThat(configuration.isCleanOnValidationError()).isEqualTo(properties.isCleanOnValidationError()); assertThat(configuration.isGroup()).isEqualTo(properties.isGroup()); - assertThat(configuration.isIgnoreMissingMigrations()) - .isEqualTo(properties.isIgnoreMissingMigrations()); - assertThat(configuration.isIgnoreIgnoredMigrations()) - .isEqualTo(properties.isIgnoreIgnoredMigrations()); - assertThat(configuration.isIgnorePendingMigrations()) - .isEqualTo(properties.isIgnorePendingMigrations()); - assertThat(configuration.isIgnoreFutureMigrations()) - .isEqualTo(properties.isIgnoreFutureMigrations()); + assertThat(configuration.isIgnoreMissingMigrations()).isEqualTo(properties.isIgnoreMissingMigrations()); + assertThat(configuration.isIgnoreIgnoredMigrations()).isEqualTo(properties.isIgnoreIgnoredMigrations()); + assertThat(configuration.isIgnorePendingMigrations()).isEqualTo(properties.isIgnorePendingMigrations()); + assertThat(configuration.isIgnoreFutureMigrations()).isEqualTo(properties.isIgnoreFutureMigrations()); assertThat(configuration.isMixed()).isEqualTo(properties.isMixed()); assertThat(configuration.isOutOfOrder()).isEqualTo(properties.isOutOfOrder()); - assertThat(configuration.isSkipDefaultCallbacks()) - .isEqualTo(properties.isSkipDefaultCallbacks()); - assertThat(configuration.isSkipDefaultResolvers()) - .isEqualTo(properties.isSkipDefaultResolvers()); - assertThat(configuration.isValidateOnMigrate()) - .isEqualTo(properties.isValidateOnMigrate()); + assertThat(configuration.isSkipDefaultCallbacks()).isEqualTo(properties.isSkipDefaultCallbacks()); + assertThat(configuration.isSkipDefaultResolvers()).isEqualTo(properties.isSkipDefaultResolvers()); + assertThat(configuration.isValidateOnMigrate()).isEqualTo(properties.isValidateOnMigrate()); } @Test @@ -110,20 +91,17 @@ public class FlywayPropertiesTests { Map properties = indexProperties( PropertyAccessorFactory.forBeanPropertyAccess(new FlywayProperties())); Map configuration = indexProperties( - PropertyAccessorFactory - .forBeanPropertyAccess(new ClassicConfiguration())); + PropertyAccessorFactory.forBeanPropertyAccess(new ClassicConfiguration())); // Properties specific settings - ignoreProperties(properties, "url", "user", "password", "enabled", - "checkLocation", "createDataSource"); + ignoreProperties(properties, "url", "user", "password", "enabled", "checkLocation", "createDataSource"); // High level object we can't set with properties - ignoreProperties(configuration, "classLoader", "dataSource", "resolvers", - "callbacks"); + ignoreProperties(configuration, "classLoader", "dataSource", "resolvers", "callbacks"); // Properties we don't want to expose ignoreProperties(configuration, "resolversAsClassNames", "callbacksAsClassNames"); // Handled by the conversion service - ignoreProperties(configuration, "baselineVersionAsString", "encodingAsString", - "locationsAsStrings", "targetAsString"); + ignoreProperties(configuration, "baselineVersionAsString", "encodingAsString", "locationsAsStrings", + "targetAsString"); // Handled as initSql array ignoreProperties(configuration, "initSql"); ignoreProperties(properties, "initSqls"); @@ -140,16 +118,14 @@ public class FlywayPropertiesTests { private void ignoreProperties(Map index, String... propertyNames) { for (String propertyName : propertyNames) { - assertThat(index.remove(propertyName)) - .describedAs("Property to ignore should be present " + propertyName) + assertThat(index.remove(propertyName)).describedAs("Property to ignore should be present " + propertyName) .isNotNull(); } } private Map indexProperties(BeanWrapper beanWrapper) { Map descriptor = new HashMap<>(); - for (PropertyDescriptor propertyDescriptor : beanWrapper - .getPropertyDescriptors()) { + for (PropertyDescriptor propertyDescriptor : beanWrapper.getPropertyDescriptors()) { descriptor.put(propertyDescriptor.getName(), propertyDescriptor); } ignoreProperties(descriptor, "class"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java index 4769bd6f447..7c06e332baf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java @@ -52,8 +52,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { assertThat(context.getBean(FreeMarkerViewResolver.class)).isNotNull(); assertThat(context.getBean(FreeMarkerConfigurer.class)).isNotNull(); assertThat(context.getBean(FreeMarkerConfig.class)).isNotNull(); - assertThat(context.getBean(freemarker.template.Configuration.class)) - .isNotNull(); + assertThat(context.getBean(freemarker.template.Configuration.class)).isNotNull(); }); } @@ -61,44 +60,36 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { public void defaultViewResolution() { this.contextRunner.run((context) -> { MockServerWebExchange exchange = render(context, "home"); - String result = exchange.getResponse().getBodyAsString() - .block(Duration.ofSeconds(30)); + String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); assertThat(result).contains("home"); - assertThat(exchange.getResponse().getHeaders().getContentType()) - .isEqualTo(MediaType.TEXT_HTML); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML); }); } @Test public void customPrefix() { - this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/") - .run((context) -> { - MockServerWebExchange exchange = render(context, "prefixed"); - String result = exchange.getResponse().getBodyAsString() - .block(Duration.ofSeconds(30)); - assertThat(result).contains("prefixed"); - }); + this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/").run((context) -> { + MockServerWebExchange exchange = render(context, "prefixed"); + String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); + assertThat(result).contains("prefixed"); + }); } @Test public void customSuffix() { - this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker") - .run((context) -> { - MockServerWebExchange exchange = render(context, "suffixed"); - String result = exchange.getResponse().getBodyAsString() - .block(Duration.ofSeconds(30)); - assertThat(result).contains("suffixed"); - }); + this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker").run((context) -> { + MockServerWebExchange exchange = render(context, "suffixed"); + String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); + assertThat(result).contains("suffixed"); + }); } @Test public void customTemplateLoaderPath() { - this.contextRunner.withPropertyValues( - "spring.freemarker.templateLoaderPath:classpath:/custom-templates/") + this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/") .run((context) -> { MockServerWebExchange exchange = render(context, "custom"); - String result = exchange.getResponse().getBodyAsString() - .block(Duration.ofSeconds(30)); + String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); assertThat(result).contains("custom"); }); } @@ -106,10 +97,9 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { @SuppressWarnings("deprecation") @Test public void customFreeMarkerSettings() { - this.contextRunner - .withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") - .run((context) -> assertThat(context.getBean(FreeMarkerConfigurer.class) - .getConfiguration().getSetting("boolean_format")) + this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") + .run((context) -> assertThat( + context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) .isEqualTo("yup,nope")); } @@ -118,8 +108,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { this.contextRunner.withPropertyValues().run((context) -> { FreeMarkerConfigurer freemarker = context.getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); - freemarker.getConfiguration().getTemplate("message.ftl").process(this, - writer); + freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); }); } @@ -131,10 +120,8 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { private MockServerWebExchange render(ApplicationContext context, String viewName) { FreeMarkerViewResolver resolver = context.getBean(FreeMarkerViewResolver.class); Mono view = resolver.resolveViewName(viewName, Locale.UK); - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/path")); - view.flatMap((v) -> v.render(null, MediaType.TEXT_HTML, exchange)) - .block(Duration.ofSeconds(30)); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); + view.flatMap((v) -> v.render(null, MediaType.TEXT_HTML, exchange)).block(Duration.ofSeconds(30)); return exchange; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java index b6eb5718b6a..6028e8ca5f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java @@ -72,8 +72,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { assertThat(this.context.getBean(FreeMarkerViewResolver.class)).isNotNull(); assertThat(this.context.getBean(FreeMarkerConfigurer.class)).isNotNull(); assertThat(this.context.getBean(FreeMarkerConfig.class)).isNotNull(); - assertThat(this.context.getBean(freemarker.template.Configuration.class)) - .isNotNull(); + assertThat(this.context.getBean(freemarker.template.Configuration.class)).isNotNull(); } @Test @@ -121,32 +120,28 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @Test public void disableCache() { load("spring.freemarker.cache:false"); - assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()) - .isEqualTo(0); + assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()).isEqualTo(0); } @Test public void allowSessionOverride() { load("spring.freemarker.allow-session-override:true"); - AbstractTemplateViewResolver viewResolver = this.context - .getBean(FreeMarkerViewResolver.class); - assertThat(viewResolver).hasFieldOrPropertyWithValue("allowSessionOverride", - true); + AbstractTemplateViewResolver viewResolver = this.context.getBean(FreeMarkerViewResolver.class); + assertThat(viewResolver).hasFieldOrPropertyWithValue("allowSessionOverride", true); } @SuppressWarnings("deprecation") @Test public void customFreeMarkerSettings() { load("spring.freemarker.settings.boolean_format:yup,nope"); - assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration() - .getSetting("boolean_format")).isEqualTo("yup,nope"); + assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) + .isEqualTo("yup,nope"); } @Test public void renderTemplate() throws Exception { load(); - FreeMarkerConfigurer freemarker = this.context - .getBean(FreeMarkerConfigurer.class); + FreeMarkerConfigurer freemarker = this.context.getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); @@ -161,10 +156,8 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @Test public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { load("spring.resources.chain.enabled:true"); - FilterRegistrationBean registration = this.context - .getBean(FilterRegistrationBean.class); - assertThat(registration.getFilter()) - .isInstanceOf(ResourceUrlEncodingFilter.class); + FilterRegistrationBean registration = this.context.getBean(FilterRegistrationBean.class); + assertThat(registration.getFilter()).isInstanceOf(ResourceUrlEncodingFilter.class); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); } @@ -173,14 +166,11 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @SuppressWarnings("rawtypes") public void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 - load(FilterRegistrationOtherConfiguration.class, - "spring.resources.chain.enabled:true"); - Map beans = this.context - .getBeansOfType(FilterRegistrationBean.class); + load(FilterRegistrationOtherConfiguration.class, "spring.resources.chain.enabled:true"); + Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(2); FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) - .findFirst().get(); + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); } @@ -189,16 +179,12 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @SuppressWarnings("rawtypes") public void registerResourceHandlingFilterWithResourceRegistrationBean() { // gh-14926 - load(FilterRegistrationResourceConfiguration.class, - "spring.resources.chain.enabled:true"); - Map beans = this.context - .getBeansOfType(FilterRegistrationBean.class); + load(FilterRegistrationResourceConfiguration.class, "spring.resources.chain.enabled:true"); + Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(1); FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) - .findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", - EnumSet.of(DispatcherType.INCLUDE)); + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.INCLUDE)); } private void load(String... env) { @@ -218,21 +204,18 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } private MockHttpServletResponse render(String viewName) throws Exception { - FreeMarkerViewResolver resolver = this.context - .getBean(FreeMarkerViewResolver.class); + FreeMarkerViewResolver resolver = this.context.getBean(FreeMarkerViewResolver.class); View view = resolver.resolveViewName(viewName, Locale.UK); assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); - request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletResponse response = new MockHttpServletResponse(); view.render(null, request, response); return response; } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ FreeMarkerAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ FreeMarkerAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class BaseConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index e5f81349314..3fe7e72c953 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -47,8 +47,7 @@ public class FreeMarkerAutoConfigurationTests { @Test public void renderNonWebAppTemplate() { this.contextRunner.run((context) -> { - freemarker.template.Configuration freemarker = context - .getBean(freemarker.template.Configuration.class); + freemarker.template.Configuration freemarker = context.getBean(freemarker.template.Configuration.class); StringWriter writer = new StringWriter(); freemarker.getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); @@ -64,30 +63,26 @@ public class FreeMarkerAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,classpath:/also-does-not-exist") - .run((context) -> assertThat(capturedOutput) - .contains("Cannot find template location")); + .run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); } @Test public void emptyTemplateLocation(CapturedOutput capturedOutput) { - File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), - "empty-templates/empty-directory"); + File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory"); emptyDirectory.mkdirs(); this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(capturedOutput) - .doesNotContain("Cannot find template location")); + .withPropertyValues( + "spring.freemarker.templateLoaderPath:" + "classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); } @Test public void nonExistentLocationAndEmptyLocation(CapturedOutput capturedOutput) { - new File(this.buildOutput.getTestResourcesLocation(), - "empty-templates/empty-directory").mkdirs(); - this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(capturedOutput) - .doesNotContain("Cannot find template location")); + new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); + this.contextRunner + .withPropertyValues("spring.freemarker.templateLoaderPath:" + + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java index 5dbd844607c..32c68504926 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java @@ -40,44 +40,42 @@ public class FreeMarkerTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertThat(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isFalse(); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomLoaderPath() { - this.environment.setProperty("spring.freemarker.template-loader-path", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { - this.environment.setProperty("spring.freemarker.template-loader-path[0]", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.freemarker.template-loader-path[0]", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.freemarker.prefix", "prefix/"); - assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.freemarker.suffix", ".freemarker"); - assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java index 74cf4cc0a8f..7d67b34e899 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java @@ -79,10 +79,9 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void emptyTemplateLocation() { - new File(this.buildOutput.getTestResourcesLocation(), - "empty-templates/empty-directory").mkdirs(); - registerAndRefreshContext("spring.groovy.template.resource-loader-path:" - + "classpath:/templates/empty-directory/"); + new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); + registerAndRefreshContext( + "spring.groovy.template.resource-loader-path:" + "classpath:/templates/empty-directory/"); } @Test @@ -105,8 +104,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void disableViewResolution() { - TestPropertyValues.of("spring.groovy.template.enabled:false") - .applyTo(this.context); + TestPropertyValues.of("spring.groovy.template.enabled:false").applyTo(this.context); registerAndRefreshContext(); assertThat(this.context.getBeanNamesForType(ViewResolver.class)).isEmpty(); } @@ -147,8 +145,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void customTemplateLoaderPath() throws Exception { - registerAndRefreshContext( - "spring.groovy.template.resource-loader-path:classpath:/custom-templates/"); + registerAndRefreshContext("spring.groovy.template.resource-loader-path:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); assertThat(result).contains("custom"); @@ -157,8 +154,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void disableCache() { registerAndRefreshContext("spring.groovy.template.cache:false"); - assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit()) - .isEqualTo(0); + assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit()).isEqualTo(0); } @Test @@ -168,18 +164,14 @@ public class GroovyTemplateAutoConfigurationTests { MarkupTemplateEngine engine = config.getTemplateEngine(); Writer writer = new StringWriter(); engine.createTemplate(new ClassPathResource("templates/message.tpl").getFile()) - .make(new HashMap( - Collections.singletonMap("greeting", "Hello World"))) - .writeTo(writer); + .make(new HashMap(Collections.singletonMap("greeting", "Hello World"))).writeTo(writer); assertThat(writer.toString()).contains("Hello World"); } @Test public void customConfiguration() { - registerAndRefreshContext( - "spring.groovy.template.configuration.auto-indent:true"); - assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()) - .isTrue(); + registerAndRefreshContext("spring.groovy.template.configuration.auto-indent:true"); + assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()).isTrue(); } private void registerAndRefreshContext(String... env) { @@ -192,16 +184,13 @@ public class GroovyTemplateAutoConfigurationTests { return render(viewName, Locale.UK); } - private MockHttpServletResponse render(String viewName, Locale locale) - throws Exception { + private MockHttpServletResponse render(String viewName, Locale locale) throws Exception { LocaleContextHolder.setLocale(locale); - GroovyMarkupViewResolver resolver = this.context - .getBean(GroovyMarkupViewResolver.class); + GroovyMarkupViewResolver resolver = this.context.getBean(GroovyMarkupViewResolver.class); View view = resolver.resolveViewName(viewName, locale); assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); - request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletResponse response = new MockHttpServletResponse(); view.render(null, request, response); return response; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java index c0253ca7a42..5fd33f3e8f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java @@ -40,44 +40,42 @@ public class GroovyTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertThat(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isFalse(); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomLoaderPath() { - this.environment.setProperty("spring.groovy.template.resource-loader-path", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.groovy.template.resource-loader-path", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { - this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.groovy.template.prefix", "prefix/"); - assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.groovy.template.suffix", ".groovytemplate"); - assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java index 1a8ac7f1e8b..ba7735696d6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java @@ -58,21 +58,16 @@ public class GsonAutoConfigurationTests { @Test public void generateNonExecutableJson() { - this.contextRunner - .withPropertyValues("spring.gson.generate-non-executable-json:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())) - .isNotEqualTo("{\"data\":1}"); - assertThat(gson.toJson(new DataObject())).endsWith("{\"data\":1}"); - }); + this.contextRunner.withPropertyValues("spring.gson.generate-non-executable-json:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isNotEqualTo("{\"data\":1}"); + assertThat(gson.toJson(new DataObject())).endsWith("{\"data\":1}"); + }); } @Test public void excludeFieldsWithoutExposeAnnotation() { - this.contextRunner - .withPropertyValues( - "spring.gson.exclude-fields-without-expose-annotation:true") + this.contextRunner.withPropertyValues("spring.gson.exclude-fields-without-expose-annotation:true") .run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); @@ -81,27 +76,23 @@ public class GsonAutoConfigurationTests { @Test public void serializeNullsTrue() { - this.contextRunner.withPropertyValues("spring.gson.serialize-nulls:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.serializeNulls()).isTrue(); - }); + this.contextRunner.withPropertyValues("spring.gson.serialize-nulls:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.serializeNulls()).isTrue(); + }); } @Test public void serializeNullsFalse() { - this.contextRunner.withPropertyValues("spring.gson.serialize-nulls:false") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.serializeNulls()).isFalse(); - }); + this.contextRunner.withPropertyValues("spring.gson.serialize-nulls:false").run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.serializeNulls()).isFalse(); + }); } @Test public void enableComplexMapKeySerialization() { - this.contextRunner - .withPropertyValues( - "spring.gson.enable-complex-map-key-serialization:true") + this.contextRunner.withPropertyValues("spring.gson.enable-complex-map-key-serialization:true") .run((context) -> { Gson gson = context.getBean(Gson.class); Map original = new LinkedHashMap<>(); @@ -115,73 +106,59 @@ public class GsonAutoConfigurationTests { this.contextRunner.run((context) -> { Gson gson = context.getBean(Gson.class); WrapperObject wrapperObject = new WrapperObject(); - assertThat(gson.toJson(wrapperObject.new NestedObject())) - .isEqualTo("{\"data\":\"nested\"}"); + assertThat(gson.toJson(wrapperObject.new NestedObject())).isEqualTo("{\"data\":\"nested\"}"); }); } @Test public void disableInnerClassSerialization() { - this.contextRunner - .withPropertyValues("spring.gson.disable-inner-class-serialization:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - WrapperObject wrapperObject = new WrapperObject(); - assertThat(gson.toJson(wrapperObject.new NestedObject())) - .isEqualTo("null"); - }); + this.contextRunner.withPropertyValues("spring.gson.disable-inner-class-serialization:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + WrapperObject wrapperObject = new WrapperObject(); + assertThat(gson.toJson(wrapperObject.new NestedObject())).isEqualTo("null"); + }); } @Test public void withLongSerializationPolicy() { - this.contextRunner.withPropertyValues( - "spring.gson.long-serialization-policy:" + LongSerializationPolicy.STRING) + this.contextRunner.withPropertyValues("spring.gson.long-serialization-policy:" + LongSerializationPolicy.STRING) .run((context) -> { Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())) - .isEqualTo("{\"data\":\"1\"}"); + assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":\"1\"}"); }); } @Test public void withFieldNamingPolicy() { FieldNamingPolicy fieldNamingPolicy = FieldNamingPolicy.UPPER_CAMEL_CASE; - this.contextRunner - .withPropertyValues( - "spring.gson.field-naming-policy:" + fieldNamingPolicy) - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.fieldNamingStrategy()).isEqualTo(fieldNamingPolicy); - }); + this.contextRunner.withPropertyValues("spring.gson.field-naming-policy:" + fieldNamingPolicy).run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.fieldNamingStrategy()).isEqualTo(fieldNamingPolicy); + }); } @Test public void additionalGsonBuilderCustomization() { - this.contextRunner.withUserConfiguration(GsonBuilderCustomizerConfig.class) - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); - }); + this.contextRunner.withUserConfiguration(GsonBuilderCustomizerConfig.class).run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); + }); } @Test public void customGsonBuilder() { - this.contextRunner.withUserConfiguration(GsonBuilderConfig.class) - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())) - .isEqualTo("{\"data\":1,\"owner\":null}"); - }); + this.contextRunner.withUserConfiguration(GsonBuilderConfig.class).run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":1,\"owner\":null}"); + }); } @Test public void withPrettyPrinting() { - this.contextRunner.withPropertyValues("spring.gson.pretty-printing:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())) - .isEqualTo("{\n \"data\": 1\n}"); - }); + this.contextRunner.withPropertyValues("spring.gson.pretty-printing:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{\n \"data\": 1\n}"); + }); } @Test @@ -194,11 +171,10 @@ public class GsonAutoConfigurationTests { @Test public void withLenient() { - this.contextRunner.withPropertyValues("spring.gson.lenient:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("lenient", true); - }); + this.contextRunner.withPropertyValues("spring.gson.lenient:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson).hasFieldOrPropertyWithValue("lenient", true); + }); } @Test @@ -211,23 +187,21 @@ public class GsonAutoConfigurationTests { @Test public void withoutHtmlEscaping() { - this.contextRunner.withPropertyValues("spring.gson.disable-html-escaping:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.htmlSafe()).isFalse(); - }); + this.contextRunner.withPropertyValues("spring.gson.disable-html-escaping:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.htmlSafe()).isFalse(); + }); } @Test public void customDateFormat() { - this.contextRunner.withPropertyValues("spring.gson.date-format:H") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - DateTime dateTime = new DateTime(1988, 6, 25, 20, 30); - Date date = dateTime.toDate(); - assertThat(gson.toJson(date)).isEqualTo("\"20\""); - }); + this.contextRunner.withPropertyValues("spring.gson.date-format:H").run((context) -> { + Gson gson = context.getBean(Gson.class); + DateTime dateTime = new DateTime(1988, 6, 25, 20, 30); + Date date = dateTime.toDate(); + assertThat(gson.toJson(date)).isEqualTo("\"20\""); + }); } @Configuration(proxyBeanMethods = false) @@ -235,18 +209,17 @@ public class GsonAutoConfigurationTests { @Bean public GsonBuilderCustomizer customSerializationExclusionStrategy() { - return (gsonBuilder) -> gsonBuilder - .addSerializationExclusionStrategy(new ExclusionStrategy() { - @Override - public boolean shouldSkipField(FieldAttributes fieldAttributes) { - return "data".equals(fieldAttributes.getName()); - } + return (gsonBuilder) -> gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes fieldAttributes) { + return "data".equals(fieldAttributes.getName()); + } - @Override - public boolean shouldSkipClass(Class aClass) { - return false; - } - }); + @Override + public boolean shouldSkipClass(Class aClass) { + return false; + } + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 80795c605e6..379a9813b41 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -65,67 +65,52 @@ public class H2ConsoleAutoConfigurationTests { TestPropertyValues.of("spring.h2.console.enabled:true").applyTo(this.context); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - ServletRegistrationBean registrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); assertThat(registrationBean.getInitParameters()).doesNotContainKey("trace"); - assertThat(registrationBean.getInitParameters()) - .doesNotContainKey("webAllowOthers"); + assertThat(registrationBean.getInitParameters()).doesNotContainKey("webAllowOthers"); } @Test public void customPathMustBeginWithASlash() { this.context.register(H2ConsoleAutoConfiguration.class); - TestPropertyValues - .of("spring.h2.console.enabled:true", "spring.h2.console.path:custom") - .applyTo(this.context); - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(this.context::refresh).withMessageContaining( - "Failed to bind properties under 'spring.h2.console'"); + TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.path:custom").applyTo(this.context); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh) + .withMessageContaining("Failed to bind properties under 'spring.h2.console'"); } @Test public void customPathWithTrailingSlash() { this.context.register(H2ConsoleAutoConfiguration.class); - TestPropertyValues - .of("spring.h2.console.enabled:true", "spring.h2.console.path:/custom/") + TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.path:/custom/") .applyTo(this.context); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - ServletRegistrationBean servletRegistrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean servletRegistrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(servletRegistrationBean.getUrlMappings()).contains("/custom/*"); } @Test public void customPath() { this.context.register(H2ConsoleAutoConfiguration.class); - TestPropertyValues - .of("spring.h2.console.enabled:true", "spring.h2.console.path:/custom") - .applyTo(this.context); + TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.path:/custom").applyTo(this.context); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - ServletRegistrationBean servletRegistrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean servletRegistrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(servletRegistrationBean.getUrlMappings()).contains("/custom/*"); } @Test public void customInitParameters() { this.context.register(H2ConsoleAutoConfiguration.class); - TestPropertyValues - .of("spring.h2.console.enabled:true", - "spring.h2.console.settings.trace=true", - "spring.h2.console.settings.webAllowOthers=true") - .applyTo(this.context); + TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.settings.trace=true", + "spring.h2.console.settings.webAllowOthers=true").applyTo(this.context); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - ServletRegistrationBean registrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); assertThat(registrationBean.getInitParameters()).containsEntry("trace", ""); - assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", - ""); + assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", ""); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java index 25d007727c2..0068ff465f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java @@ -39,16 +39,14 @@ public class H2ConsolePropertiesTests { @Test public void pathMustHaveLengthGreaterThanOne() { this.properties = new H2ConsoleProperties(); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.properties.setPath("/")) + assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("/")) .withMessageContaining("Path must have length greater than 1"); } @Test public void customPathMustBeginWithASlash() { this.properties = new H2ConsoleProperties(); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.properties.setPath("custom")) + assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("custom")) .withMessageContaining("Path must start with '/'"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index aa5c00d5f21..f9b92d4555b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java @@ -71,8 +71,7 @@ public class HypermediaAutoConfigurationTests { this.context.refresh(); LinkDiscoverers discoverers = this.context.getBean(LinkDiscoverers.class); assertThat(discoverers).isNotNull(); - Optional discoverer = discoverers - .getLinkDiscovererFor(MediaTypes.HAL_JSON); + Optional discoverer = discoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON); assertThat(discoverer).containsInstanceOf(HalLinkDiscoverer.class); } @@ -91,8 +90,7 @@ public class HypermediaAutoConfigurationTests { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(EnableHypermediaSupportConfig.class, BaseConfig.class); - TestPropertyValues.of("spring.jackson.serialization.INDENT_OUTPUT:true") - .applyTo(this.context); + TestPropertyValues.of("spring.jackson.serialization.INDENT_OUTPUT:true").applyTo(this.context); this.context.refresh(); assertThat(this.context.getBeansOfType(HypermediaConfiguration.class)).isEmpty(); assertThat(this.context.getBeansOfType(EntityLinksConfiguration.class)).isEmpty(); @@ -104,12 +102,11 @@ public class HypermediaAutoConfigurationTests { this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); this.context.refresh(); - RequestMappingHandlerAdapter handlerAdapter = this.context - .getBean(RequestMappingHandlerAdapter.class); + RequestMappingHandlerAdapter handlerAdapter = this.context.getBean(RequestMappingHandlerAdapter.class); for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - assertThat(converter.getSupportedMediaTypes()) - .contains(MediaType.APPLICATION_JSON, MediaTypes.HAL_JSON); + assertThat(converter.getSupportedMediaTypes()).contains(MediaType.APPLICATION_JSON, + MediaTypes.HAL_JSON); } } } @@ -119,22 +116,19 @@ public class HypermediaAutoConfigurationTests { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); - TestPropertyValues.of("spring.hateoas.use-hal-as-default-json-media-type:false") - .applyTo(this.context); + TestPropertyValues.of("spring.hateoas.use-hal-as-default-json-media-type:false").applyTo(this.context); this.context.refresh(); - RequestMappingHandlerAdapter handlerAdapter = this.context - .getBean(RequestMappingHandlerAdapter.class); + RequestMappingHandlerAdapter handlerAdapter = this.context.getBean(RequestMappingHandlerAdapter.class); for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - assertThat(converter.getSupportedMediaTypes()) - .containsExactly(MediaTypes.HAL_JSON, MediaTypes.HAL_JSON_UTF8); + assertThat(converter.getSupportedMediaTypes()).containsExactly(MediaTypes.HAL_JSON, + MediaTypes.HAL_JSON_UTF8); } } } - @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - HypermediaAutoConfiguration.class }) + @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, HypermediaAutoConfiguration.class }) static class BaseConfig { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java index c1dfef246c8..dfd1666be5d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java @@ -46,8 +46,8 @@ public class HypermediaAutoConfigurationWithoutJacksonTests { this.context.refresh(); } - @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, HypermediaAutoConfiguration.class }) + @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + HypermediaAutoConfiguration.class }) static class BaseConfig { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java index 43f258cbd78..bbbdc732244 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java @@ -66,83 +66,70 @@ public class HazelcastAutoConfigurationClientTests { @Test public void systemPropertyWithXml() { - this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-client-specific.xml") + this.contextRunner.withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-client-specific.xml") .run(assertSpecificHazelcastClient("explicit-xml")); } @Test public void systemPropertyWithYaml() { - this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-client-specific.yaml") + this.contextRunner.withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-client-specific.yaml") .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test public void explicitConfigFileWithXml() { - this.contextRunner - .withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml") - .run(assertSpecificHazelcastClient("explicit-xml")); + this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml").run(assertSpecificHazelcastClient("explicit-xml")); } @Test public void explicitConfigFileWithYaml() { this.contextRunner - .withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.yaml") + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.yaml") .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test public void explicitConfigUrlWithXml() { - this.contextRunner.withPropertyValues( - "spring.hazelcast.config=classpath:org/springframework/" + this.contextRunner + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + "boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") .run(assertSpecificHazelcastClient("explicit-xml")); } @Test public void explicitConfigUrlWithYaml() { - this.contextRunner.withPropertyValues( - "spring.hazelcast.config=classpath:org/springframework/" + this.contextRunner + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test public void unknownConfigFile() { - this.contextRunner - .withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) + this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("foo/bar/unknown.xml")); } @Test public void clientConfigTakesPrecedence() { this.contextRunner.withUserConfiguration(HazelcastServerAndClientConfig.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") - .run((context) -> assertThat(context).getBean(HazelcastInstance.class) - .isInstanceOf(HazelcastClientProxy.class)); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> assertThat(context) + .getBean(HazelcastInstance.class).isInstanceOf(HazelcastClientProxy.class)); } - private ContextConsumer assertSpecificHazelcastClient( - String label) { - return (context) -> assertThat(context).getBean(HazelcastInstance.class) - .isInstanceOf(HazelcastInstance.class).has(labelEqualTo(label)); + private ContextConsumer assertSpecificHazelcastClient(String label) { + return (context) -> assertThat(context).getBean(HazelcastInstance.class).isInstanceOf(HazelcastInstance.class) + .has(labelEqualTo(label)); } private static Condition labelEqualTo(String label) { - return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig() - .getLabels().stream().anyMatch((e) -> e.equals(label)), - "Label equals to " + label); + return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig().getLabels().stream() + .anyMatch((e) -> e.equals(label)), "Label equals to " + label); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java index bf7ba986590..8cbe488194a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java @@ -55,8 +55,7 @@ public class HazelcastAutoConfigurationServerTests { // hazelcast.xml present in root classpath this.contextRunner.run((context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getConfigurationUrl()) - .isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); + assertThat(config.getConfigurationUrl()).isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); }); } @@ -84,8 +83,8 @@ public class HazelcastAutoConfigurationServerTests { @Test public void explicitConfigFileWithXml() { - this.contextRunner.withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.xml") .run(assertSpecificHazelcastServer( "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); @@ -93,8 +92,8 @@ public class HazelcastAutoConfigurationServerTests { @Test public void explicitConfigFileWithYaml() { - this.contextRunner.withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.yaml") .run(assertSpecificHazelcastServer( "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); @@ -103,9 +102,8 @@ public class HazelcastAutoConfigurationServerTests { @Test public void explicitConfigUrlWithXml() { this.contextRunner - .withPropertyValues( - "spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") .run(assertSpecificHazelcastServer( "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); } @@ -113,15 +111,13 @@ public class HazelcastAutoConfigurationServerTests { @Test public void explicitConfigUrlWithYaml() { this.contextRunner - .withPropertyValues( - "spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") .run(assertSpecificHazelcastServer( "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); } - private ContextConsumer assertSpecificHazelcastServer( - String location) { + private ContextConsumer assertSpecificHazelcastServer(String location) { return (context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); assertThat(config.getConfigurationUrl()).asString().endsWith(location); @@ -130,10 +126,8 @@ public class HazelcastAutoConfigurationServerTests { @Test public void unknownConfigFile() { - this.contextRunner - .withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) + this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("foo/bar/unknown.xml")); } @@ -143,12 +137,9 @@ public class HazelcastAutoConfigurationServerTests { HazelcastInstance existing = Hazelcast.newHazelcastInstance(config); try { this.contextRunner.withUserConfiguration(HazelcastConfigWithName.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") - .run((context) -> { - HazelcastInstance hazelcast = context - .getBean(HazelcastInstance.class); - assertThat(hazelcast.getConfig().getInstanceName()) - .isEqualTo("my-test-instance"); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + assertThat(hazelcast.getConfig().getInstanceName()).isEqualTo("my-test-instance"); // Should reuse any existing instance by default. assertThat(hazelcast).isEqualTo(existing); }); @@ -161,8 +152,7 @@ public class HazelcastAutoConfigurationServerTests { @Test public void configInstanceWithoutName() { this.contextRunner.withUserConfiguration(HazelcastConfigNoName.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") - .run((context) -> { + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); Map queueConfigs = config.getQueueConfigs(); assertThat(queueConfigs.keySet()).containsOnly("another-queue"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index 682ea9575d0..308267aa9b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -43,8 +43,7 @@ public class HazelcastAutoConfigurationTests { // as both hazelcast.yaml and hazelcast.xml in test classpath. this.contextRunner.run((context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getConfigurationUrl()) - .isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); + assertThat(config.getConfigurationUrl()).isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java index 86851a42481..872e7329c5b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java @@ -46,50 +46,40 @@ public class HazelcastJpaDependencyAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - HazelcastJpaDependencyAutoConfiguration.class)) + HibernateJpaAutoConfiguration.class, HazelcastJpaDependencyAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.datasource.initialization-mode=never"); @Test public void registrationIfHazelcastInstanceHasRegularBeanName() { - this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) - .run((context) -> { - assertThat(postProcessors(context)) - .containsKey("hazelcastInstanceJpaDependencyPostProcessor"); - assertThat(entityManagerFactoryDependencies(context)) - .contains("hazelcastInstance"); - }); + this.contextRunner.withUserConfiguration(HazelcastConfiguration.class).run((context) -> { + assertThat(postProcessors(context)).containsKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(entityManagerFactoryDependencies(context)).contains("hazelcastInstance"); + }); } @Test public void noRegistrationIfHazelcastInstanceHasCustomBeanName() { - this.contextRunner.withUserConfiguration(HazelcastCustomNameConfiguration.class) - .run((context) -> { - assertThat(entityManagerFactoryDependencies(context)) - .doesNotContain("hazelcastInstance"); - assertThat(postProcessors(context)).doesNotContainKey( - "hazelcastInstanceJpaDependencyPostProcessor"); - }); + this.contextRunner.withUserConfiguration(HazelcastCustomNameConfiguration.class).run((context) -> { + assertThat(entityManagerFactoryDependencies(context)).doesNotContain("hazelcastInstance"); + assertThat(postProcessors(context)).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); + }); } @Test public void noRegistrationWithNoHazelcastInstance() { this.contextRunner.run((context) -> { - assertThat(entityManagerFactoryDependencies(context)) - .doesNotContain("hazelcastInstance"); - assertThat(postProcessors(context)) - .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(entityManagerFactoryDependencies(context)).doesNotContain("hazelcastInstance"); + assertThat(postProcessors(context)).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); }); } @Test public void noRegistrationWithNoEntityManagerFactory() { new ApplicationContextRunner().withUserConfiguration(HazelcastConfiguration.class) - .withConfiguration(AutoConfigurations - .of(HazelcastJpaDependencyAutoConfiguration.class)) - .run((context) -> assertThat(postProcessors(context)).doesNotContainKey( - "hazelcastInstanceJpaDependencyPostProcessor")); + .withConfiguration(AutoConfigurations.of(HazelcastJpaDependencyAutoConfiguration.class)) + .run((context) -> assertThat(postProcessors(context)) + .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor")); } private Map postProcessors( @@ -97,11 +87,9 @@ public class HazelcastJpaDependencyAutoConfigurationTests { return context.getBeansOfType(EntityManagerFactoryDependsOnPostProcessor.class); } - private List entityManagerFactoryDependencies( - AssertableApplicationContext context) { - String[] dependsOn = ((BeanDefinitionRegistry) context - .getSourceApplicationContext()).getBeanDefinition("entityManagerFactory") - .getDependsOn(); + private List entityManagerFactoryDependencies(AssertableApplicationContext context) { + String[] dependsOn = ((BeanDefinitionRegistry) context.getSourceApplicationContext()) + .getBeanDefinition("entityManagerFactory").getDependsOn(); return (dependsOn != null) ? Arrays.asList(dependsOn) : Collections.emptyList(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java index 131aee56a92..da0f0e80867 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java @@ -63,48 +63,39 @@ import static org.assertj.core.api.Assertions.assertThat; public class HttpMessageConvertersAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test public void jacksonNotAvailable() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(ObjectMapper.class); - assertThat(context) - .doesNotHaveBean(MappingJackson2HttpMessageConverter.class); - assertThat(context) - .doesNotHaveBean(MappingJackson2XmlHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(MappingJackson2HttpMessageConverter.class); + assertThat(context).doesNotHaveBean(MappingJackson2XmlHttpMessageConverter.class); }); } @Test public void jacksonDefaultConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, - "mappingJackson2HttpMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test public void jacksonConverterWithBuilder() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, - "mappingJackson2HttpMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test public void jacksonXmlConverterWithBuilder() { - this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) - .run(assertConverter(MappingJackson2XmlHttpMessageConverter.class, - "mappingJackson2XmlHttpMessageConverter")); + this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class).run(assertConverter( + MappingJackson2XmlHttpMessageConverter.class, "mappingJackson2XmlHttpMessageConverter")); } @Test public void jacksonCustomConverter() { - this.contextRunner - .withUserConfiguration(JacksonObjectMapperConfig.class, - JacksonConverterConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, - "customJacksonMessageConverter")); + this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class, JacksonConverterConfig.class) + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter")); } @Test @@ -117,33 +108,25 @@ public class HttpMessageConvertersAutoConfigurationTests { @Test public void gsonDefaultConverter() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) - .run(assertConverter(GsonHttpMessageConverter.class, - "gsonHttpMessageConverter")); + this.contextRunner.withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) + .run(assertConverter(GsonHttpMessageConverter.class, "gsonHttpMessageConverter")); } @Test public void gsonCustomConverter() { this.contextRunner.withUserConfiguration(GsonConverterConfig.class) .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) - .run(assertConverter(GsonHttpMessageConverter.class, - "customGsonMessageConverter")); + .run(assertConverter(GsonHttpMessageConverter.class, "customGsonMessageConverter")); } @Test public void gsonCanBePreferred() { - allOptionsRunner() - .withPropertyValues("spring.http.converters.preferred-json-mapper:gson") - .run((context) -> { - assertConverterBeanExists(context, GsonHttpMessageConverter.class, - "gsonHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters(context, - GsonHttpMessageConverter.class); - assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); - assertThat(context) - .doesNotHaveBean(MappingJackson2HttpMessageConverter.class); - }); + allOptionsRunner().withPropertyValues("spring.http.converters.preferred-json-mapper:gson").run((context) -> { + assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(MappingJackson2HttpMessageConverter.class); + }); } @Test @@ -156,71 +139,58 @@ public class HttpMessageConvertersAutoConfigurationTests { @Test public void jsonbDefaultConverter() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .run(assertConverter(JsonbHttpMessageConverter.class, - "jsonbHttpMessageConverter")); + this.contextRunner.withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) + .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test public void jsonbCustomConverter() { this.contextRunner.withUserConfiguration(JsonbConverterConfig.class) .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .run(assertConverter(JsonbHttpMessageConverter.class, - "customJsonbMessageConverter")); + .run(assertConverter(JsonbHttpMessageConverter.class, "customJsonbMessageConverter")); } @Test public void jsonbCanBePreferred() { - allOptionsRunner() - .withPropertyValues("spring.http.converters.preferred-json-mapper:jsonb") - .run((context) -> { - assertConverterBeanExists(context, JsonbHttpMessageConverter.class, - "jsonbHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters(context, - JsonbHttpMessageConverter.class); - assertThat(context).doesNotHaveBean(GsonHttpMessageConverter.class); - assertThat(context) - .doesNotHaveBean(MappingJackson2HttpMessageConverter.class); - }); + allOptionsRunner().withPropertyValues("spring.http.converters.preferred-json-mapper:jsonb").run((context) -> { + assertConverterBeanExists(context, JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(context, JsonbHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(GsonHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(MappingJackson2HttpMessageConverter.class); + }); } @Test public void stringDefaultConverter() { - this.contextRunner.run(assertConverter(StringHttpMessageConverter.class, - "stringHttpMessageConverter")); + this.contextRunner.run(assertConverter(StringHttpMessageConverter.class, "stringHttpMessageConverter")); } @Test public void stringCustomConverter() { this.contextRunner.withUserConfiguration(StringConverterConfig.class) - .run(assertConverter(StringHttpMessageConverter.class, - "customStringMessageConverter")); + .run(assertConverter(StringHttpMessageConverter.class, "customStringMessageConverter")); } @Test public void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class, TypeConstrainedConverterConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = ((GenericApplicationContext) context - .getSourceApplicationContext()).getBeanDefinition( - "mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()).isEqualTo( - MappingJackson2HttpMessageConverterConfiguration.class - .getName()); + BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) + .getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); }); } @Test public void typeConstrainedConverterFromSpringDataDoesNotPreventAutoConfigurationOfJacksonConverter() { - this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class, - RepositoryRestMvcConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = ((GenericApplicationContext) context - .getSourceApplicationContext()).getBeanDefinition( - "mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()).isEqualTo( - MappingJackson2HttpMessageConverterConfiguration.class - .getName()); + this.contextRunner + .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) + .getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); }); } @@ -229,8 +199,7 @@ public class HttpMessageConvertersAutoConfigurationTests { allOptionsRunner().run((context) -> { assertConverterBeanExists(context, MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters(context, - MappingJackson2HttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(context, MappingJackson2HttpMessageConverter.class); assertThat(context).doesNotHaveBean(GsonHttpMessageConverter.class); assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); }); @@ -238,13 +207,10 @@ public class HttpMessageConvertersAutoConfigurationTests { @Test public void gsonIsPreferredIfJacksonIsNotAvailable() { - allOptionsRunner().withClassLoader( - new FilteredClassLoader(ObjectMapper.class.getPackage().getName())) + allOptionsRunner().withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName())) .run((context) -> { - assertConverterBeanExists(context, GsonHttpMessageConverter.class, - "gsonHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters(context, - GsonHttpMessageConverter.class); + assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); }); } @@ -252,54 +218,44 @@ public class HttpMessageConvertersAutoConfigurationTests { @Test public void jsonbIsPreferredIfJacksonAndGsonAreNotAvailable() { allOptionsRunner() - .withClassLoader( - new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), - Gson.class.getPackage().getName())) - .run(assertConverter(JsonbHttpMessageConverter.class, - "jsonbHttpMessageConverter")); + .withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), + Gson.class.getPackage().getName())) + .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test public void whenServletWebApplicationHttpMessageConvertersIsConfigured() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(HttpMessageConverters.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); } @Test public void whenReactiveWebApplicationHttpMessageConvertersIsNotConfigured() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(HttpMessageConverters.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(HttpMessageConverters.class)); } private ApplicationContextRunner allOptionsRunner() { - return this.contextRunner - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, - JacksonAutoConfiguration.class, JsonbAutoConfiguration.class)); + return this.contextRunner.withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, + JacksonAutoConfiguration.class, JsonbAutoConfiguration.class)); } private ContextConsumer assertConverter( Class> converterType, String beanName) { return (context) -> { assertConverterBeanExists(context, converterType, beanName); - assertConverterBeanRegisteredWithHttpMessageConverters(context, - converterType); + assertConverterBeanRegisteredWithHttpMessageConverters(context, converterType); }; } - private void assertConverterBeanExists(AssertableApplicationContext context, - Class type, String beanName) { + private void assertConverterBeanExists(AssertableApplicationContext context, Class type, String beanName) { assertThat(context).hasSingleBean(type); assertThat(context).hasBean(beanName); } - private void assertConverterBeanRegisteredWithHttpMessageConverters( - AssertableApplicationContext context, + private void assertConverterBeanRegisteredWithHttpMessageConverters(AssertableApplicationContext context, Class> type) { HttpMessageConverter converter = context.getBean(type); HttpMessageConverters converters = context.getBean(HttpMessageConverters.class); @@ -335,8 +291,7 @@ public class HttpMessageConvertersAutoConfigurationTests { protected static class JacksonConverterConfig { @Bean - public MappingJackson2HttpMessageConverter customJacksonMessageConverter( - ObjectMapper objectMapper) { + public MappingJackson2HttpMessageConverter customJacksonMessageConverter(ObjectMapper objectMapper) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(objectMapper); return converter; @@ -383,8 +338,7 @@ public class HttpMessageConvertersAutoConfigurationTests { @Bean public TypeConstrainedMappingJackson2HttpMessageConverter typeConstrainedConverter() { - return new TypeConstrainedMappingJackson2HttpMessageConverter( - RepresentationModel.class); + return new TypeConstrainedMappingJackson2HttpMessageConverter(RepresentationModel.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java index 76dba6297d5..ca36e1799e4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java @@ -55,12 +55,9 @@ public class HttpMessageConvertersTests { } assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, - ResourceRegionHttpMessageConverter.class, - SourceHttpMessageConverter.class, - AllEncompassingFormHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class, - MappingJackson2SmileHttpMessageConverter.class, - MappingJackson2CborHttpMessageConverter.class, + ResourceRegionHttpMessageConverter.class, SourceHttpMessageConverter.class, + AllEncompassingFormHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class, + MappingJackson2SmileHttpMessageConverter.class, MappingJackson2CborHttpMessageConverter.class, MappingJackson2XmlHttpMessageConverter.class); } @@ -68,8 +65,7 @@ public class HttpMessageConvertersTests { public void addBeforeExistingConverter() { MappingJackson2HttpMessageConverter converter1 = new MappingJackson2HttpMessageConverter(); MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter(); - HttpMessageConverters converters = new HttpMessageConverters(converter1, - converter2); + HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); assertThat(converters.getConverters().contains(converter1)).isTrue(); assertThat(converters.getConverters().contains(converter2)).isTrue(); List httpConverters = new ArrayList<>(); @@ -89,8 +85,7 @@ public class HttpMessageConvertersTests { public void addNewConverters() { HttpMessageConverter converter1 = mock(HttpMessageConverter.class); HttpMessageConverter converter2 = mock(HttpMessageConverter.class); - HttpMessageConverters converters = new HttpMessageConverters(converter1, - converter2); + HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); assertThat(converters.getConverters().get(0)).isEqualTo(converter1); assertThat(converters.getConverters().get(1)).isEqualTo(converter2); } @@ -99,10 +94,8 @@ public class HttpMessageConvertersTests { public void convertersAreAddedToFormPartConverter() { HttpMessageConverter converter1 = mock(HttpMessageConverter.class); HttpMessageConverter converter2 = mock(HttpMessageConverter.class); - List> converters = new HttpMessageConverters(converter1, - converter2).getConverters(); - List> partConverters = extractFormPartConverters( - converters); + List> converters = new HttpMessageConverters(converter1, converter2).getConverters(); + List> partConverters = extractFormPartConverters(converters); assertThat(partConverters.get(0)).isEqualTo(converter1); assertThat(partConverters.get(1)).isEqualTo(converter2); } @@ -112,10 +105,8 @@ public class HttpMessageConvertersTests { HttpMessageConverters converters = new HttpMessageConverters() { @Override - protected List> postProcessConverters( - List> converters) { - converters.removeIf( - MappingJackson2XmlHttpMessageConverter.class::isInstance); + protected List> postProcessConverters(List> converters) { + converters.removeIf(MappingJackson2XmlHttpMessageConverter.class::isInstance); return converters; } @@ -126,12 +117,9 @@ public class HttpMessageConvertersTests { } assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, - ResourceRegionHttpMessageConverter.class, - SourceHttpMessageConverter.class, - AllEncompassingFormHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class, - MappingJackson2SmileHttpMessageConverter.class, - MappingJackson2CborHttpMessageConverter.class); + ResourceRegionHttpMessageConverter.class, SourceHttpMessageConverter.class, + AllEncompassingFormHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class, + MappingJackson2SmileHttpMessageConverter.class, MappingJackson2CborHttpMessageConverter.class); } @Test @@ -141,35 +129,27 @@ public class HttpMessageConvertersTests { @Override protected List> postProcessPartConverters( List> converters) { - converters.removeIf( - MappingJackson2XmlHttpMessageConverter.class::isInstance); + converters.removeIf(MappingJackson2XmlHttpMessageConverter.class::isInstance); return converters; } }; List> converterClasses = new ArrayList<>(); - for (HttpMessageConverter converter : extractFormPartConverters( - converters.getConverters())) { + for (HttpMessageConverter converter : extractFormPartConverters(converters.getConverters())) { converterClasses.add(converter.getClass()); } assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class, - MappingJackson2SmileHttpMessageConverter.class); + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, SourceHttpMessageConverter.class, + MappingJackson2HttpMessageConverter.class, MappingJackson2SmileHttpMessageConverter.class); } @SuppressWarnings("unchecked") - private List> extractFormPartConverters( - List> converters) { - AllEncompassingFormHttpMessageConverter formConverter = findFormConverter( - converters); - return (List>) ReflectionTestUtils.getField(formConverter, - "partConverters"); + private List> extractFormPartConverters(List> converters) { + AllEncompassingFormHttpMessageConverter formConverter = findFormConverter(converters); + return (List>) ReflectionTestUtils.getField(formConverter, "partConverters"); } - private AllEncompassingFormHttpMessageConverter findFormConverter( - Collection> converters) { + private AllEncompassingFormHttpMessageConverter findFormConverter(Collection> converters) { for (HttpMessageConverter converter : converters) { if (converter instanceof AllEncompassingFormHttpMessageConverter) { return (AllEncompassingFormHttpMessageConverter) converter; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java index 3fef3b4b5c0..5d012863364 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java @@ -51,40 +51,35 @@ public class CodecsAutoConfigurationTests { CodecCustomizer customizer = context.getBean(CodecCustomizer.class); CodecConfigurer configurer = new DefaultClientCodecConfigurer(); customizer.customize(configurer); - assertThat(configurer.defaultCodecs()) - .hasFieldOrPropertyWithValue("enableLoggingRequestDetails", false); + assertThat(configurer.defaultCodecs()).hasFieldOrPropertyWithValue("enableLoggingRequestDetails", false); }); } @Test public void loggingRequestDetailsCustomizerShouldUseHttpProperties() { - this.contextRunner.withPropertyValues("spring.http.log-request-details=true") - .run((context) -> { - CodecCustomizer customizer = context.getBean(CodecCustomizer.class); - CodecConfigurer configurer = new DefaultClientCodecConfigurer(); - customizer.customize(configurer); - assertThat(configurer.defaultCodecs()).hasFieldOrPropertyWithValue( - "enableLoggingRequestDetails", true); - }); + this.contextRunner.withPropertyValues("spring.http.log-request-details=true").run((context) -> { + CodecCustomizer customizer = context.getBean(CodecCustomizer.class); + CodecConfigurer configurer = new DefaultClientCodecConfigurer(); + customizer.customize(configurer); + assertThat(configurer.defaultCodecs()).hasFieldOrPropertyWithValue("enableLoggingRequestDetails", true); + }); } @Test public void loggingRequestDetailsBeanShouldHaveOrderZero() { this.contextRunner.run((context) -> { Method customizerMethod = ReflectionUtils.findMethod( - CodecsAutoConfiguration.LoggingCodecConfiguration.class, - "loggingCodecCustomizer", HttpProperties.class); - Integer order = new TestAnnotationAwareOrderComparator() - .findOrder(customizerMethod); + CodecsAutoConfiguration.LoggingCodecConfiguration.class, "loggingCodecCustomizer", + HttpProperties.class); + Integer order = new TestAnnotationAwareOrderComparator().findOrder(customizerMethod); assertThat(order).isEqualTo(0); }); } @Test public void jacksonCodecCustomizerBacksOffWhenThereIsNoObjectMapper() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean("jacksonCodecCustomizer")); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("jacksonCodecCustomizer")); } @Test @@ -95,18 +90,15 @@ public class CodecsAutoConfigurationTests { @Test public void userProvidedCustomizerCanOverrideJacksonCodecCustomizer() { - this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class, - CodecCustomizerConfiguration.class).run((context) -> { - List codecCustomizers = context - .getBean(CodecCustomizers.class).codecCustomizers; + this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class, CodecCustomizerConfiguration.class) + .run((context) -> { + List codecCustomizers = context.getBean(CodecCustomizers.class).codecCustomizers; assertThat(codecCustomizers).hasSize(3); - assertThat(codecCustomizers.get(2)) - .isInstanceOf(TestCodecCustomizer.class); + assertThat(codecCustomizers.get(2)).isInstanceOf(TestCodecCustomizer.class); }); } - static class TestAnnotationAwareOrderComparator - extends AnnotationAwareOrderComparator { + static class TestAnnotationAwareOrderComparator extends AnnotationAwareOrderComparator { @Override public Integer findOrder(Object obj) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java index c3076c850a6..22d3249e228 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java @@ -46,36 +46,30 @@ public class InfluxDbAutoConfigurationTests { @Test public void influxDbRequiresUrl() { - this.contextRunner - .run((context) -> assertThat(context.getBeansOfType(InfluxDB.class)) - .isEmpty()); + this.contextRunner.run((context) -> assertThat(context.getBeansOfType(InfluxDB.class)).isEmpty()); } @Test public void influxDbCanBeCustomized() { this.contextRunner - .withPropertyValues("spring.influx.url=http://localhost", - "spring.influx.password:password", "spring.influx.user:user") - .run(((context) -> assertThat(context.getBeansOfType(InfluxDB.class)) - .hasSize(1))); + .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.password:password", + "spring.influx.user:user") + .run(((context) -> assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1))); } @Test public void influxDbCanBeCreatedWithoutCredentials() { - this.contextRunner.withPropertyValues("spring.influx.url=http://localhost") - .run((context) -> { - assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); - int readTimeout = getReadTimeoutProperty(context); - assertThat(readTimeout).isEqualTo(10_000); - }); + this.contextRunner.withPropertyValues("spring.influx.url=http://localhost").run((context) -> { + assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); + int readTimeout = getReadTimeoutProperty(context); + assertThat(readTimeout).isEqualTo(10_000); + }); } @Test public void influxDbWithOkHttpClientBuilderProvider() { - this.contextRunner - .withUserConfiguration(CustomOkHttpClientBuilderProviderConfig.class) - .withPropertyValues("spring.influx.url=http://localhost") - .run((context) -> { + this.contextRunner.withUserConfiguration(CustomOkHttpClientBuilderProviderConfig.class) + .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); int readTimeout = getReadTimeoutProperty(context); assertThat(readTimeout).isEqualTo(40_000); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java index f0154cbb3d3..d29235ea8b7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java @@ -37,22 +37,19 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ProjectInfoAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - ProjectInfoAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, ProjectInfoAutoConfiguration.class)); @Test public void gitPropertiesUnavailableIfResourceNotAvailable() { - this.contextRunner - .run((context) -> assertThat(context.getBeansOfType(GitProperties.class)) - .isEmpty()); + this.contextRunner.run((context) -> assertThat(context.getBeansOfType(GitProperties.class)).isEmpty()); } @Test public void gitPropertiesWithNoData() { - this.contextRunner.withPropertyValues("spring.info.git.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") + this.contextRunner + .withPropertyValues("spring.info.git.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") .run((context) -> { GitProperties gitProperties = context.getBean(GitProperties.class); assertThat(gitProperties.getBranch()).isNull(); @@ -61,13 +58,11 @@ public class ProjectInfoAutoConfigurationTests { @Test public void gitPropertiesFallbackWithGitPropertiesBean() { - this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class) - .withPropertyValues("spring.info.git.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/git.properties") + this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).withPropertyValues( + "spring.info.git.location=" + "classpath:/org/springframework/boot/autoconfigure/info/git.properties") .run((context) -> { GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties) - .isSameAs(context.getBean("customGitProperties")); + assertThat(gitProperties).isSameAs(context.getBean("customGitProperties")); }); } @@ -99,45 +94,38 @@ public class ProjectInfoAutoConfigurationTests { assertThat(buildProperties.getArtifact()).isEqualTo("demo"); assertThat(buildProperties.getName()).isEqualTo("Demo Project"); assertThat(buildProperties.getVersion()).isEqualTo("0.0.1-SNAPSHOT"); - assertThat(buildProperties.getTime().toEpochMilli()) - .isEqualTo(1457100965000L); + assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457100965000L); }); } @Test public void buildPropertiesCustomLocation() { - this.contextRunner.withPropertyValues("spring.info.build.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") + this.contextRunner + .withPropertyValues("spring.info.build.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") .run((context) -> { - BuildProperties buildProperties = context - .getBean(BuildProperties.class); + BuildProperties buildProperties = context.getBean(BuildProperties.class); assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); assertThat(buildProperties.getArtifact()).isEqualTo("acme"); assertThat(buildProperties.getName()).isEqualTo("acme"); assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); - assertThat(buildProperties.getTime().toEpochMilli()) - .isEqualTo(1457088120000L); + assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); }); } @Test public void buildPropertiesCustomInvalidLocation() { this.contextRunner - .withPropertyValues("spring.info.build.location=" - + "classpath:/org/acme/no-build-info.properties") - .run((context) -> assertThat( - context.getBeansOfType(BuildProperties.class)).hasSize(0)); + .withPropertyValues("spring.info.build.location=" + "classpath:/org/acme/no-build-info.properties") + .run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0)); } @Test public void buildPropertiesFallbackWithBuildInfoBean() { - this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class) - .run((context) -> { - BuildProperties buildProperties = context - .getBean(BuildProperties.class); - assertThat(buildProperties) - .isSameAs(context.getBean("customBuildProperties")); - }); + this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties).isSameAs(context.getBean("customBuildProperties")); + }); } @Test @@ -145,8 +133,7 @@ public class ProjectInfoAutoConfigurationTests { this.contextRunner.withPropertyValues( "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") .run((context) -> { - BuildProperties buildProperties = context - .getBean(BuildProperties.class); + BuildProperties buildProperties = context.getBean(BuildProperties.class); assertThat(buildProperties.get("charset")).isEqualTo("test™"); }); } @@ -156,8 +143,7 @@ public class ProjectInfoAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.info.build.encoding=US-ASCII", "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") .run((context) -> { - BuildProperties buildProperties = context - .getBean(BuildProperties.class); + BuildProperties buildProperties = context.getBean(BuildProperties.class); assertThat(buildProperties.get("charset")).isNotEqualTo("test™"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index 35f951e832f..4aaf00394fb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -57,38 +57,31 @@ import static org.mockito.Mockito.mock; public class IntegrationAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, - IntegrationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); @Test public void integrationIsAvailable() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(TestGateway.class); - assertThat(context) - .hasSingleBean(IntegrationComponentScanConfiguration.class); + assertThat(context).hasSingleBean(IntegrationComponentScanConfiguration.class); }); } @Test public void explicitIntegrationComponentScan() { - this.contextRunner - .withUserConfiguration(CustomIntegrationComponentScanConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TestGateway.class); - assertThat(context) - .doesNotHaveBean(IntegrationComponentScanConfiguration.class); - }); + this.contextRunner.withUserConfiguration(CustomIntegrationComponentScanConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(TestGateway.class); + assertThat(context).doesNotHaveBean(IntegrationComponentScanConfiguration.class); + }); } @Test public void noMBeanServerAvailable() { ApplicationContextRunner contextRunnerWithoutJmx = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(IntegrationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class)); contextRunnerWithoutJmx.run((context) -> { assertThat(context).hasSingleBean(TestGateway.class); - assertThat(context) - .hasSingleBean(IntegrationComponentScanConfiguration.class); + assertThat(context).hasSingleBean(IntegrationComponentScanConfiguration.class); }); } @@ -96,21 +89,17 @@ public class IntegrationAutoConfigurationTests { public void parentContext() { this.contextRunner.run((context) -> this.contextRunner.withParent(context) .withPropertyValues("spring.jmx.default_domain=org.foo") - .run((child) -> assertThat(child) - .hasSingleBean(HeaderChannelRegistry.class))); + .run((child) -> assertThat(child).hasSingleBean(HeaderChannelRegistry.class))); } @Test public void enableJmxIntegration() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=true") - .run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - assertThat(mBeanServer.getDomains()).contains( - "org.springframework.integration", - "org.springframework.integration.monitor"); - assertThat(context).hasBean( - IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME); - }); + this.contextRunner.withPropertyValues("spring.jmx.enabled=true").run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + assertThat(mBeanServer.getDomains()).contains("org.springframework.integration", + "org.springframework.integration.monitor"); + assertThat(context).hasBean(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME); + }); } @Test @@ -123,12 +112,11 @@ public class IntegrationAutoConfigurationTests { @Test public void customizeJmxDomain() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=true", - "spring.jmx.default_domain=org.foo").run((context) -> { + this.contextRunner.withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default_domain=org.foo") + .run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); - assertThat(mBeanServer.getDomains()).contains("org.foo") - .doesNotContain("org.springframework.integration", - "org.springframework.integration.monitor"); + assertThat(mBeanServer.getDomains()).contains("org.foo").doesNotContain( + "org.springframework.integration", "org.springframework.integration.monitor"); }); } @@ -137,68 +125,54 @@ public class IntegrationAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.jmx.enabled=true") .withUserConfiguration(CustomMBeanExporter.class).run((context) -> { assertThat(context).getBeans(MBeanExporter.class).hasSize(2); - assertThat(context.getBean(MBeanExporter.class)) - .isSameAs(context.getBean("myMBeanExporter")); + assertThat(context.getBean(MBeanExporter.class)).isSameAs(context.getBean("myMBeanExporter")); }); } @Test public void integrationJdbcDataSourceInitializerEnabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, - IntegrationAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.integration.jdbc.initialize-schema=always") .run((context) -> { - IntegrationProperties properties = context - .getBean(IntegrationProperties.class); + IntegrationProperties properties = context.getBean(IntegrationProperties.class); assertThat(properties.getJdbc().getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.ALWAYS); JdbcOperations jdbc = context.getBean(JdbcOperations.class); assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")) - .isEmpty(); - assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")) - .isEmpty(); + assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")) - .isEmpty(); + assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); }); } @Test public void integrationJdbcDataSourceInitializerDisabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, - IntegrationAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.integration.jdbc.initialize-schema=never") .run((context) -> { - IntegrationProperties properties = context - .getBean(IntegrationProperties.class); + IntegrationProperties properties = context.getBean(IntegrationProperties.class); assertThat(properties.getJdbc().getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.NEVER); JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> jdbc.queryForList("select * from INT_MESSAGE")); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> jdbc.queryForList("select * from INT_MESSAGE")); }); } @Test public void integrationJdbcDataSourceInitializerEnabledByDefaultWithEmbeddedDb() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, - IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true") - .run((context) -> { - IntegrationProperties properties = context - .getBean(IntegrationProperties.class); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true").run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); assertThat(properties.getJdbc().getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.EMBEDDED); JdbcOperations jdbc = context.getBean(JdbcOperations.class); @@ -208,12 +182,10 @@ public class IntegrationAutoConfigurationTests { @Test public void integrationEnablesDefaultCounts() { - this.contextRunner.withUserConfiguration(MessageSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("myMessageSource"); - assertThat(((MessageProcessorMessageSource) context - .getBean("myMessageSource")).isCountsEnabled()).isTrue(); - }); + this.contextRunner.withUserConfiguration(MessageSourceConfiguration.class).run((context) -> { + assertThat(context).hasBean("myMessageSource"); + assertThat(((MessageProcessorMessageSource) context.getBean("myMessageSource")).isCountsEnabled()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index a98d478f2f3..c3c1f50acc7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -90,12 +90,10 @@ public class JacksonAutoConfigurationTests { @Test public void doubleModuleRegistration() { this.contextRunner.withUserConfiguration(DoubleModulesConfig.class) - .withConfiguration(AutoConfigurations - .of(HttpMessageConvertersAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.writeValueAsString(new Foo())) - .isEqualTo("{\"foo\":\"bar\"}"); + assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); }); } @@ -109,30 +107,23 @@ public class JacksonAutoConfigurationTests { @Test public void customDateFormat() { - this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - DateFormat dateFormat = mapper.getDateFormat(); - assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class); - assertThat(((SimpleDateFormat) dateFormat).toPattern()) - .isEqualTo("yyyyMMddHHmmss"); - }); + this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + DateFormat dateFormat = mapper.getDateFormat(); + assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class); + assertThat(((SimpleDateFormat) dateFormat).toPattern()).isEqualTo("yyyyMMddHHmmss"); + }); } @Test public void customJodaDateTimeFormat() throws Exception { - this.contextRunner - .withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss", - "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss", + "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, - DateTimeZone.UTC); - assertThat(mapper.writeValueAsString(dateTime)) - .isEqualTo("\"1988-06-25 20:30:00\""); + DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); + assertThat(mapper.writeValueAsString(dateTime)).isEqualTo("\"1988-06-25 20:30:00\""); Date date = dateTime.toDate(); - assertThat(mapper.writeValueAsString(date)) - .isEqualTo("\"19880625203000\""); + assertThat(mapper.writeValueAsString(date)).isEqualTo("\"19880625203000\""); }); } @@ -156,13 +147,10 @@ public class JacksonAutoConfigurationTests { @Test public void customPropertyNamingStrategyField() { - this.contextRunner - .withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy()) - .isInstanceOf(SnakeCaseStrategy.class); - }); + this.contextRunner.withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); + }); } @Test @@ -171,191 +159,139 @@ public class JacksonAutoConfigurationTests { "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy()) - .isInstanceOf(SnakeCaseStrategy.class); + assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); }); } @Test public void enableSerializationFeature() { - this.contextRunner - .withPropertyValues("spring.jackson.serialization.indent_output:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()) - .isFalse(); - assertThat(mapper.getSerializationConfig().hasSerializationFeatures( - SerializationFeature.INDENT_OUTPUT.getMask())).isTrue(); - }); + this.contextRunner.withPropertyValues("spring.jackson.serialization.indent_output:true").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); + assertThat(mapper.getSerializationConfig() + .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())).isTrue(); + }); } @Test public void disableSerializationFeature() { - this.contextRunner - .withPropertyValues( - "spring.jackson.serialization.write_dates_as_timestamps:false") + this.contextRunner.withPropertyValues("spring.jackson.serialization.write_dates_as_timestamps:false") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS - .enabledByDefault()).isTrue(); - assertThat(mapper.getSerializationConfig().hasSerializationFeatures( - SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())) + assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()).isTrue(); + assertThat(mapper.getSerializationConfig() + .hasSerializationFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())) .isFalse(); }); } @Test public void enableDeserializationFeature() { - this.contextRunner - .withPropertyValues( - "spring.jackson.deserialization.use_big_decimal_for_floats:true") + this.contextRunner.withPropertyValues("spring.jackson.deserialization.use_big_decimal_for_floats:true") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS - .enabledByDefault()).isFalse(); - assertThat( - mapper.getDeserializationConfig().hasDeserializationFeatures( - DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS - .getMask())).isTrue(); + assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()).isFalse(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())) + .isTrue(); }); } @Test public void disableDeserializationFeature() { - this.contextRunner - .withPropertyValues( - "spring.jackson.deserialization.fail-on-unknown-properties:false") + this.contextRunner.withPropertyValues("spring.jackson.deserialization.fail-on-unknown-properties:false") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES - .enabledByDefault()).isTrue(); - assertThat( - mapper.getDeserializationConfig().hasDeserializationFeatures( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES - .getMask())).isFalse(); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())) + .isFalse(); }); } @Test public void enableMapperFeature() { - this.contextRunner - .withPropertyValues( - "spring.jackson.mapper.require_setters_for_getters:true") + this.contextRunner.withPropertyValues("spring.jackson.mapper.require_setters_for_getters:true") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat( - MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()) - .isFalse(); - assertThat(mapper.getSerializationConfig().hasMapperFeatures( - MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) - .isTrue(); - assertThat(mapper.getDeserializationConfig().hasMapperFeatures( - MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) - .isTrue(); + assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()).isFalse(); + assertThat(mapper.getSerializationConfig() + .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())).isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())).isTrue(); }); } @Test public void disableMapperFeature() { - this.contextRunner - .withPropertyValues("spring.jackson.mapper.use_annotations:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())) - .isFalse(); - assertThat(mapper.getSerializationConfig() - .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())) - .isFalse(); - }); + this.contextRunner.withPropertyValues("spring.jackson.mapper.use_annotations:false").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig().hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())) + .isFalse(); + assertThat(mapper.getSerializationConfig().hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())) + .isFalse(); + }); } @Test public void enableParserFeature() { - this.contextRunner - .withPropertyValues("spring.jackson.parser.allow_single_quotes:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()) - .isFalse(); - assertThat(mapper.getFactory() - .isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)).isTrue(); - }); + this.contextRunner.withPropertyValues("spring.jackson.parser.allow_single_quotes:true").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)).isTrue(); + }); } @Test public void disableParserFeature() { - this.contextRunner - .withPropertyValues("spring.jackson.parser.auto_close_source:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()) - .isTrue(); - assertThat(mapper.getFactory() - .isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse(); - }); + this.contextRunner.withPropertyValues("spring.jackson.parser.auto_close_source:false").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse(); + }); } @Test public void enableGeneratorFeature() { - this.contextRunner - .withPropertyValues( - "spring.jackson.generator.write_numbers_as_strings:true") + this.contextRunner.withPropertyValues("spring.jackson.generator.write_numbers_as_strings:true") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS - .enabledByDefault()).isFalse(); - assertThat(mapper.getFactory() - .isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)) - .isTrue(); + assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()).isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); }); } @Test public void disableGeneratorFeature() { - this.contextRunner - .withPropertyValues("spring.jackson.generator.auto_close_target:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()) - .isTrue(); - assertThat(mapper.getFactory() - .isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) - .isFalse(); - }); + this.contextRunner.withPropertyValues("spring.jackson.generator.auto_close_target:false").run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)).isFalse(); + }); } @Test public void defaultObjectMapperBuilder() { this.contextRunner.run((context) -> { - Jackson2ObjectMapperBuilder builder = context - .getBean(Jackson2ObjectMapperBuilder.class); + Jackson2ObjectMapperBuilder builder = context.getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); - assertThat(mapper.getSerializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); - assertThat( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) - .isTrue(); - assertThat(mapper.getDeserializationConfig() - .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) - .isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) + .isFalse(); }); } @Test public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { this.contextRunner.withUserConfiguration(ModuleConfig.class).run((context) -> { - ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class) - .build(); - assertThat(context.getBean(CustomModule.class).getOwners()) - .contains((ObjectCodec) objectMapper); + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); + assertThat(context.getBean(CustomModule.class).getOwners()).contains((ObjectCodec) objectMapper); assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); assertThat(objectMapper.canSerialize(Baz.class)).isTrue(); }); @@ -364,86 +300,68 @@ public class JacksonAutoConfigurationTests { @Test public void defaultSerializationInclusion() { this.contextRunner.run((context) -> { - ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class) - .build(); - assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion() - .getValueInclusion()).isEqualTo(JsonInclude.Include.USE_DEFAULTS); + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); + assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) + .isEqualTo(JsonInclude.Include.USE_DEFAULTS); }); } @Test public void customSerializationInclusion() { - this.contextRunner - .withPropertyValues("spring.jackson.default-property-inclusion:non_null") - .run((context) -> { - ObjectMapper objectMapper = context - .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(objectMapper.getSerializationConfig() - .getDefaultPropertyInclusion().getValueInclusion()) - .isEqualTo(JsonInclude.Include.NON_NULL); - }); + this.contextRunner.withPropertyValues("spring.jackson.default-property-inclusion:non_null").run((context) -> { + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); + assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) + .isEqualTo(JsonInclude.Include.NON_NULL); + }); } @Test public void customTimeZoneFormattingADateTime() { - this.contextRunner - .withPropertyValues("spring.jackson.time-zone:America/Los_Angeles", - "spring.jackson.date-format:zzzz", "spring.jackson.locale:en") - .run((context) -> { - ObjectMapper objectMapper = context - .getBean(Jackson2ObjectMapperBuilder.class).build(); + this.contextRunner.withPropertyValues("spring.jackson.time-zone:America/Los_Angeles", + "spring.jackson.date-format:zzzz", "spring.jackson.locale:en").run((context) -> { + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); - assertThat(objectMapper.writeValueAsString(dateTime)) - .isEqualTo("\"Pacific Daylight Time\""); + assertThat(objectMapper.writeValueAsString(dateTime)).isEqualTo("\"Pacific Daylight Time\""); }); } @Test public void customTimeZoneFormattingADate() throws JsonProcessingException { - this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", - "spring.jackson.date-format:z").run((context) -> { - ObjectMapper objectMapper = context - .getBean(Jackson2ObjectMapperBuilder.class).build(); + this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", "spring.jackson.date-format:z") + .run((context) -> { + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); Date date = new Date(1436966242231L); - assertThat(objectMapper.writeValueAsString(date)) - .isEqualTo("\"GMT+10:00\""); + assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); }); } @Test public void customLocaleWithJodaTime() throws JsonProcessingException { - this.contextRunner - .withPropertyValues("spring.jackson.locale:de_DE", - "spring.jackson.date-format:zzzz", - "spring.jackson.serialization.write-dates-with-zone-id:true") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.jackson.locale:de_DE", "spring.jackson.date-format:zzzz", + "spring.jackson.serialization.write-dates-with-zone-id:true").run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - DateTime jodaTime = new DateTime(1478424650000L, - DateTimeZone.forID("Europe/Rome")); - assertThat(objectMapper.writeValueAsString(jodaTime)) - .startsWith("\"Mitteleuropäische "); + DateTime jodaTime = new DateTime(1478424650000L, DateTimeZone.forID("Europe/Rome")); + assertThat(objectMapper.writeValueAsString(jodaTime)).startsWith("\"Mitteleuropäische "); }); } @Test public void additionalJacksonBuilderCustomization() { - this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class) - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); - }); + this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class).run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); + }); } @Test public void parameterNamesModuleIsAutoConfigured() { - assertParameterNamesModuleCreatorBinding(Mode.DEFAULT, - JacksonAutoConfiguration.class); + assertParameterNamesModuleCreatorBinding(Mode.DEFAULT, JacksonAutoConfiguration.class); } @Test public void customParameterNamesModuleCanBeConfigured() { - assertParameterNamesModuleCreatorBinding(Mode.DELEGATING, - ParameterNamesModuleConfig.class, JacksonAutoConfiguration.class); + assertParameterNamesModuleCreatorBinding(Mode.DELEGATING, ParameterNamesModuleConfig.class, + JacksonAutoConfiguration.class); } @Test @@ -451,17 +369,17 @@ public class JacksonAutoConfigurationTests { this.contextRunner.run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); - String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter() - .withZone(DateTimeZone.UTC).print(dateTime); - assertThat(mapper.writeValueAsString(dateTime)) - .isEqualTo("\"" + expected + "\""); + String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter().withZone(DateTimeZone.UTC) + .print(dateTime); + assertThat(mapper.writeValueAsString(dateTime)).isEqualTo("\"" + expected + "\""); }); } @Test public void writeWithVisibility() { - this.contextRunner.withPropertyValues("spring.jackson.visibility.getter:none", - "spring.jackson.visibility.field:any").run((context) -> { + this.contextRunner + .withPropertyValues("spring.jackson.visibility.getter:none", "spring.jackson.visibility.field:any") + .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); String json = mapper.writeValueAsString(new VisibilityBean()); assertThat(json).contains("property1"); @@ -470,15 +388,13 @@ public class JacksonAutoConfigurationTests { }); } - private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, - Class... configClasses) { + private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, Class... configClasses) { this.contextRunner.withUserConfiguration(configClasses).run((context) -> { - DeserializationConfig deserializationConfig = context - .getBean(ObjectMapper.class).getDeserializationConfig(); - AnnotationIntrospector annotationIntrospector = deserializationConfig - .getAnnotationIntrospector().allIntrospectors().iterator().next(); - assertThat(annotationIntrospector) - .hasFieldOrPropertyWithValue("creatorBinding", expectedMode); + DeserializationConfig deserializationConfig = context.getBean(ObjectMapper.class) + .getDeserializationConfig(); + AnnotationIntrospector annotationIntrospector = deserializationConfig.getAnnotationIntrospector() + .allIntrospectors().iterator().next(); + assertThat(annotationIntrospector).hasFieldOrPropertyWithValue("creatorBinding", expectedMode); }); } @@ -521,8 +437,7 @@ public class JacksonAutoConfigurationTests { module.addSerializer(Foo.class, new JsonSerializer() { @Override - public void serialize(Foo value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + public void serialize(Foo value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeStringField("foo", "bar"); jgen.writeEndObject(); @@ -600,8 +515,7 @@ public class JacksonAutoConfigurationTests { private static class BazSerializer extends JsonObjectSerializer { @Override - protected void serializeObject(Baz value, JsonGenerator jgen, - SerializerProvider provider) { + protected void serializeObject(Baz value, JsonGenerator jgen, SerializerProvider provider) { } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index c952521b11b..48447a02f91 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -63,13 +63,11 @@ public class DataSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withPropertyValues("spring.datasource.initialization-mode=never", - "spring.datasource.url:jdbc:hsqldb:mem:testdb-" - + new Random().nextInt()); + "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); @Test public void testDefaultDataSourceExists() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(DataSource.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DataSource.class)); } @Test @@ -83,55 +81,44 @@ public class DataSourceAutoConfigurationTests { @Test public void testBadUrl() { - this.contextRunner - .withPropertyValues("spring.datasource.url:jdbc:not-going-to-work") + this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:not-going-to-work") .withClassLoader(new DisableEmbeddedDatabaseClassLoader()) - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class)); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test public void testBadDriverClass() { - this.contextRunner - .withPropertyValues( - "spring.datasource.driverClassName:org.none.jdbcDriver") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) + this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.none.jdbcDriver") + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("org.none.jdbcDriver")); } @Test public void hikariValidatesConnectionByDefault() { - assertDataSource(HikariDataSource.class, - Collections.singletonList("org.apache.tomcat"), (dataSource) -> - // Use Connection#isValid() - assertThat(dataSource.getConnectionTestQuery()).isNull()); + assertDataSource(HikariDataSource.class, Collections.singletonList("org.apache.tomcat"), (dataSource) -> + // Use Connection#isValid() + assertThat(dataSource.getConnectionTestQuery()).isNull()); } @Test public void tomcatIsFallback() { - assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, - Collections.singletonList("com.zaxxer.hikari"), - (dataSource) -> assertThat(dataSource.getUrl()) - .startsWith("jdbc:hsqldb:mem:testdb")); + assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, Collections.singletonList("com.zaxxer.hikari"), + (dataSource) -> assertThat(dataSource.getUrl()).startsWith("jdbc:hsqldb:mem:testdb")); } @Test public void tomcatValidatesConnectionByDefault() { - assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, - Collections.singletonList("com.zaxxer.hikari"), (dataSource) -> { + assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, Collections.singletonList("com.zaxxer.hikari"), + (dataSource) -> { assertThat(dataSource.isTestOnBorrow()).isTrue(); - assertThat(dataSource.getValidationQuery()) - .isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); + assertThat(dataSource.getValidationQuery()).isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); }); } @Test public void commonsDbcp2IsFallback() { - assertDataSource(BasicDataSource.class, - Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), - (dataSource) -> assertThat(dataSource.getUrl()) - .startsWith("jdbc:hsqldb:mem:testdb")); + assertDataSource(BasicDataSource.class, Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), + (dataSource) -> assertThat(dataSource.getUrl()).startsWith("jdbc:hsqldb:mem:testdb")); } @Test @@ -147,13 +134,11 @@ public class DataSourceAutoConfigurationTests { @Test @SuppressWarnings("resource") public void testEmbeddedTypeDefaultsUsername() { - this.contextRunner.withPropertyValues( - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb").run((context) -> { DataSource bean = context.getBean(DataSource.class); HikariDataSource pool = (HikariDataSource) bean; - assertThat(pool.getDriverClassName()) - .isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(pool.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); assertThat(pool.getUsername()).isEqualTo("sa"); }); } @@ -165,44 +150,35 @@ public class DataSourceAutoConfigurationTests { @Test public void explicitTypeNoSupportedDataSource() { this.contextRunner - .withClassLoader( - new FilteredClassLoader("org.apache.tomcat", "com.zaxxer.hikari", - "org.apache.commons.dbcp", "org.apache.commons.dbcp2")) - .withPropertyValues( - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + .withClassLoader(new FilteredClassLoader("org.apache.tomcat", "com.zaxxer.hikari", + "org.apache.commons.dbcp", "org.apache.commons.dbcp2")) + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", - "spring.datasource.type:" - + SimpleDriverDataSource.class.getName()) + "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) .run(this::containsOnlySimpleDriverDataSource); } @Test public void explicitTypeSupportedDataSource() { this.contextRunner - .withPropertyValues( - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", - "spring.datasource.type:" - + SimpleDriverDataSource.class.getName()) + "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) .run(this::containsOnlySimpleDriverDataSource); } - private void containsOnlySimpleDriverDataSource( - AssertableApplicationContext context) { + private void containsOnlySimpleDriverDataSource(AssertableApplicationContext context) { assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).getBean(DataSource.class) - .isExactlyInstanceOf(SimpleDriverDataSource.class); + assertThat(context).getBean(DataSource.class).isExactlyInstanceOf(SimpleDriverDataSource.class); } @Test public void testExplicitDriverClassClearsUsername() { - this.contextRunner.withPropertyValues( - "spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), + this.contextRunner.withPropertyValues("spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), "spring.datasource.url:jdbc:foo://localhost").run((context) -> { assertThat(context).hasSingleBean(DataSource.class); HikariDataSource dataSource = context.getBean(HikariDataSource.class); - assertThat(dataSource.getDriverClassName()) - .isEqualTo(DatabaseTestDriver.class.getName()); + assertThat(dataSource.getDriverClassName()).isEqualTo(DatabaseTestDriver.class.getName()); assertThat(dataSource.getUsername()).isNull(); }); } @@ -210,24 +186,20 @@ public class DataSourceAutoConfigurationTests { @Test public void testDefaultDataSourceCanBeOverridden() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) - .run((context) -> assertThat(context).getBean(DataSource.class) - .isInstanceOf(BasicDataSource.class)); + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); } @Test public void testDataSourceIsInitializedEarly() { - this.contextRunner - .withUserConfiguration(TestInitializedDataSourceConfiguration.class) + this.contextRunner.withUserConfiguration(TestInitializedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.initialization-mode=always") - .run((context) -> assertThat(context - .getBean(TestInitializedDataSourceConfiguration.class).called) - .isTrue()); + .run((context) -> assertThat(context.getBean(TestInitializedDataSourceConfiguration.class).called) + .isTrue()); } - private void assertDataSource(Class expectedType, - List hiddenPackages, Consumer consumer) { - FilteredClassLoader classLoader = new FilteredClassLoader( - StringUtils.toStringArray(hiddenPackages)); + private void assertDataSource(Class expectedType, List hiddenPackages, + Consumer consumer) { + FilteredClassLoader classLoader = new FilteredClassLoader(StringUtils.toStringArray(hiddenPackages)); this.contextRunner.withClassLoader(classLoader).run((context) -> { DataSource bean = context.getBean(DataSource.class); assertThat(bean).isInstanceOf(expectedType); @@ -260,8 +232,7 @@ public class DataSourceAutoConfigurationTests { public void validateDataSourceIsInitialized(DataSource dataSource) { // Inject the datasource to validate it is initialized at the injection point JdbcTemplate template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) - .isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(1); this.called = true; } @@ -314,10 +285,8 @@ public class DataSourceAutoConfigurationTests { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection - .values()) { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) { if (name.equals(candidate.getDriverClassName())) { throw new ClassNotFoundException(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java index 2eba6101781..609ea8fda93 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java @@ -45,10 +45,8 @@ public class DataSourceBeanCreationFailureAnalyzerTests { @Test public void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); - assertThat(failureAnalysis.getDescription()).contains( - "'url' attribute is not specified", - "no embedded datasource could be configured", - "Failed to determine a suitable driver class"); + assertThat(failureAnalysis.getDescription()).contains("'url' attribute is not specified", + "no embedded datasource could be configured", "Failed to determine a suitable driver class"); assertThat(failureAnalysis.getAction()).contains( "If you want an embedded database (H2, HSQL or Derby), please put it on the classpath", "If you have database settings to be loaded from a particular profile you may need to activate it", @@ -59,8 +57,7 @@ public class DataSourceBeanCreationFailureAnalyzerTests { public void failureAnalysisIsPerformedWithActiveProfiles() { this.environment.setActiveProfiles("first", "second"); FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); - assertThat(failureAnalysis.getAction()) - .contains("(the profiles first,second are currently active)"); + assertThat(failureAnalysis.getAction()).contains("(the profiles first,second are currently active)"); } private FailureAnalysis performAnalysis(Class configuration) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java index 1a46c55a13b..20ed8553103 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java @@ -64,21 +64,18 @@ public class DataSourceInitializerInvokerTests { @Test public void dataSourceInitialized() { - this.contextRunner - .withPropertyValues("spring.datasource.initialization-mode:always") - .run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - DataSource dataSource = context.getBean(DataSource.class); - assertThat(dataSource).isInstanceOf(HikariDataSource.class); - assertDataSourceIsInitialized(dataSource); - }); + this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always").run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + DataSource dataSource = context.getBean(DataSource.class); + assertThat(dataSource).isInstanceOf(HikariDataSource.class); + assertDataSourceIsInitialized(dataSource); + }); } @Test public void initializationAppliesToCustomDataSource() { this.contextRunner.withUserConfiguration(OneDataSource.class) - .withPropertyValues("spring.datasource.initialization-mode:always") - .run((context) -> { + .withPropertyValues("spring.datasource.initialization-mode:always").run((context) -> { assertThat(context).hasSingleBean(DataSource.class); assertDataSourceIsInitialized(context.getBean(DataSource.class)); }); @@ -86,66 +83,52 @@ public class DataSourceInitializerInvokerTests { private void assertDataSourceIsInitialized(DataSource dataSource) { JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) - .isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(1); } @Test public void dataSourceInitializedWithExplicitScript() { - this.contextRunner - .withPropertyValues("spring.datasource.initialization-mode:always", - "spring.datasource.schema:" - + getRelativeLocationFor("schema.sql"), - "spring.datasource.data:" + getRelativeLocationFor("data.sql")) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.schema:" + getRelativeLocationFor("schema.sql"), + "spring.datasource.data:" + getRelativeLocationFor("data.sql")).run((context) -> { DataSource dataSource = context.getBean(DataSource.class); assertThat(dataSource).isInstanceOf(HikariDataSource.class); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from FOO", - Integer.class)).isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)).isEqualTo(1); }); } @Test public void dataSourceInitializedWithMultipleScripts() { - this.contextRunner - .withPropertyValues("spring.datasource.initialization-mode:always", - "spring.datasource.schema:" + getRelativeLocationFor("schema.sql") - + "," + getRelativeLocationFor("another.sql"), - "spring.datasource.data:" + getRelativeLocationFor("data.sql")) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.schema:" + getRelativeLocationFor("schema.sql") + "," + + getRelativeLocationFor("another.sql"), + "spring.datasource.data:" + getRelativeLocationFor("data.sql")).run((context) -> { DataSource dataSource = context.getBean(DataSource.class); assertThat(dataSource).isInstanceOf(HikariDataSource.class); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from FOO", - Integer.class)).isEqualTo(1); - assertThat(template.queryForObject("SELECT COUNT(*) from SPAM", - Integer.class)).isEqualTo(0); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)).isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from SPAM", Integer.class)).isEqualTo(0); }); } @Test public void dataSourceInitializedWithExplicitSqlScriptEncoding() { - this.contextRunner - .withPropertyValues("spring.datasource.initialization-mode:always", - "spring.datasource.sqlScriptEncoding:UTF-8", - "spring.datasource.schema:" - + getRelativeLocationFor("encoding-schema.sql"), - "spring.datasource.data:" - + getRelativeLocationFor("encoding-data.sql")) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.sqlScriptEncoding:UTF-8", + "spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"), + "spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql")).run((context) -> { DataSource dataSource = context.getBean(DataSource.class); assertThat(dataSource).isInstanceOf(HikariDataSource.class); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from BAR", - Integer.class)).isEqualTo(2); - assertThat(template.queryForObject("SELECT name from BAR WHERE id=1", - String.class)).isEqualTo("bar"); - assertThat(template.queryForObject("SELECT name from BAR WHERE id=2", - String.class)).isEqualTo("ばー"); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(2); + assertThat(template.queryForObject("SELECT name from BAR WHERE id=1", String.class)) + .isEqualTo("bar"); + assertThat(template.queryForObject("SELECT name from BAR WHERE id=2", String.class)) + .isEqualTo("ばー"); }); } @@ -157,13 +140,10 @@ public class DataSourceInitializerInvokerTests { @Test public void initializationDoesNotApplyWithSeveralDataSources() { this.contextRunner.withUserConfiguration(TwoDataSources.class) - .withPropertyValues("spring.datasource.initialization-mode:always") - .run((context) -> { + .withPropertyValues("spring.datasource.initialization-mode:always").run((context) -> { assertThat(context.getBeanNamesForType(DataSource.class)).hasSize(2); - assertDataSourceNotInitialized( - context.getBean("oneDataSource", DataSource.class)); - assertDataSourceNotInitialized( - context.getBean("twoDataSource", DataSource.class)); + assertDataSourceNotInitialized(context.getBean("oneDataSource", DataSource.class)); + assertDataSourceNotInitialized(context.getBean("twoDataSource", DataSource.class)); }); } @@ -178,8 +158,8 @@ public class DataSourceInitializerInvokerTests { private void assertDataSourceNotInitialized(DataSource dataSource) { JdbcOperations template = new JdbcTemplate(dataSource); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) .satisfies((ex) -> { SQLException sqlException = ex.getSQLException(); int expectedCode = -5501; // user lacks privilege or object not found @@ -189,33 +169,29 @@ public class DataSourceInitializerInvokerTests { @Test public void dataSourceInitializedWithSchemaCredentials() { - this.contextRunner.withPropertyValues( - "spring.datasource.initialization-mode:always", - "spring.datasource.sqlScriptEncoding:UTF-8", - "spring.datasource.schema:" - + getRelativeLocationFor("encoding-schema.sql"), - "spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql"), - "spring.datasource.schema-username:admin", - "spring.datasource.schema-password:admin").run((context) -> { + this.contextRunner + .withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.sqlScriptEncoding:UTF-8", + "spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"), + "spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql"), + "spring.datasource.schema-username:admin", "spring.datasource.schema-password:admin") + .run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class); }); } @Test public void dataSourceInitializedWithDataCredentials() { - this.contextRunner.withPropertyValues( - "spring.datasource.initialization-mode:always", - "spring.datasource.sqlScriptEncoding:UTF-8", - "spring.datasource.schema:" - + getRelativeLocationFor("encoding-schema.sql"), - "spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql"), - "spring.datasource.data-username:admin", - "spring.datasource.data-password:admin").run((context) -> { + this.contextRunner + .withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.sqlScriptEncoding:UTF-8", + "spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"), + "spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql"), + "spring.datasource.data-username:admin", "spring.datasource.data-password:admin") + .run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class); }); } @@ -223,58 +199,42 @@ public class DataSourceInitializerInvokerTests { public void multipleScriptsAppliedInLexicalOrder() { new ApplicationContextRunner(() -> { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.setResourceLoader( - new ReverseOrderResourceLoader(new DefaultResourceLoader())); + context.setResourceLoader(new ReverseOrderResourceLoader(new DefaultResourceLoader())); return context; }).withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withPropertyValues("spring.datasource.initialization-mode=always", - "spring.datasource.url:jdbc:hsqldb:mem:testdb-" - + new Random().nextInt(), - "spring.datasource.schema:classpath*:" - + getRelativeLocationFor("lexical-schema-*.sql"), - "spring.datasource.data:classpath*:" - + getRelativeLocationFor("data.sql")) + "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt(), + "spring.datasource.schema:classpath*:" + getRelativeLocationFor("lexical-schema-*.sql"), + "spring.datasource.data:classpath*:" + getRelativeLocationFor("data.sql")) .run((context) -> { DataSource dataSource = context.getBean(DataSource.class); assertThat(dataSource).isInstanceOf(HikariDataSource.class); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from FOO", - Integer.class)).isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)).isEqualTo(1); }); } @Test public void testDataSourceInitializedWithInvalidSchemaResource() { - this.contextRunner - .withPropertyValues("spring.datasource.initialization-mode:always", - "spring.datasource.schema:classpath:does/not/exist.sql") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.schema:classpath:does/not/exist.sql").run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class); - assertThat(context.getStartupFailure()) - .hasMessageContaining("does/not/exist.sql"); - assertThat(context.getStartupFailure()) - .hasMessageContaining("spring.datasource.schema"); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class); + assertThat(context.getStartupFailure()).hasMessageContaining("does/not/exist.sql"); + assertThat(context.getStartupFailure()).hasMessageContaining("spring.datasource.schema"); }); } @Test public void dataSourceInitializedWithInvalidDataResource() { - this.contextRunner - .withPropertyValues("spring.datasource.initialization-mode:always", - "spring.datasource.schema:" - + getRelativeLocationFor("schema.sql"), - "spring.datasource.data:classpath:does/not/exist.sql") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", + "spring.datasource.schema:" + getRelativeLocationFor("schema.sql"), + "spring.datasource.data:classpath:does/not/exist.sql").run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class); - assertThat(context.getStartupFailure()) - .hasMessageContaining("does/not/exist.sql"); - assertThat(context.getStartupFailure()) - .hasMessageContaining("spring.datasource.data"); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class); + assertThat(context.getStartupFailure()).hasMessageContaining("does/not/exist.sql"); + assertThat(context.getStartupFailure()).hasMessageContaining("spring.datasource.data"); }); } @@ -327,8 +287,7 @@ public class DataSourceInitializerInvokerTests { @Override public Resource[] getResources(String locationPattern) throws IOException { Resource[] resources = this.resolver.getResources(locationPattern); - Arrays.sort(resources, - Comparator.comparing(Resource::getFilename).reversed()); + Arrays.sort(resources, Comparator.comparing(Resource::getFilename).reversed()); return resources; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java index f201385ce67..f01c3cb12d5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java @@ -45,8 +45,7 @@ public class DataSourceInitializerTests { @Test public void initializeEmbeddedByDefault() { try (HikariDataSource dataSource = createDataSource()) { - DataSourceInitializer initializer = new DataSourceInitializer(dataSource, - new DataSourceProperties()); + DataSourceInitializer initializer = new DataSourceInitializer(dataSource, new DataSourceProperties()); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); assertThat(initializer.createSchema()).isTrue(); assertNumberOfRows(jdbcTemplate, 0); @@ -60,8 +59,7 @@ public class DataSourceInitializerTests { try (HikariDataSource dataSource = createDataSource()) { DataSourceProperties properties = new DataSourceProperties(); properties.setInitializationMode(DataSourceInitializationMode.ALWAYS); - DataSourceInitializer initializer = new DataSourceInitializer(dataSource, - properties); + DataSourceInitializer initializer = new DataSourceInitializer(dataSource, properties); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); assertThat(initializer.createSchema()).isTrue(); assertNumberOfRows(jdbcTemplate, 0); @@ -71,8 +69,7 @@ public class DataSourceInitializerTests { } private void assertNumberOfRows(JdbcTemplate jdbcTemplate, int count) { - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) - .isEqualTo(count); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(count); } @Test @@ -80,8 +77,7 @@ public class DataSourceInitializerTests { try (HikariDataSource dataSource = createDataSource()) { DataSourceProperties properties = new DataSourceProperties(); properties.setInitializationMode(DataSourceInitializationMode.NEVER); - DataSourceInitializer initializer = new DataSourceInitializer(dataSource, - properties); + DataSourceInitializer initializer = new DataSourceInitializer(dataSource, properties); assertThat(initializer.createSchema()).isFalse(); } } @@ -94,15 +90,13 @@ public class DataSourceInitializerTests { given(connection.getMetaData()).willReturn(metadata); DataSource dataSource = mock(DataSource.class); given(dataSource.getConnection()).willReturn(connection); - DataSourceInitializer initializer = new DataSourceInitializer(dataSource, - new DataSourceProperties()); + DataSourceInitializer initializer = new DataSourceInitializer(dataSource, new DataSourceProperties()); assertThat(initializer.createSchema()).isFalse(); verify(dataSource).getConnection(); } private HikariDataSource createDataSource() { - return DataSourceBuilder.create().type(HikariDataSource.class) - .url("jdbc:h2:mem:" + UUID.randomUUID()).build(); + return DataSourceBuilder.create().type(HikariDataSource.class).url("jdbc:h2:mem:" + UUID.randomUUID()).build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java index 3734d773a40..f674ae108ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java @@ -51,10 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; public class DataSourceJmxConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.url=" + "jdbc:hsqldb:mem:test-" - + UUID.randomUUID()) - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, - DataSourceAutoConfiguration.class)); + .withPropertyValues("spring.datasource.url=" + "jdbc:hsqldb:mem:test-" + UUID.randomUUID()) + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, DataSourceAutoConfiguration.class)); @Test public void hikariAutoConfiguredCanUseRegisterMBeans() { @@ -62,55 +60,42 @@ public class DataSourceJmxConfigurationTests { this.contextRunner .withPropertyValues("spring.jmx.enabled=true", "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true") + "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") .run((context) -> { assertThat(context).hasSingleBean(HikariDataSource.class); - assertThat(context.getBean(HikariDataSource.class).isRegisterMbeans()) - .isTrue(); + assertThat(context.getBean(HikariDataSource.class).isRegisterMbeans()).isTrue(); MBeanServer mBeanServer = context.getBean(MBeanServer.class); validateHikariMBeansRegistration(mBeanServer, poolName, true); }); } @Test - public void hikariAutoConfiguredWithoutDataSourceName() - throws MalformedObjectNameException { + public void hikariAutoConfiguredWithoutDataSourceName() throws MalformedObjectNameException { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); - Set existingInstances = mBeanServer - .queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null); - this.contextRunner - .withPropertyValues( - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.hikari.register-mbeans=true") - .run((context) -> { + Set existingInstances = mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), + null); + this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.hikari.register-mbeans=true").run((context) -> { assertThat(context).hasSingleBean(HikariDataSource.class); - assertThat(context.getBean(HikariDataSource.class).isRegisterMbeans()) - .isTrue(); + assertThat(context.getBean(HikariDataSource.class).isRegisterMbeans()).isTrue(); // We can't rely on the number of MBeans so we're checking that the // pool and pool // config MBeans were registered - assertThat(mBeanServer - .queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null) - .size()).isEqualTo(existingInstances.size() + 2); + assertThat(mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null).size()) + .isEqualTo(existingInstances.size() + 2); }); } @Test public void hikariAutoConfiguredUsesJmsFlag() { String poolName = UUID.randomUUID().toString(); - this.contextRunner - .withPropertyValues( - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, + "spring.datasource.hikari.register-mbeans=true").run((context) -> { assertThat(context).hasSingleBean(HikariDataSource.class); - assertThat(context.getBean(HikariDataSource.class).isRegisterMbeans()) - .isTrue(); + assertThat(context.getBean(HikariDataSource.class).isRegisterMbeans()).isTrue(); // Hikari can still register mBeans - validateHikariMBeansRegistration( - ManagementFactory.getPlatformMBeanServer(), poolName, true); + validateHikariMBeansRegistration(ManagementFactory.getPlatformMBeanServer(), poolName, true); }); } @@ -120,12 +105,10 @@ public class DataSourceJmxConfigurationTests { this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) .withPropertyValues("spring.jmx.enabled=true", "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true") + "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") .run((context) -> { assertThat(context).hasSingleBean(javax.sql.DataSource.class); - HikariDataSource hikariDataSource = context - .getBean(javax.sql.DataSource.class) + HikariDataSource hikariDataSource = context.getBean(javax.sql.DataSource.class) .unwrap(HikariDataSource.class); assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); MBeanServer mBeanServer = context.getBean(MBeanServer.class); @@ -133,61 +116,50 @@ public class DataSourceJmxConfigurationTests { }); } - private void validateHikariMBeansRegistration(MBeanServer mBeanServer, - String poolName, boolean expected) throws MalformedObjectNameException { - assertThat(mBeanServer.isRegistered( - new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")"))) - .isEqualTo(expected); - assertThat(mBeanServer.isRegistered( - new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")"))) - .isEqualTo(expected); + private void validateHikariMBeansRegistration(MBeanServer mBeanServer, String poolName, boolean expected) + throws MalformedObjectNameException { + assertThat(mBeanServer.isRegistered(new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")"))) + .isEqualTo(expected); + assertThat(mBeanServer.isRegistered(new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")"))) + .isEqualTo(expected); } @Test public void tomcatDoesNotExposeMBeanPoolByDefault() { - this.contextRunner - .withPropertyValues( - "spring.datasource.type=" + DataSource.class.getName()) - .run((context) -> assertThat(context) - .doesNotHaveBean(ConnectionPool.class)); + this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName()) + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionPool.class)); } @Test public void tomcatAutoConfiguredCanExposeMBeanPool() { - this.contextRunner.withPropertyValues( - "spring.datasource.type=" + DataSource.class.getName(), + this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), "spring.datasource.tomcat.jmx-enabled=true").run((context) -> { assertThat(context).hasBean("dataSourceMBean"); assertThat(context).hasSingleBean(ConnectionPool.class); - assertThat(context.getBean(DataSourceProxy.class).createPool() - .getJmxPool()) - .isSameAs(context.getBean(ConnectionPool.class)); + assertThat(context.getBean(DataSourceProxy.class).createPool().getJmxPool()) + .isSameAs(context.getBean(ConnectionPool.class)); }); } @Test public void tomcatProxiedCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) - .withPropertyValues( - "spring.datasource.type=" + DataSource.class.getName(), + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), "spring.datasource.tomcat.jmx-enabled=true") .run((context) -> { assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).getBean("dataSourceMBean") - .isInstanceOf(ConnectionPool.class); + assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); }); } @Test public void tomcatDelegateCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceDelegateConfiguration.class) - .withPropertyValues( - "spring.datasource.type=" + DataSource.class.getName(), + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), "spring.datasource.tomcat.jmx-enabled=true") .run((context) -> { assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).getBean("dataSourceMBean") - .isInstanceOf(ConnectionPool.class); + assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); }); } @@ -220,8 +192,7 @@ public class DataSourceJmxConfigurationTests { public static DataSourceBeanPostProcessor dataSourceBeanPostProcessor() { return new DataSourceBeanPostProcessor() { @Override - public Object postProcessAfterInitialization(Object bean, - String beanName) { + public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof javax.sql.DataSource) { return new DelegatingDataSource((javax.sql.DataSource) bean); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java index 142e961a29b..424c117365d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java @@ -83,17 +83,13 @@ public class DataSourceJsonSerializationTests { private ConversionService conversionService = new DefaultConversionService(); @Override - public void serialize(DataSource value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + public void serialize(DataSource value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); - for (PropertyDescriptor property : BeanUtils - .getPropertyDescriptors(DataSource.class)) { + for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(DataSource.class)) { Method reader = property.getReadMethod(); if (reader != null && property.getWriteMethod() != null - && this.conversionService.canConvert(String.class, - property.getPropertyType())) { - jgen.writeObjectField(property.getName(), - ReflectionUtils.invokeMethod(reader, value)); + && this.conversionService.canConvert(String.class, property.getPropertyType())) { + jgen.writeObjectField(property.getName(), ReflectionUtils.invokeMethod(reader, value)); } } jgen.writeEndObject(); @@ -106,15 +102,13 @@ public class DataSourceJsonSerializationTests { private ConversionService conversionService = new DefaultConversionService(); @Override - public List changeProperties(SerializationConfig config, - BeanDescription beanDesc, List beanProperties) { + public List changeProperties(SerializationConfig config, BeanDescription beanDesc, + List beanProperties) { List result = new ArrayList<>(); for (BeanPropertyWriter writer : beanProperties) { - AnnotatedMethod setter = beanDesc.findMethod( - "set" + StringUtils.capitalize(writer.getName()), + AnnotatedMethod setter = beanDesc.findMethod("set" + StringUtils.capitalize(writer.getName()), new Class[] { writer.getType().getRawClass() }); - if (setter != null && this.conversionService.canConvert(String.class, - writer.getType().getRawClass())) { + if (setter != null && this.conversionService.canConvert(String.class, writer.getType().getRawClass())) { result.add(writer); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index c89a53d6c70..13abaa3bb0d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -38,8 +38,7 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); assertThat(properties.getDriverClassName()).isNull(); - assertThat(properties.determineDriverClassName()) - .isEqualTo("com.mysql.cj.jdbc.Driver"); + assertThat(properties.determineDriverClassName()).isEqualTo("com.mysql.cj.jdbc.Driver"); } @Test @@ -48,8 +47,7 @@ public class DataSourcePropertiesTests { properties.setUrl("jdbc:mysql://mydb"); properties.setDriverClassName("org.hsqldb.jdbcDriver"); assertThat(properties.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); - assertThat(properties.determineDriverClassName()) - .isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(properties.determineDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); } @Test @@ -57,20 +55,16 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); assertThat(properties.getUrl()).isNull(); - assertThat(properties.determineUrl()) - .isEqualTo(EmbeddedDatabaseConnection.H2.getUrl("testdb")); + assertThat(properties.determineUrl()).isEqualTo(EmbeddedDatabaseConnection.H2.getUrl("testdb")); } @Test public void determineUrlWithNoEmbeddedSupport() throws Exception { DataSourceProperties properties = new DataSourceProperties(); - properties.setBeanClassLoader( - new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); + properties.setBeanClassLoader(new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); properties.afterPropertiesSet(); - assertThatExceptionOfType( - DataSourceProperties.DataSourceBeanCreationException.class) - .isThrownBy(properties::determineUrl) - .withMessageContaining("Failed to determine suitable jdbc url"); + assertThatExceptionOfType(DataSourceProperties.DataSourceBeanCreationException.class) + .isThrownBy(properties::determineUrl).withMessageContaining("Failed to determine suitable jdbc url"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java index 76dc5461f17..f6700dae3fa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java @@ -46,8 +46,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { @Test public void testDataSourceExists() { this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); @@ -55,19 +54,16 @@ public class DataSourceTransactionManagerAutoConfigurationTests { @Test public void testNoDataSourceExists() { - this.context.register(DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(DataSource.class)).isEmpty(); - assertThat(this.context.getBeanNamesForType(DataSourceTransactionManager.class)) - .isEmpty(); + assertThat(this.context.getBeanNamesForType(DataSourceTransactionManager.class)).isEmpty(); } @Test public void testManualConfiguration() { this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); @@ -75,50 +71,40 @@ public class DataSourceTransactionManagerAutoConfigurationTests { @Test public void testExistingTransactionManager() { - this.context.register(TransactionManagerConfiguration.class, - EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(TransactionManagerConfiguration.class, EmbeddedDataSourceConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)).hasSize(1); assertThat(this.context.getBean(PlatformTransactionManager.class)) .isEqualTo(this.context.getBean("myTransactionManager")); } @Test public void testMultiDataSource() { - this.context.register(MultiDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, + this.context.register(MultiDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)).isEmpty(); } @Test public void testMultiDataSourceUsingPrimary() { this.context.register(MultiDataSourceUsingPrimaryConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); - assertThat(this.context.getBean(AbstractTransactionManagementConfiguration.class)) - .isNotNull(); + assertThat(this.context.getBean(AbstractTransactionManagementConfiguration.class)).isNotNull(); } @Test public void testCustomizeDataSourceTransactionManagerUsingProperties() { TestPropertyValues - .of("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") + .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - DataSourceTransactionManager transactionManager = this.context - .getBean(DataSourceTransactionManager.class); + DataSourceTransactionManager transactionManager = this.context.getBean(DataSourceTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java index 4dc2c6b2734..6cc4a341ac3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java @@ -56,12 +56,10 @@ public class EmbeddedDataSourceConfigurationTests { @Test public void generateUniqueName() throws Exception { this.context = load("spring.datasource.generate-unique-name=true"); - try (AnnotationConfigApplicationContext context2 = load( - "spring.datasource.generate-unique-name=true")) { + try (AnnotationConfigApplicationContext context2 = load("spring.datasource.generate-unique-name=true")) { DataSource dataSource = this.context.getBean(DataSource.class); DataSource dataSource2 = context2.getBean(DataSource.class); - assertThat(getDatabaseName(dataSource)) - .isNotEqualTo(getDatabaseName(dataSource2)); + assertThat(getDatabaseName(dataSource)).isNotEqualTo(getDatabaseName(dataSource2)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index 74fce10d2b7..60f21860ffd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -49,8 +49,7 @@ public class HikariDataSourceConfigurationTests { @Test public void testDataSourcePropertiesOverridden() { - this.contextRunner.withPropertyValues( - "spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", + this.contextRunner.withPropertyValues("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", "spring.datasource.hikari.max-lifetime=1234").run((context) -> { HikariDataSource ds = context.getBean(HikariDataSource.class); assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); @@ -61,14 +60,12 @@ public class HikariDataSourceConfigurationTests { @Test public void testDataSourceGenericPropertiesOverridden() { - this.contextRunner - .withPropertyValues("spring.datasource.hikari.data-source-properties" - + ".dataSourceClassName=org.h2.JDBCDataSource") + this.contextRunner.withPropertyValues( + "spring.datasource.hikari.data-source-properties" + ".dataSourceClassName=org.h2.JDBCDataSource") .run((context) -> { HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getDataSourceProperties() - .getProperty("dataSourceClassName")) - .isEqualTo("org.h2.JDBCDataSource"); + assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) + .isEqualTo("org.h2.JDBCDataSource"); }); } @@ -83,19 +80,17 @@ public class HikariDataSourceConfigurationTests { @Test public void nameIsAliasedToPoolName() { - this.contextRunner.withPropertyValues("spring.datasource.name=myDS") - .run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getPoolName()).isEqualTo("myDS"); + this.contextRunner.withPropertyValues("spring.datasource.name=myDS").run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getPoolName()).isEqualTo("myDS"); - }); + }); } @Test public void poolNameTakesPrecedenceOverName() { this.contextRunner - .withPropertyValues("spring.datasource.name=myDS", - "spring.datasource.hikari.pool-name=myHikariDS") + .withPropertyValues("spring.datasource.name=myDS", "spring.datasource.hikari.pool-name=myHikariDS") .run((context) -> { HikariDataSource ds = context.getBean(HikariDataSource.class); assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java index 9b447f2e64e..c7587cd76e2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java @@ -39,11 +39,9 @@ public class HikariDriverConfigurationFailureAnalyzerTests { public void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis).isNotNull(); - assertThat(failureAnalysis.getDescription()) - .isEqualTo("Configuration of the Hikari connection pool failed: " - + "'dataSourceClassName' is not supported."); - assertThat(failureAnalysis.getAction()) - .contains("Spring Boot auto-configures only a driver"); + assertThat(failureAnalysis.getDescription()).isEqualTo( + "Configuration of the Hikari connection pool failed: " + "'dataSourceClassName' is not supported."); + assertThat(failureAnalysis.getAction()).contains("Spring Boot auto-configures only a driver"); } @Test @@ -61,11 +59,9 @@ public class HikariDriverConfigurationFailureAnalyzerTests { private BeanCreationException createFailure(Class configuration) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues - .of("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.hikari.data-source-class-name=com.example.Foo", - "spring.datasource.initialization-mode=always") - .applyTo(context); + TestPropertyValues.of("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.hikari.data-source-class-name=com.example.Foo", + "spring.datasource.initialization-mode=always").applyTo(context); context.register(configuration); try { context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java index f1bb950f2d9..614d95925e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java @@ -50,16 +50,15 @@ public class JdbcTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.initialization-mode=never", "spring.datasource.generate-unique-name=true") - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class)); + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)); @Test public void testJdbcTemplateExists() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); - assertThat(jdbcTemplate.getDataSource()) - .isEqualTo(context.getBean(DataSource.class)); + assertThat(jdbcTemplate.getDataSource()).isEqualTo(context.getBean(DataSource.class)); assertThat(jdbcTemplate.getFetchSize()).isEqualTo(-1); assertThat(jdbcTemplate.getQueryTimeout()).isEqualTo(-1); assertThat(jdbcTemplate.getMaxRows()).isEqualTo(-1); @@ -69,8 +68,7 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testJdbcTemplateWithCustomProperties() { this.contextRunner.withPropertyValues("spring.jdbc.template.fetch-size:100", - "spring.jdbc.template.query-timeout:60", - "spring.jdbc.template.max-rows:1000").run((context) -> { + "spring.jdbc.template.query-timeout:60", "spring.jdbc.template.max-rows:1000").run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); assertThat(jdbcTemplate.getDataSource()).isNotNull(); @@ -82,97 +80,78 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testJdbcTemplateExistsWithCustomDataSource() { - this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JdbcOperations.class); - JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); - assertThat(jdbcTemplate.getDataSource()) - .isEqualTo(context.getBean("customDataSource")); - }); + this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(JdbcOperations.class); + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + assertThat(jdbcTemplate.getDataSource()).isEqualTo(context.getBean("customDataSource")); + }); } @Test public void testNamedParameterJdbcTemplateExists() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); - NamedParameterJdbcTemplate namedParameterJdbcTemplate = context - .getBean(NamedParameterJdbcTemplate.class); - assertThat(namedParameterJdbcTemplate.getJdbcOperations()) - .isEqualTo(context.getBean(JdbcOperations.class)); + NamedParameterJdbcTemplate namedParameterJdbcTemplate = context.getBean(NamedParameterJdbcTemplate.class); + assertThat(namedParameterJdbcTemplate.getJdbcOperations()).isEqualTo(context.getBean(JdbcOperations.class)); }); } @Test public void testMultiDataSource() { - this.contextRunner.withUserConfiguration(MultiDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(JdbcOperations.class); - assertThat(context) - .doesNotHaveBean(NamedParameterJdbcOperations.class); - }); + this.contextRunner.withUserConfiguration(MultiDataSourceConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean(JdbcOperations.class); + assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class); + }); } @Test public void testMultiJdbcTemplate() { this.contextRunner.withUserConfiguration(MultiJdbcTemplateConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(NamedParameterJdbcOperations.class)); + .run((context) -> assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class)); } @Test public void testMultiDataSourceUsingPrimary() { - this.contextRunner - .withUserConfiguration(MultiDataSourceUsingPrimaryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JdbcOperations.class); - assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); - assertThat(context.getBean(JdbcTemplate.class).getDataSource()) - .isEqualTo(context.getBean("test1DataSource")); - }); + this.contextRunner.withUserConfiguration(MultiDataSourceUsingPrimaryConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(JdbcOperations.class); + assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); + assertThat(context.getBean(JdbcTemplate.class).getDataSource()) + .isEqualTo(context.getBean("test1DataSource")); + }); } @Test public void testMultiJdbcTemplateUsingPrimary() { - this.contextRunner - .withUserConfiguration(MultiJdbcTemplateUsingPrimaryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); - assertThat(context.getBean(NamedParameterJdbcTemplate.class) - .getJdbcOperations()) - .isEqualTo(context.getBean("test1Template")); - }); + this.contextRunner.withUserConfiguration(MultiJdbcTemplateUsingPrimaryConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); + assertThat(context.getBean(NamedParameterJdbcTemplate.class).getJdbcOperations()) + .isEqualTo(context.getBean("test1Template")); + }); } @Test public void testExistingCustomJdbcTemplate() { - this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JdbcOperations.class); - assertThat(context.getBean(JdbcOperations.class)) - .isEqualTo(context.getBean("customJdbcOperations")); - }); + this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(JdbcOperations.class); + assertThat(context.getBean(JdbcOperations.class)).isEqualTo(context.getBean("customJdbcOperations")); + }); } @Test public void testExistingCustomNamedParameterJdbcTemplate() { - this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); - assertThat(context.getBean(NamedParameterJdbcOperations.class)) - .isEqualTo(context - .getBean("customNamedParameterJdbcOperations")); - }); + this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); + assertThat(context.getBean(NamedParameterJdbcOperations.class)) + .isEqualTo(context.getBean("customNamedParameterJdbcOperations")); + }); } @Test public void testDependencyToDataSourceInitialization() { this.contextRunner.withUserConfiguration(DataSourceInitializationValidator.class) - .withPropertyValues("spring.datasource.initialization-mode=always") - .run((context) -> { + .withPropertyValues("spring.datasource.initialization-mode=always").run((context) -> { assertThat(context).hasNotFailed(); - assertThat(context - .getBean(DataSourceInitializationValidator.class).count) - .isEqualTo(1); + assertThat(context.getBean(DataSourceInitializationValidator.class).count).isEqualTo(1); }); } @@ -180,57 +159,41 @@ public class JdbcTemplateAutoConfigurationTests { public void testDependencyToFlyway() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) .withPropertyValues("spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceMigrationValidator.class).count) - .isEqualTo(0); + assertThat(context.getBean(DataSourceMigrationValidator.class).count).isEqualTo(0); }); } @Test public void testDependencyToFlywayWithJdbcTemplateMixed() { - this.contextRunner - .withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) + this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) .withPropertyValues("spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { assertThat(context).hasNotFailed(); assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); - assertThat(context.getBean( - NamedParameterDataSourceMigrationValidator.class).count) - .isEqualTo(0); + assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isEqualTo(0); }); } @Test public void testDependencyToLiquibase() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) - .withPropertyValues( - "spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") - .withConfiguration( - AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .run((context) -> { + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceMigrationValidator.class).count) - .isEqualTo(0); + assertThat(context.getBean(DataSourceMigrationValidator.class).count).isEqualTo(0); }); } @Test public void testDependencyToLiquibaseWithJdbcTemplateMixed() { - this.contextRunner - .withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) - .withPropertyValues( - "spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") - .withConfiguration( - AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .run((context) -> { + this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { assertThat(context).hasNotFailed(); assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); - assertThat(context.getBean( - NamedParameterDataSourceMigrationValidator.class).count) - .isEqualTo(0); + assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isEqualTo(0); }); } @@ -243,8 +206,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Bean - public NamedParameterJdbcOperations customNamedParameterJdbcOperations( - DataSource dataSource) { + public NamedParameterJdbcOperations customNamedParameterJdbcOperations(DataSource dataSource) { return new NamedParameterJdbcTemplate(dataSource); } @@ -296,8 +258,7 @@ public class JdbcTemplateAutoConfigurationTests { private final Integer count; DataSourceInitializationValidator(JdbcTemplate jdbcTemplate) { - this.count = jdbcTemplate.queryForObject("SELECT COUNT(*) from BAR", - Integer.class); + this.count = jdbcTemplate.queryForObject("SELECT COUNT(*) from BAR", Integer.class); } } @@ -307,8 +268,7 @@ public class JdbcTemplateAutoConfigurationTests { private final Integer count; DataSourceMigrationValidator(JdbcTemplate jdbcTemplate) { - this.count = jdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", - Integer.class); + this.count = jdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", Integer.class); } } @@ -317,10 +277,9 @@ public class JdbcTemplateAutoConfigurationTests { private final Integer count; - NamedParameterDataSourceMigrationValidator( - NamedParameterJdbcTemplate namedParameterJdbcTemplate) { - this.count = namedParameterJdbcTemplate.queryForObject( - "SELECT COUNT(*) from CITY", Collections.emptyMap(), Integer.class); + NamedParameterDataSourceMigrationValidator(NamedParameterJdbcTemplate namedParameterJdbcTemplate) { + this.count = namedParameterJdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", Collections.emptyMap(), + Integer.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java index eb8e8306bd6..7cf47d3d2f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java @@ -55,23 +55,20 @@ public class JndiDataSourceAutoConfigurationTests { @BeforeEach public void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } @BeforeEach public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @AfterEach public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -83,8 +80,7 @@ public class JndiDataSourceAutoConfigurationTests { } @Test - public void dataSourceIsAvailableFromJndi() - throws IllegalStateException, NamingException { + public void dataSourceIsAvailableFromJndi() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); @@ -98,67 +94,56 @@ public class JndiDataSourceAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void mbeanDataSourceIsExcludedFromExport() - throws IllegalStateException, NamingException { + public void mbeanDataSourceIsExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context); - this.context.register(JndiDataSourceAutoConfiguration.class, - MBeanExporterConfiguration.class); + this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); - Set excludedBeans = (Set) ReflectionTestUtils.getField(exporter, - "excludedBeans"); + Set excludedBeans = (Set) ReflectionTestUtils.getField(exporter, "excludedBeans"); assertThat(excludedBeans).containsExactly("dataSource"); } @SuppressWarnings("unchecked") @Test - public void mbeanDataSourceIsExcludedFromExportByAllExporters() - throws IllegalStateException, NamingException { + public void mbeanDataSourceIsExcludedFromExportByAllExporters() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context); - this.context.register(JndiDataSourceAutoConfiguration.class, - MBeanExporterConfiguration.class, + this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class, AnotherMBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); - for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.class) - .values()) { - Set excludedBeans = (Set) ReflectionTestUtils - .getField(exporter, "excludedBeans"); + for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.class).values()) { + Set excludedBeans = (Set) ReflectionTestUtils.getField(exporter, "excludedBeans"); assertThat(excludedBeans).containsExactly("dataSource"); } } @SuppressWarnings("unchecked") @Test - public void standardDataSourceIsNotExcludedFromExport() - throws IllegalStateException, NamingException { + public void standardDataSourceIsNotExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = mock(DataSource.class); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context); - this.context.register(JndiDataSourceAutoConfiguration.class, - MBeanExporterConfiguration.class); + this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); - Set excludedBeans = (Set) ReflectionTestUtils.getField(exporter, - "excludedBeans"); + Set excludedBeans = (Set) ReflectionTestUtils.getField(exporter, "excludedBeans"); assertThat(excludedBeans).isEmpty(); } - private void configureJndi(String name, DataSource dataSource) - throws IllegalStateException { + private void configureJndi(String name, DataSource dataSource) throws IllegalStateException { TestableInitialContextFactory.bind(name, dataSource); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java index 6b8656841f8..c57478eb382 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java @@ -59,23 +59,20 @@ public class TomcatDataSourceConfigurationTests { TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb").applyTo(this.context); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); - assertThat(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class)) - .isNotNull(); + assertThat(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class)).isNotNull(); } @Test public void testDataSourcePropertiesOverridden() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); - TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb", - PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", - PREFIX + "testOnReturn:true", - PREFIX + "timeBetweenEvictionRunsMillis:10000", - PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", - PREFIX + "jdbcInterceptors:SlowQueryReport", - PREFIX + "validationInterval:9999").applyTo(this.context); + TestPropertyValues + .of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", + PREFIX + "testOnReturn:true", PREFIX + "timeBetweenEvictionRunsMillis:10000", + PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", + PREFIX + "jdbcInterceptors:SlowQueryReport", PREFIX + "validationInterval:9999") + .applyTo(this.context); this.context.refresh(); - org.apache.tomcat.jdbc.pool.DataSource ds = this.context - .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); + org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(ds.getUrl()).isEqualTo("jdbc:h2:mem:testdb"); assertThat(ds.isTestWhileIdle()).isTrue(); assertThat(ds.isTestOnBorrow()).isTrue(); @@ -87,10 +84,8 @@ public class TomcatDataSourceConfigurationTests { assertDataSourceHasInterceptors(ds); } - private void assertDataSourceHasInterceptors(DataSourceProxy ds) - throws ClassNotFoundException { - PoolProperties.InterceptorDefinition[] interceptors = ds - .getJdbcInterceptorsAsArray(); + private void assertDataSourceHasInterceptors(DataSourceProxy ds) throws ClassNotFoundException { + PoolProperties.InterceptorDefinition[] interceptors = ds.getJdbcInterceptorsAsArray(); for (PoolProperties.InterceptorDefinition interceptor : interceptors) { if (SlowQueryReport.class == interceptor.getInterceptorClass()) { return; @@ -104,8 +99,7 @@ public class TomcatDataSourceConfigurationTests { this.context.register(TomcatDataSourceConfiguration.class); TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb").applyTo(this.context); this.context.refresh(); - org.apache.tomcat.jdbc.pool.DataSource ds = this.context - .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); + org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(5000); assertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(60000); assertThat(ds.getMaxWait()).isEqualTo(30000); @@ -120,8 +114,7 @@ public class TomcatDataSourceConfigurationTests { @Bean @ConfigurationProperties(prefix = "spring.datasource.tomcat") public DataSource dataSource() { - return DataSourceBuilder.create() - .type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); + return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java index c32cb0aa9c1..149656d50d7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java @@ -50,8 +50,7 @@ public class XADataSourceAutoConfigurationTests { @Test public void createFromUrl() { - ApplicationContext context = createContext(FromProperties.class, - "spring.datasource.url:jdbc:hsqldb:mem:test", + ApplicationContext context = createContext(FromProperties.class, "spring.datasource.url:jdbc:hsqldb:mem:test", "spring.datasource.username:un"); context.getBean(DataSource.class); MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java index e635fc6bec9..815705a26d3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java @@ -53,8 +53,7 @@ public class JerseyAutoConfigurationCustomApplicationTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/test/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/test/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -74,8 +73,8 @@ public class JerseyAutoConfigurationCustomApplicationTests { } @Configuration(proxyBeanMethods = false) - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) static class TestConfiguration { @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java index 9ba272d14ef..2573b1f4cbe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java @@ -60,8 +60,7 @@ public class JerseyAutoConfigurationCustomFilterContextPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -92,8 +91,8 @@ public class JerseyAutoConfigurationCustomFilterContextPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java index cd6920a93fb..fbe639834e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java @@ -50,8 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.type=filter") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext public class JerseyAutoConfigurationCustomFilterPathTests { @@ -60,8 +59,7 @@ public class JerseyAutoConfigurationCustomFilterPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -92,8 +90,8 @@ public class JerseyAutoConfigurationCustomFilterPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java index b4bcc4c2d5f..4ded178348c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java @@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.servlet.load-on-startup=5") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.servlet.load-on-startup=5") @DirtiesContext public class JerseyAutoConfigurationCustomLoadOnStartupTests { @@ -52,8 +51,7 @@ public class JerseyAutoConfigurationCustomLoadOnStartupTests { @Test public void contextLoads() { - assertThat(this.context.getBean("jerseyServletRegistration")) - .hasFieldOrPropertyWithValue("loadOnStartup", 5); + assertThat(this.context.getBean("jerseyServletRegistration")).hasFieldOrPropertyWithValue("loadOnStartup", 5); } @MinimalWebConfiguration @@ -69,8 +67,8 @@ public class JerseyAutoConfigurationCustomLoadOnStartupTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java index d5cae3ecf96..c73731cc283 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java @@ -60,8 +60,7 @@ public class JerseyAutoConfigurationCustomObjectMapperProviderTests { @Test public void contextLoads() { - ResponseEntity response = this.restTemplate.getForEntity("/rest/message", - String.class); + ResponseEntity response = this.restTemplate.getForEntity("/rest/message", String.class); assertThat(HttpStatus.OK).isEqualTo(response.getStatusCode()); assertThat("{\"subject\":\"Jersey\"}").isEqualTo(response.getBody()); } @@ -119,9 +118,8 @@ public class JerseyAutoConfigurationCustomObjectMapperProviderTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JacksonAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java index d0d7dae58f9..76690556707 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java @@ -50,8 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "server.servlet.contextPath=/app") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "server.servlet.contextPath=/app") @DirtiesContext public class JerseyAutoConfigurationCustomServletContextPathTests { @@ -60,8 +59,7 @@ public class JerseyAutoConfigurationCustomServletContextPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -92,8 +90,8 @@ public class JerseyAutoConfigurationCustomServletContextPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java index 1e6fa74b41e..8596eff12fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java @@ -59,8 +59,7 @@ public class JerseyAutoConfigurationCustomServletPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -91,8 +90,8 @@ public class JerseyAutoConfigurationCustomServletPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java index 307dff006eb..4f1bc4d7fb3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java @@ -49,8 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.type=filter") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext public class JerseyAutoConfigurationDefaultFilterPathTests { @@ -59,8 +58,7 @@ public class JerseyAutoConfigurationDefaultFilterPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -90,8 +88,8 @@ public class JerseyAutoConfigurationDefaultFilterPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java index a29bf206e8e..44d97d8dd9b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java @@ -58,8 +58,7 @@ public class JerseyAutoConfigurationDefaultServletPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -89,8 +88,8 @@ public class JerseyAutoConfigurationDefaultServletPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java index f748ba2eb29..bd00603da97 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java @@ -62,8 +62,7 @@ public class JerseyAutoConfigurationObjectMapperProviderTests { @Test public void responseIsSerializedUsingAutoConfiguredObjectMapper() { - ResponseEntity response = this.restTemplate.getForEntity("/rest/message", - String.class); + ResponseEntity response = this.restTemplate.getForEntity("/rest/message", String.class); assertThat(HttpStatus.OK).isEqualTo(response.getStatusCode()); assertThat(response.getBody()).isEqualTo("{\"subject\":\"Jersey\"}"); } @@ -130,9 +129,8 @@ public class JerseyAutoConfigurationObjectMapperProviderTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JacksonAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java index 2b13f89edaf..e5dead0087f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java @@ -59,14 +59,12 @@ public class JerseyAutoConfigurationServletContainerTests { @Test public void existingJerseyServletIsAmended(CapturedOutput output) { - assertThat(output) - .contains("Configuring existing registration for Jersey servlet"); - assertThat(output).contains( - "Servlet " + Application.class.getName() + " was not registered"); + assertThat(output).contains("Configuring existing registration for Jersey servlet"); + assertThat(output).contains("Servlet " + Application.class.getName() + " was not registered"); } - @ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) @Import(ContainerConfiguration.class) @Path("/hello") public static class Application extends ResourceConfig { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java index b6a3756ff31..b903a229d82 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java @@ -50,71 +50,53 @@ public class JerseyAutoConfigurationTests { public void requestContextFilterRegistrationIsAutoConfigured() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(FilterRegistrationBean.class); - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getFilter()).isInstanceOf(RequestContextFilter.class); }); } @Test public void whenUserDefinesARequestContextFilterTheAutoConfiguredRegistrationBacksOff() { - this.contextRunner.withUserConfiguration(RequestContextFilterConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(FilterRegistrationBean.class); - assertThat(context).hasSingleBean(RequestContextFilter.class); - }); + this.contextRunner.withUserConfiguration(RequestContextFilterConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean(FilterRegistrationBean.class); + assertThat(context).hasSingleBean(RequestContextFilter.class); + }); } @Test public void whenUserDefinesARequestContextFilterRegistrationTheAutoConfiguredRegistrationBacksOff() { - this.contextRunner - .withUserConfiguration( - RequestContextFilterRegistrationConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(FilterRegistrationBean.class); - assertThat(context).hasBean("customRequestContextFilterRegistration"); - }); + this.contextRunner.withUserConfiguration(RequestContextFilterRegistrationConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(FilterRegistrationBean.class); + assertThat(context).hasBean("customRequestContextFilterRegistration"); + }); } @Test public void whenJaxbIsAvailableTheObjectMapperIsCustomizedWithAnAnnotationIntrospector() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .run((context) -> { - ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig() - .getAnnotationIntrospector().allIntrospectors().stream() - .filter(JaxbAnnotationIntrospector.class::isInstance)) - .hasSize(1); - }); + this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)).run((context) -> { + ObjectMapper objectMapper = context.getBean(ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors().stream() + .filter(JaxbAnnotationIntrospector.class::isInstance)).hasSize(1); + }); } @Test public void whenJaxbIsNotAvailableTheObjectMapperCustomizationBacksOff() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader("javax.xml.bind.annotation")) - .run((context) -> { + this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader("javax.xml.bind.annotation")).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig() - .getAnnotationIntrospector().allIntrospectors().stream() - .filter(JaxbAnnotationIntrospector.class::isInstance)) - .isEmpty(); + assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors() + .stream().filter(JaxbAnnotationIntrospector.class::isInstance)).isEmpty(); }); } @Test public void whenJacksonJaxbModuleIsNotAvailableTheObjectMapperCustomizationBacksOff() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withClassLoader( - new FilteredClassLoader(JaxbAnnotationIntrospector.class)) - .run((context) -> { + this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(JaxbAnnotationIntrospector.class)).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig() - .getAnnotationIntrospector().allIntrospectors().stream() - .filter(JaxbAnnotationIntrospector.class::isInstance)) - .isEmpty(); + assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors() + .stream().filter(JaxbAnnotationIntrospector.class::isInstance)).isEmpty(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java index 1783eb73e7c..fe8694a4d7c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java @@ -49,8 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Eddú Meléndez */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.application-path=/api") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.application-path=/api") @DirtiesContext public class JerseyAutoConfigurationWithoutApplicationPathTests { @@ -59,8 +58,7 @@ public class JerseyAutoConfigurationWithoutApplicationPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/api/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/api/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -90,8 +88,8 @@ public class JerseyAutoConfigurationWithoutApplicationPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index ad27e02f44a..05bb5243c4d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -64,24 +64,20 @@ public class JmsAutoConfigurationTests { private static final String ACTIVEMQ_NETWORK_URL = "tcp://localhost:61616"; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, - JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); @Test public void testDefaultJmsConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run(this::testDefaultJmsConfiguration); + this.contextRunner.withUserConfiguration(TestConfiguration.class).run(this::testDefaultJmsConfiguration); } private void testDefaultJmsConfiguration(AssertableApplicationContext loaded) { assertThat(loaded).hasSingleBean(ConnectionFactory.class); assertThat(loaded).hasSingleBean(CachingConnectionFactory.class); CachingConnectionFactory factory = loaded.getBean(CachingConnectionFactory.class); - assertThat(factory.getTargetConnectionFactory()) - .isInstanceOf(ActiveMQConnectionFactory.class); + assertThat(factory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); - JmsMessagingTemplate messagingTemplate = loaded - .getBean(JmsMessagingTemplate.class); + JmsMessagingTemplate messagingTemplate = loaded.getBean(JmsMessagingTemplate.class); assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); assertThat(getBrokerUrl(factory)).isEqualTo(ACTIVEMQ_EMBEDDED_URL); @@ -91,40 +87,35 @@ public class JmsAutoConfigurationTests { @Test public void testConnectionFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration2.class) - .run((context) -> assertThat( - context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) - .isEqualTo("foobar")); + .run((context) -> assertThat(context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + .isEqualTo("foobar")); } @Test public void testJmsTemplateBackOff() { - this.contextRunner.withUserConfiguration(TestConfiguration3.class).run( - (context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()) - .isEqualTo(999)); + this.contextRunner.withUserConfiguration(TestConfiguration3.class) + .run((context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()).isEqualTo(999)); } @Test public void testJmsMessagingTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class) - .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class) - .getDefaultDestinationName()).isEqualTo("fooBar")); + .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class).getDefaultDestinationName()) + .isEqualTo("fooBar")); } @Test public void testJmsTemplateBackOffEverything() { this.contextRunner - .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, - TestConfiguration5.class) + .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class) .run(this::testJmsTemplateBackOffEverything); } private void testJmsTemplateBackOffEverything(AssertableApplicationContext loaded) { JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); assertThat(jmsTemplate.getPriority()).isEqualTo(999); - assertThat(loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) - .isEqualTo("foobar"); - JmsMessagingTemplate messagingTemplate = loaded - .getBean(JmsMessagingTemplate.class); + assertThat(loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL()).isEqualTo("foobar"); + JmsMessagingTemplate messagingTemplate = loaded.getBean(JmsMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); } @@ -132,156 +123,124 @@ public class JmsAutoConfigurationTests { @Test public void testEnableJmsCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run((context) -> assertThat(context).getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class) + .run((context) -> assertThat(context) + .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class)); } @Test public void testJmsListenerContainerFactoryBackOff() { - this.contextRunner.withUserConfiguration(TestConfiguration6.class, - EnableJmsConfiguration.class).run( - (context) -> assertThat(context) - .getBean("jmsListenerContainerFactory", - JmsListenerContainerFactory.class) - .isExactlyInstanceOf( - SimpleJmsListenerContainerFactory.class)); + this.contextRunner.withUserConfiguration(TestConfiguration6.class, EnableJmsConfiguration.class) + .run((context) -> assertThat(context) + .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) + .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class)); } @Test public void jmsListenerContainerFactoryWhenMultipleConnectionFactoryBeansShouldBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration10.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(JmsListenerContainerFactory.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JmsListenerContainerFactory.class)); } @Test public void testJmsListenerContainerFactoryWithCustomSettings() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) .withPropertyValues("spring.jms.listener.autoStartup=false", - "spring.jms.listener.acknowledgeMode=client", - "spring.jms.listener.concurrency=2", + "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", "spring.jms.listener.maxConcurrency=10") .run(this::testJmsListenerContainerFactoryWithCustomSettings); } - private void testJmsListenerContainerFactoryWithCustomSettings( - AssertableApplicationContext loaded) { - DefaultMessageListenerContainer container = getContainer(loaded, - "jmsListenerContainerFactory"); + private void testJmsListenerContainerFactoryWithCustomSettings(AssertableApplicationContext loaded) { + DefaultMessageListenerContainer container = getContainer(loaded, "jmsListenerContainerFactory"); assertThat(container.isAutoStartup()).isFalse(); - assertThat(container.getSessionAcknowledgeMode()) - .isEqualTo(Session.CLIENT_ACKNOWLEDGE); + assertThat(container.getSessionAcknowledgeMode()).isEqualTo(Session.CLIENT_ACKNOWLEDGE); assertThat(container.getConcurrentConsumers()).isEqualTo(2); assertThat(container.getMaxConcurrentConsumers()).isEqualTo(10); } @Test public void testDefaultContainerFactoryWithJtaTransactionManager() { - this.contextRunner.withUserConfiguration(TestConfiguration7.class, - EnableJmsConfiguration.class).run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, - "jmsListenerContainerFactory"); + this.contextRunner.withUserConfiguration(TestConfiguration7.class, EnableJmsConfiguration.class) + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); assertThat(container.isSessionTransacted()).isFalse(); - assertThat(container).hasFieldOrPropertyWithValue( - "transactionManager", + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", context.getBean(JtaTransactionManager.class)); }); } @Test public void testDefaultContainerFactoryNonJtaTransactionManager() { - this.contextRunner.withUserConfiguration(TestConfiguration8.class, - EnableJmsConfiguration.class).run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, - "jmsListenerContainerFactory"); + this.contextRunner.withUserConfiguration(TestConfiguration8.class, EnableJmsConfiguration.class) + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); assertThat(container.isSessionTransacted()).isTrue(); - assertThat(container) - .hasFieldOrPropertyWithValue("transactionManager", null); + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", null); }); } @Test public void testDefaultContainerFactoryNoTransactionManager() { - this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, - "jmsListenerContainerFactory"); - assertThat(container.isSessionTransacted()).isTrue(); - assertThat(container) - .hasFieldOrPropertyWithValue("transactionManager", null); - }); + this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class).run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isTrue(); + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", null); + }); } @Test public void testDefaultContainerFactoryWithMessageConverters() { - this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, - EnableJmsConfiguration.class).run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, - "jmsListenerContainerFactory"); - assertThat(container.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); + this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, EnableJmsConfiguration.class) + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); }); } @Test public void testCustomContainerFactoryWithConfigurer() { - this.contextRunner - .withUserConfiguration(TestConfiguration9.class, - EnableJmsConfiguration.class) - .withPropertyValues("spring.jms.listener.autoStartup=false") - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, - "customListenerContainerFactory"); - assertThat(container.getCacheLevel()) - .isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); + this.contextRunner.withUserConfiguration(TestConfiguration9.class, EnableJmsConfiguration.class) + .withPropertyValues("spring.jms.listener.autoStartup=false").run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "customListenerContainerFactory"); + assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); assertThat(container.isAutoStartup()).isFalse(); }); } - private DefaultMessageListenerContainer getContainer( - AssertableApplicationContext loaded, String name) { - JmsListenerContainerFactory factory = loaded.getBean(name, - JmsListenerContainerFactory.class); + private DefaultMessageListenerContainer getContainer(AssertableApplicationContext loaded, String name) { + JmsListenerContainerFactory factory = loaded.getBean(name, JmsListenerContainerFactory.class); assertThat(factory).isInstanceOf(DefaultJmsListenerContainerFactory.class); - return ((DefaultJmsListenerContainerFactory) factory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); + return ((DefaultJmsListenerContainerFactory) factory).createListenerContainer(mock(JmsListenerEndpoint.class)); } @Test public void testJmsTemplateWithMessageConverter() { - this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); - }); + this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class).run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + }); } @Test public void testJmsTemplateWithDestinationResolver() { this.contextRunner.withUserConfiguration(DestinationResolversConfiguration.class) - .run((context) -> assertThat( - context.getBean(JmsTemplate.class).getDestinationResolver()) - .isSameAs(context.getBean("myDestinationResolver"))); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).getDestinationResolver()) + .isSameAs(context.getBean("myDestinationResolver"))); } @Test public void testJmsTemplateFullCustomization() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) .withPropertyValues("spring.jms.template.default-destination=testQueue", - "spring.jms.template.delivery-delay=500", - "spring.jms.template.delivery-mode=non-persistent", - "spring.jms.template.priority=6", - "spring.jms.template.time-to-live=6000", + "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", + "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", "spring.jms.template.receive-timeout=2000") .run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); + assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(jmsTemplate.getDefaultDestinationName()) - .isEqualTo("testQueue"); + assertThat(jmsTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); assertThat(jmsTemplate.getDeliveryDelay()).isEqualTo(500); assertThat(jmsTemplate.getDeliveryMode()).isEqualTo(1); assertThat(jmsTemplate.getPriority()).isEqualTo(6); @@ -293,28 +252,22 @@ public class JmsAutoConfigurationTests { @Test public void testJmsMessagingTemplateUseConfiguredDefaultDestination() { - this.contextRunner - .withPropertyValues("spring.jms.template.default-destination=testQueue") - .run((context) -> { - JmsMessagingTemplate messagingTemplate = context - .getBean(JmsMessagingTemplate.class); - assertThat(messagingTemplate.getDefaultDestinationName()) - .isEqualTo("testQueue"); - }); + this.contextRunner.withPropertyValues("spring.jms.template.default-destination=testQueue").run((context) -> { + JmsMessagingTemplate messagingTemplate = context.getBean(JmsMessagingTemplate.class); + assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); + }); } @Test public void testPubSubDisabledByDefault() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat( - context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); } @Test public void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { this.contextRunner.withUserConfiguration(TestConfiguration4.class) - .run((context) -> assertThat( - context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); } @Test @@ -340,8 +293,7 @@ public class JmsAutoConfigurationTests { ConnectionFactory factory = context.getBean(ConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(factory).isNotNull() - .isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); }); } @@ -354,46 +306,38 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); ConnectionFactory factory = context.getBean(ConnectionFactory.class); assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(getBrokerUrl((CachingConnectionFactory) factory)) - .isEqualTo(ACTIVEMQ_NETWORK_URL); + assertThat(getBrokerUrl((CachingConnectionFactory) factory)).isEqualTo(ACTIVEMQ_NETWORK_URL); }); } @Test public void testActiveMQOverriddenRemoteHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000") - .run((context) -> { + .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000").run((context) -> { assertThat(context).hasSingleBean(JmsTemplate.class); assertThat(context).hasSingleBean(CachingConnectionFactory.class); JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); ConnectionFactory factory = context.getBean(ConnectionFactory.class); assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(getBrokerUrl((CachingConnectionFactory) factory)) - .isEqualTo("tcp://remote-host:10000"); + assertThat(getBrokerUrl((CachingConnectionFactory) factory)).isEqualTo("tcp://remote-host:10000"); }); } private String getBrokerUrl(CachingConnectionFactory connectionFactory) { - assertThat(connectionFactory.getTargetConnectionFactory()) - .isInstanceOf(ActiveMQConnectionFactory.class); - return ((ActiveMQConnectionFactory) connectionFactory - .getTargetConnectionFactory()).getBrokerURL(); + assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); + return ((ActiveMQConnectionFactory) connectionFactory.getTargetConnectionFactory()).getBrokerURL(); } @Test public void testActiveMQOverriddenPool() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true") - .run((context) -> { + .withPropertyValues("spring.activemq.pool.enabled:true").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsPoolConnectionFactory pool = context - .getBean(JmsPoolConnectionFactory.class); + JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool - .getConnectionFactory(); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); }); } @@ -401,17 +345,14 @@ public class JmsAutoConfigurationTests { @Test public void testActiveMQOverriddenPoolAndStandalone() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true", - "spring.activemq.inMemory:false") + .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.inMemory:false") .run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsPoolConnectionFactory pool = context - .getBean(JmsPoolConnectionFactory.class); + JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool - .getConnectionFactory(); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); }); } @@ -423,25 +364,21 @@ public class JmsAutoConfigurationTests { "spring.activemq.brokerUrl:tcp://remote-host:10000") .run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsPoolConnectionFactory pool = context - .getBean(JmsPoolConnectionFactory.class); + JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool - .getConnectionFactory(); - assertThat(factory.getBrokerURL()) - .isEqualTo("tcp://remote-host:10000"); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); + assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000"); }); } @Test public void enableJmsAutomatically() { this.contextRunner.withUserConfiguration(NoEnableJmsConfiguration.class) - .run((context) -> assertThat(context).hasBean( - JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) - .hasBean( - JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)); + .run((context) -> assertThat(context) + .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)); } @Configuration(proxyBeanMethods = false) @@ -479,8 +416,7 @@ public class JmsAutoConfigurationTests { protected static class TestConfiguration4 implements BeanPostProcessor { @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean.getClass().isAssignableFrom(JmsTemplate.class)) { JmsTemplate jmsTemplate = (JmsTemplate) bean; jmsTemplate.setPubSubDomain(true); @@ -489,8 +425,7 @@ public class JmsAutoConfigurationTests { } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @@ -501,8 +436,7 @@ public class JmsAutoConfigurationTests { @Bean JmsMessagingTemplate jmsMessagingTemplate(JmsTemplate jmsTemplate) { - JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate( - jmsTemplate); + JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate(jmsTemplate); messagingTemplate.setDefaultDestinationName("fooBar"); return messagingTemplate; } @@ -513,8 +447,7 @@ public class JmsAutoConfigurationTests { protected static class TestConfiguration6 { @Bean - JmsListenerContainerFactory jmsListenerContainerFactory( - ConnectionFactory connectionFactory) { + JmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) { SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); return factory; @@ -579,8 +512,7 @@ public class JmsAutoConfigurationTests { @Bean JmsListenerContainerFactory customListenerContainerFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); factory.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java index be49dbab059..9495746e9da 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java @@ -43,8 +43,7 @@ import static org.mockito.Mockito.mock; public class JndiConnectionFactoryAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); private ClassLoader threadContextClassLoader; @@ -53,19 +52,16 @@ public class JndiConnectionFactoryAutoConfigurationTests { @BeforeEach public void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @AfterEach public void cleanUp() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -75,8 +71,7 @@ public class JndiConnectionFactoryAutoConfigurationTests { @Test public void detectNoAvailableCandidates() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ConnectionFactory.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactory.class)); } @Test @@ -87,44 +82,37 @@ public class JndiConnectionFactoryAutoConfigurationTests { @Test public void detectWithXAConnectionFactory() { - ConnectionFactory connectionFactory = configureConnectionFactory( - "java:/XAConnectionFactory"); + ConnectionFactory connectionFactory = configureConnectionFactory("java:/XAConnectionFactory"); this.contextRunner.run(assertConnectionFactory(connectionFactory)); } @Test public void jndiNamePropertySet() { - ConnectionFactory connectionFactory = configureConnectionFactory( - "java:comp/env/myCF"); + ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=java:comp/env/myCF") .run(assertConnectionFactory(connectionFactory)); } @Test public void jndiNamePropertySetWithResourceRef() { - ConnectionFactory connectionFactory = configureConnectionFactory( - "java:comp/env/myCF"); + ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=myCF") .run(assertConnectionFactory(connectionFactory)); } @Test public void jndiNamePropertySetWithWrongValue() { - this.contextRunner.withPropertyValues("spring.jms.jndi-name=doesNotExistCF") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining("doesNotExistCF"); - }); + this.contextRunner.withPropertyValues("spring.jms.jndi-name=doesNotExistCF").run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) + .hasMessageContaining("doesNotExistCF"); + }); } - private ContextConsumer assertConnectionFactory( - ConnectionFactory connectionFactory) { + private ContextConsumer assertConnectionFactory(ConnectionFactory connectionFactory) { return (context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context.getBean(ConnectionFactory.class)) - .isSameAs(connectionFactory); + assertThat(context.getBean(ConnectionFactory.class)).isSameAs(connectionFactory); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java index ae6838bd444..40d176a9891 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java @@ -44,60 +44,49 @@ import static org.mockito.Mockito.mockingDetails; public class ActiveMQAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, - JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); @Test public void brokerIsEmbeddedByDefault() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(CachingConnectionFactory.class); - CachingConnectionFactory cachingConnectionFactory = context - .getBean(CachingConnectionFactory.class); - assertThat(cachingConnectionFactory.getTargetConnectionFactory()) - .isInstanceOf(ActiveMQConnectionFactory.class); - assertThat(((ActiveMQConnectionFactory) cachingConnectionFactory - .getTargetConnectionFactory()).getBrokerURL()) - .isEqualTo("vm://localhost?broker.persistent=false"); - }); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(CachingConnectionFactory.class); + CachingConnectionFactory cachingConnectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(cachingConnectionFactory.getTargetConnectionFactory()) + .isInstanceOf(ActiveMQConnectionFactory.class); + assertThat( + ((ActiveMQConnectionFactory) cachingConnectionFactory.getTargetConnectionFactory()).getBrokerURL()) + .isEqualTo("vm://localhost?broker.persistent=false"); + }); } @Test public void configurationBacksOffWhenCustomConnectionFactoryExists() { - this.contextRunner - .withUserConfiguration(CustomConnectionFactoryConfiguration.class) - .run((context) -> assertThat( - mockingDetails(context.getBean(ConnectionFactory.class)).isMock()) - .isTrue()); + this.contextRunner.withUserConfiguration(CustomConnectionFactoryConfiguration.class).run( + (context) -> assertThat(mockingDetails(context.getBean(ConnectionFactory.class)).isMock()).isTrue()); } @Test public void connectionFactoryIsCachedByDefault() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context).hasSingleBean(CachingConnectionFactory.class); - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getTargetConnectionFactory()) - .isInstanceOf(ActiveMQConnectionFactory.class); - assertThat(connectionFactory.isCacheConsumers()).isFalse(); - assertThat(connectionFactory.isCacheProducers()).isTrue(); - assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(1); - }); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context).hasSingleBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); + assertThat(connectionFactory.isCacheConsumers()).isFalse(); + assertThat(connectionFactory.isCacheProducers()).isTrue(); + assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(1); + }); } @Test public void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.consumers=true", - "spring.jms.cache.producers=false", + .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", "spring.jms.cache.session-cache-size=10") .run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); assertThat(context).hasSingleBean(CachingConnectionFactory.class); - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.isCacheConsumers()).isTrue(); assertThat(connectionFactory.isCacheProducers()).isFalse(); assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); @@ -108,27 +97,19 @@ public class ActiveMQAutoConfigurationTests { public void connectionFactoryCachingCanBeDisabled() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { - assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)) - .hasSize(1); - ActiveMQConnectionFactory connectionFactory = context - .getBean(ActiveMQConnectionFactory.class); + assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)).hasSize(1); + ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); ActiveMQConnectionFactory defaultFactory = new ActiveMQConnectionFactory( "vm://localhost?broker.persistent=false"); - assertThat(connectionFactory.getUserName()) - .isEqualTo(defaultFactory.getUserName()); - assertThat(connectionFactory.getPassword()) - .isEqualTo(defaultFactory.getPassword()); - assertThat(connectionFactory.getCloseTimeout()) - .isEqualTo(defaultFactory.getCloseTimeout()); + assertThat(connectionFactory.getUserName()).isEqualTo(defaultFactory.getUserName()); + assertThat(connectionFactory.getPassword()).isEqualTo(defaultFactory.getPassword()); + assertThat(connectionFactory.getCloseTimeout()).isEqualTo(defaultFactory.getCloseTimeout()); assertThat(connectionFactory.isNonBlockingRedelivery()) .isEqualTo(defaultFactory.isNonBlockingRedelivery()); - assertThat(connectionFactory.getSendTimeout()) - .isEqualTo(defaultFactory.getSendTimeout()); - assertThat(connectionFactory.isTrustAllPackages()) - .isEqualTo(defaultFactory.isTrustAllPackages()); + assertThat(connectionFactory.getSendTimeout()).isEqualTo(defaultFactory.getSendTimeout()); + assertThat(connectionFactory.isTrustAllPackages()).isEqualTo(defaultFactory.isTrustAllPackages()); assertThat(connectionFactory.getTrustedPackages()) - .containsExactly(StringUtils - .toStringArray(defaultFactory.getTrustedPackages())); + .containsExactly(StringUtils.toStringArray(defaultFactory.getTrustedPackages())); }); } @@ -137,47 +118,36 @@ public class ActiveMQAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.enabled=false", "spring.activemq.brokerUrl=vm://localhost?useJmx=false&broker.persistent=false", - "spring.activemq.user=foo", "spring.activemq.password=bar", - "spring.activemq.closeTimeout=500", - "spring.activemq.nonBlockingRedelivery=true", - "spring.activemq.sendTimeout=1000", - "spring.activemq.packages.trust-all=false", - "spring.activemq.packages.trusted=com.example.acme") + "spring.activemq.user=foo", "spring.activemq.password=bar", "spring.activemq.closeTimeout=500", + "spring.activemq.nonBlockingRedelivery=true", "spring.activemq.sendTimeout=1000", + "spring.activemq.packages.trust-all=false", "spring.activemq.packages.trusted=com.example.acme") .run((context) -> { - assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)) - .hasSize(1); - ActiveMQConnectionFactory connectionFactory = context - .getBean(ActiveMQConnectionFactory.class); + assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)).hasSize(1); + ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); assertThat(connectionFactory.getUserName()).isEqualTo("foo"); assertThat(connectionFactory.getPassword()).isEqualTo("bar"); assertThat(connectionFactory.getCloseTimeout()).isEqualTo(500); assertThat(connectionFactory.isNonBlockingRedelivery()).isTrue(); assertThat(connectionFactory.getSendTimeout()).isEqualTo(1000); assertThat(connectionFactory.isTrustAllPackages()).isFalse(); - assertThat(connectionFactory.getTrustedPackages()) - .containsExactly("com.example.acme"); + assertThat(connectionFactory.getTrustedPackages()).containsExactly("com.example.acme"); }); } @Test public void defaultPoolConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=true") - .run((context) -> { - assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)) - .hasSize(1); - JmsPoolConnectionFactory connectionFactory = context - .getBean(JmsPoolConnectionFactory.class); + .withPropertyValues("spring.activemq.pool.enabled=true").run((context) -> { + assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo( - defaultFactory.getBlockIfSessionPoolIsFullTimeout()); + .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); assertThat(connectionFactory.getConnectionIdleTimeout()) .isEqualTo(defaultFactory.getConnectionIdleTimeout()); - assertThat(connectionFactory.getMaxConnections()) - .isEqualTo(defaultFactory.getMaxConnections()); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); assertThat(connectionFactory.getMaxSessionsPerConnection()) .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); assertThat(connectionFactory.getConnectionCheckInterval()) @@ -190,29 +160,20 @@ public class ActiveMQAutoConfigurationTests { @Test public void customPoolConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=true", - "spring.activemq.pool.blockIfFull=false", - "spring.activemq.pool.blockIfFullTimeout=64", - "spring.activemq.pool.idleTimeout=512", - "spring.activemq.pool.maxConnections=256", - "spring.activemq.pool.maxSessionsPerConnection=1024", + .withPropertyValues("spring.activemq.pool.enabled=true", "spring.activemq.pool.blockIfFull=false", + "spring.activemq.pool.blockIfFullTimeout=64", "spring.activemq.pool.idleTimeout=512", + "spring.activemq.pool.maxConnections=256", "spring.activemq.pool.maxSessionsPerConnection=1024", "spring.activemq.pool.timeBetweenExpirationCheck=2048", "spring.activemq.pool.useAnonymousProducers=false") .run((context) -> { - assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)) - .hasSize(1); - JmsPoolConnectionFactory connectionFactory = context - .getBean(JmsPoolConnectionFactory.class); + assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo(64); - assertThat(connectionFactory.getConnectionIdleTimeout()) - .isEqualTo(512); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); + assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaxSessionsPerConnection()) - .isEqualTo(1024); - assertThat(connectionFactory.getConnectionCheckInterval()) - .isEqualTo(2048); + assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); + assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); }); } @@ -220,8 +181,7 @@ public class ActiveMQAutoConfigurationTests { @Test public void poolConnectionFactoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true") - .run((context) -> { + .withPropertyValues("spring.activemq.pool.enabled:true").run((context) -> { ConnectionFactory factory = context.getBean(ConnectionFactory.class); assertThat(factory).isInstanceOf(JmsPoolConnectionFactory.class); context.getSourceApplicationContext().close(); @@ -250,8 +210,7 @@ public class ActiveMQAutoConfigurationTests { @Bean public ActiveMQConnectionFactoryCustomizer activeMQConnectionFactoryCustomizer() { return (factory) -> { - factory.setBrokerURL( - "vm://localhost?useJmx=false&broker.persistent=false"); + factory.setBrokerURL("vm://localhost?useJmx=false&broker.persistent=false"); factory.setUserName("foobar"); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java index 91aa652957b..ad70a16729a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java @@ -40,37 +40,32 @@ public class ActiveMQPropertiesTests { @Test public void getBrokerUrlIsInMemoryByDefault() { - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo(DEFAULT_EMBEDDED_BROKER_URL); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo(DEFAULT_EMBEDDED_BROKER_URL); } @Test public void getBrokerUrlUseExplicitBrokerUrl() { this.properties.setBrokerUrl("vm://foo-bar"); - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo("vm://foo-bar"); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test public void getBrokerUrlWithInMemorySetToFalse() { this.properties.setInMemory(false); - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo(DEFAULT_NETWORK_BROKER_URL); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo(DEFAULT_NETWORK_BROKER_URL); } @Test public void getExplicitBrokerUrlAlwaysWins() { this.properties.setBrokerUrl("vm://foo-bar"); this.properties.setInMemory(false); - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo("vm://foo-bar"); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test public void setTrustAllPackages() { this.properties.getPackages().setTrustAll(true); - assertThat(createFactory(this.properties) - .createConnectionFactory(ActiveMQConnectionFactory.class) + assertThat(createFactory(this.properties).createConnectionFactory(ActiveMQConnectionFactory.class) .isTrustAllPackages()).isTrue(); } @@ -85,8 +80,7 @@ public class ActiveMQPropertiesTests { assertThat(factory.getTrustedPackages().get(0)).isEqualTo("trusted.package"); } - private ActiveMQConnectionFactoryFactory createFactory( - ActiveMQProperties properties) { + private ActiveMQConnectionFactoryFactory createFactory(ActiveMQProperties properties) { return new ActiveMQConnectionFactoryFactory(properties, Collections.emptyList()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index adb768cd034..82c85664484 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -66,36 +66,30 @@ import static org.assertj.core.api.Assertions.assertThat; public class ArtemisAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, - JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); @Test public void connectionFactoryIsCachedByDefault() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context).hasSingleBean(CachingConnectionFactory.class); - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getTargetConnectionFactory()) - .isInstanceOf(ActiveMQConnectionFactory.class); - assertThat(connectionFactory.isCacheConsumers()).isFalse(); - assertThat(connectionFactory.isCacheProducers()).isTrue(); - assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(1); - }); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context).hasSingleBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); + assertThat(connectionFactory.isCacheConsumers()).isFalse(); + assertThat(connectionFactory.isCacheProducers()).isTrue(); + assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(1); + }); } @Test public void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.consumers=true", - "spring.jms.cache.producers=false", + .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", "spring.jms.cache.session-cache-size=10") .run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); assertThat(context).hasSingleBean(CachingConnectionFactory.class); - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.isCacheConsumers()).isTrue(); assertThat(connectionFactory.isCacheProducers()).isFalse(); assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); @@ -108,8 +102,7 @@ public class ArtemisAutoConfigurationTests { .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); assertThat(context).doesNotHaveBean(CachingConnectionFactory.class); - assertThat(context.getBean(ConnectionFactory.class)) - .isInstanceOf(ActiveMQConnectionFactory.class); + assertThat(context.getBean(ConnectionFactory.class)).isInstanceOf(ActiveMQConnectionFactory.class); }); } @@ -118,14 +111,11 @@ public class ArtemisAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:native").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory connectionFactory = context - .getBean(ConnectionFactory.class); - assertThat(connectionFactory) - .isEqualTo(jmsTemplate.getConnectionFactory()); + ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory( connectionFactory); - assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", - 61616); + assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); assertThat(activeMQConnectionFactory.getUser()).isNull(); assertThat(activeMQConnectionFactory.getPassword()).isNull(); }); @@ -134,32 +124,26 @@ public class ArtemisAutoConfigurationTests { @Test public void nativeConnectionFactoryCustomHost() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native", - "spring.artemis.host:192.168.1.144", "spring.artemis.port:9876") + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.host:192.168.1.144", + "spring.artemis.port:9876") .run((context) -> assertNettyConnectionFactory( - getActiveMQConnectionFactory( - context.getBean(ConnectionFactory.class)), - "192.168.1.144", 9876)); + getActiveMQConnectionFactory(context.getBean(ConnectionFactory.class)), "192.168.1.144", 9876)); } @Test public void nativeConnectionFactoryCredentials() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native", - "spring.artemis.user:user", "spring.artemis.password:secret") + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", + "spring.artemis.password:secret") .run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory connectionFactory = context - .getBean(ConnectionFactory.class); - assertThat(connectionFactory) - .isEqualTo(jmsTemplate.getConnectionFactory()); + ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory( connectionFactory); - assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", - 61616); + assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); assertThat(activeMQConnectionFactory.getUser()).isEqualTo("user"); - assertThat(activeMQConnectionFactory.getPassword()) - .isEqualTo("secret"); + assertThat(activeMQConnectionFactory.getPassword()).isEqualTo("secret"); }); } @@ -167,46 +151,37 @@ public class ArtemisAutoConfigurationTests { public void embeddedConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:embedded").run((context) -> { - ArtemisProperties properties = context - .getBean(ArtemisProperties.class); + ArtemisProperties properties = context.getBean(ArtemisProperties.class); assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); assertThat(context).hasSingleBean(EmbeddedJMS.class); org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean( - org.apache.activemq.artemis.core.config.Configuration.class); + .getBean(org.apache.activemq.artemis.core.config.Configuration.class); assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); - assertInVmConnectionFactory(getActiveMQConnectionFactory( - context.getBean(ConnectionFactory.class))); + assertInVmConnectionFactory(getActiveMQConnectionFactory(context.getBean(ConnectionFactory.class))); }); } @Test public void embeddedConnectionFactoryByDefault() { // No mode is specified - this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(EmbeddedJMS.class); - org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean( - org.apache.activemq.artemis.core.config.Configuration.class); - assertThat(configuration.isPersistenceEnabled()).isFalse(); - assertThat(configuration.isSecurityEnabled()).isFalse(); - assertInVmConnectionFactory(getActiveMQConnectionFactory( - context.getBean(ConnectionFactory.class))); - }); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(EmbeddedJMS.class); + org.apache.activemq.artemis.core.config.Configuration configuration = context + .getBean(org.apache.activemq.artemis.core.config.Configuration.class); + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); + assertInVmConnectionFactory(getActiveMQConnectionFactory(context.getBean(ConnectionFactory.class))); + }); } @Test public void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.enabled:false") - .run((context) -> { + .withPropertyValues("spring.artemis.embedded.enabled:false").run((context) -> { assertThat(context).doesNotHaveBean(EmbeddedJMS.class); - assertNettyConnectionFactory( - getActiveMQConnectionFactory( - context.getBean(ConnectionFactory.class)), + assertNettyConnectionFactory(getActiveMQConnectionFactory(context.getBean(ConnectionFactory.class)), "localhost", 61616); }); } @@ -215,12 +190,10 @@ public class ArtemisAutoConfigurationTests { public void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:embedded", - "spring.artemis.embedded.enabled:false") + .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") .run((context) -> { assertThat(context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); - assertInVmConnectionFactory(getActiveMQConnectionFactory( - context.getBean(ConnectionFactory.class))); + assertInVmConnectionFactory(getActiveMQConnectionFactory(context.getBean(ConnectionFactory.class))); }); } @@ -241,20 +214,18 @@ public class ArtemisAutoConfigurationTests { @Test public void embeddedServerWithDestinationConfig() { - this.contextRunner.withUserConfiguration(DestinationConfiguration.class) - .run((context) -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("sampleQueue", true); - checker.checkTopic("sampleTopic", true); - }); + this.contextRunner.withUserConfiguration(DestinationConfiguration.class).run((context) -> { + DestinationChecker checker = new DestinationChecker(context); + checker.checkQueue("sampleQueue", true); + checker.checkTopic("sampleTopic", true); + }); } @Test public void embeddedServiceWithCustomJmsConfiguration() { // Ignored with custom config this.contextRunner.withUserConfiguration(CustomJmsConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2") - .run((context) -> { + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2").run((context) -> { DestinationChecker checker = new DestinationChecker(context); checker.checkQueue("custom", true); // See CustomJmsConfiguration checker.checkQueue("Queue1", true); @@ -265,9 +236,9 @@ public class ArtemisAutoConfigurationTests { @Test public void embeddedServiceWithCustomArtemisConfiguration() { this.contextRunner.withUserConfiguration(CustomArtemisConfiguration.class) - .run((context) -> assertThat(context.getBean( - org.apache.activemq.artemis.core.config.Configuration.class) - .getName()).isEqualTo("customFooBar")); + .run((context) -> assertThat( + context.getBean(org.apache.activemq.artemis.core.config.Configuration.class).getName()) + .isEqualTo("customFooBar")); } @Test @@ -278,8 +249,7 @@ public class ArtemisAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.embedded.queues=TestQueue", "spring.artemis.embedded.persistent:true", - "spring.artemis.embedded.dataDirectory:" - + dataFolder.getAbsolutePath()) + "spring.artemis.embedded.dataDirectory:" + dataFolder.getAbsolutePath()) .run((context) -> context.getBean(JmsTemplate.class).send("TestQueue", (session) -> session.createTextMessage(messageId))) .run((context) -> { @@ -295,35 +265,26 @@ public class ArtemisAutoConfigurationTests { @Test public void severalEmbeddedBrokers() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1") - .run((first) -> { - this.contextRunner - .withPropertyValues("spring.artemis.embedded.queues=Queue2") - .run((second) -> { - ArtemisProperties firstProperties = first - .getBean(ArtemisProperties.class); - ArtemisProperties secondProperties = second - .getBean(ArtemisProperties.class); - assertThat(firstProperties.getEmbedded().getServerId()) - .isLessThan(secondProperties.getEmbedded() - .getServerId()); - DestinationChecker firstChecker = new DestinationChecker( - first); - firstChecker.checkQueue("Queue1", true); - firstChecker.checkQueue("Queue2", true); - DestinationChecker secondChecker = new DestinationChecker( - second); - secondChecker.checkQueue("Queue2", true); - secondChecker.checkQueue("Queue1", true); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1").run((first) -> { + this.contextRunner.withPropertyValues("spring.artemis.embedded.queues=Queue2").run((second) -> { + ArtemisProperties firstProperties = first.getBean(ArtemisProperties.class); + ArtemisProperties secondProperties = second.getBean(ArtemisProperties.class); + assertThat(firstProperties.getEmbedded().getServerId()) + .isLessThan(secondProperties.getEmbedded().getServerId()); + DestinationChecker firstChecker = new DestinationChecker(first); + firstChecker.checkQueue("Queue1", true); + firstChecker.checkQueue("Queue2", true); + DestinationChecker secondChecker = new DestinationChecker(second); + secondChecker.checkQueue("Queue2", true); + secondChecker.checkQueue("Queue1", true); + }); }); } @Test public void connectToASpecificEmbeddedBroker() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.serverId=93", - "spring.artemis.embedded.queues=Queue1") + .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") .run((first) -> { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode=embedded", @@ -332,11 +293,9 @@ public class ArtemisAutoConfigurationTests { // Do not start a specific one "spring.artemis.embedded.enabled=false") .run((secondContext) -> { - DestinationChecker firstChecker = new DestinationChecker( - first); + DestinationChecker firstChecker = new DestinationChecker(first); firstChecker.checkQueue("Queue1", true); - DestinationChecker secondChecker = new DestinationChecker( - secondContext); + DestinationChecker secondChecker = new DestinationChecker(secondContext); secondChecker.checkQueue("Queue1", true); }); }); @@ -344,103 +303,79 @@ public class ArtemisAutoConfigurationTests { @Test public void defaultPoolConnectionFactoryIsApplied() { - this.contextRunner.withPropertyValues("spring.artemis.pool.enabled=true") - .run((context) -> { - assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)) - .hasSize(1); - JmsPoolConnectionFactory connectionFactory = context - .getBean(JmsPoolConnectionFactory.class); - JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); - assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) - .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo( - defaultFactory.getBlockIfSessionPoolIsFullTimeout()); - assertThat(connectionFactory.getConnectionIdleTimeout()) - .isEqualTo(defaultFactory.getConnectionIdleTimeout()); - assertThat(connectionFactory.getMaxConnections()) - .isEqualTo(defaultFactory.getMaxConnections()); - assertThat(connectionFactory.getMaxSessionsPerConnection()) - .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); - assertThat(connectionFactory.getConnectionCheckInterval()) - .isEqualTo(defaultFactory.getConnectionCheckInterval()); - assertThat(connectionFactory.isUseAnonymousProducers()) - .isEqualTo(defaultFactory.isUseAnonymousProducers()); - }); + this.contextRunner.withPropertyValues("spring.artemis.pool.enabled=true").run((context) -> { + assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); + JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); + assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) + .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) + .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); + assertThat(connectionFactory.getConnectionIdleTimeout()) + .isEqualTo(defaultFactory.getConnectionIdleTimeout()); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); + assertThat(connectionFactory.getMaxSessionsPerConnection()) + .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); + assertThat(connectionFactory.getConnectionCheckInterval()) + .isEqualTo(defaultFactory.getConnectionCheckInterval()); + assertThat(connectionFactory.isUseAnonymousProducers()).isEqualTo(defaultFactory.isUseAnonymousProducers()); + }); } @Test public void customPoolConnectionFactoryIsApplied() { this.contextRunner - .withPropertyValues("spring.artemis.pool.enabled=true", - "spring.artemis.pool.blockIfFull=false", - "spring.artemis.pool.blockIfFullTimeout=64", - "spring.artemis.pool.idleTimeout=512", - "spring.artemis.pool.maxConnections=256", - "spring.artemis.pool.maxSessionsPerConnection=1024", + .withPropertyValues("spring.artemis.pool.enabled=true", "spring.artemis.pool.blockIfFull=false", + "spring.artemis.pool.blockIfFullTimeout=64", "spring.artemis.pool.idleTimeout=512", + "spring.artemis.pool.maxConnections=256", "spring.artemis.pool.maxSessionsPerConnection=1024", "spring.artemis.pool.timeBetweenExpirationCheck=2048", "spring.artemis.pool.useAnonymousProducers=false") .run((context) -> { - assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)) - .hasSize(1); - JmsPoolConnectionFactory connectionFactory = context - .getBean(JmsPoolConnectionFactory.class); + assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo(64); - assertThat(connectionFactory.getConnectionIdleTimeout()) - .isEqualTo(512); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); + assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaxSessionsPerConnection()) - .isEqualTo(1024); - assertThat(connectionFactory.getConnectionCheckInterval()) - .isEqualTo(2048); + assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); + assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); }); } @Test public void poolConnectionFactoryConfiguration() { - this.contextRunner.withPropertyValues("spring.artemis.pool.enabled:true") - .run((context) -> { - ConnectionFactory factory = context.getBean(ConnectionFactory.class); - assertThat(factory).isInstanceOf(JmsPoolConnectionFactory.class); - context.getSourceApplicationContext().close(); - assertThat(factory.createConnection()).isNull(); - }); + this.contextRunner.withPropertyValues("spring.artemis.pool.enabled:true").run((context) -> { + ConnectionFactory factory = context.getBean(ConnectionFactory.class); + assertThat(factory).isInstanceOf(JmsPoolConnectionFactory.class); + context.getSourceApplicationContext().close(); + assertThat(factory.createConnection()).isNull(); + }); } - private ActiveMQConnectionFactory getActiveMQConnectionFactory( - ConnectionFactory connectionFactory) { + private ActiveMQConnectionFactory getActiveMQConnectionFactory(ConnectionFactory connectionFactory) { assertThat(connectionFactory).isInstanceOf(CachingConnectionFactory.class); - return (ActiveMQConnectionFactory) ((CachingConnectionFactory) connectionFactory) - .getTargetConnectionFactory(); + return (ActiveMQConnectionFactory) ((CachingConnectionFactory) connectionFactory).getTargetConnectionFactory(); } - private TransportConfiguration assertInVmConnectionFactory( - ActiveMQConnectionFactory connectionFactory) { - TransportConfiguration transportConfig = getSingleTransportConfiguration( - connectionFactory); - assertThat(transportConfig.getFactoryClassName()) - .isEqualTo(InVMConnectorFactory.class.getName()); + private TransportConfiguration assertInVmConnectionFactory(ActiveMQConnectionFactory connectionFactory) { + TransportConfiguration transportConfig = getSingleTransportConfiguration(connectionFactory); + assertThat(transportConfig.getFactoryClassName()).isEqualTo(InVMConnectorFactory.class.getName()); return transportConfig; } - private TransportConfiguration assertNettyConnectionFactory( - ActiveMQConnectionFactory connectionFactory, String host, int port) { - TransportConfiguration transportConfig = getSingleTransportConfiguration( - connectionFactory); - assertThat(transportConfig.getFactoryClassName()) - .isEqualTo(NettyConnectorFactory.class.getName()); + private TransportConfiguration assertNettyConnectionFactory(ActiveMQConnectionFactory connectionFactory, + String host, int port) { + TransportConfiguration transportConfig = getSingleTransportConfiguration(connectionFactory); + assertThat(transportConfig.getFactoryClassName()).isEqualTo(NettyConnectorFactory.class.getName()); assertThat(transportConfig.getParams().get("host")).isEqualTo(host); assertThat(transportConfig.getParams().get("port")).isEqualTo(port); return transportConfig; } - private TransportConfiguration getSingleTransportConfiguration( - ActiveMQConnectionFactory connectionFactory) { - TransportConfiguration[] transportConfigurations = connectionFactory - .getServerLocator().getStaticTransportConfigurations(); + private TransportConfiguration getSingleTransportConfiguration(ActiveMQConnectionFactory connectionFactory) { + TransportConfiguration[] transportConfigurations = connectionFactory.getServerLocator() + .getStaticTransportConfigurations(); assertThat(transportConfigurations.length).isEqualTo(1); return transportConfigurations[0]; } @@ -464,21 +399,19 @@ public class ArtemisAutoConfigurationTests { checkDestination(name, true, shouldExist); } - public void checkDestination(String name, final boolean pubSub, - final boolean shouldExist) { + public void checkDestination(String name, final boolean pubSub, final boolean shouldExist) { this.jmsTemplate.execute((SessionCallback) (session) -> { try { - Destination destination = this.destinationResolver - .resolveDestinationName(session, name, pubSub); + Destination destination = this.destinationResolver.resolveDestinationName(session, name, pubSub); if (!shouldExist) { - throw new IllegalStateException("Destination '" + name - + "' was not expected but got " + destination); + throw new IllegalStateException( + "Destination '" + name + "' was not expected but got " + destination); } } catch (JMSException ex) { if (shouldExist) { - throw new IllegalStateException("Destination '" + name - + "' was expected but got " + ex.getMessage()); + throw new IllegalStateException( + "Destination '" + name + "' was expected but got " + ex.getMessage()); } } return null; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java index 2d405fde94e..7c79510e803 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java @@ -41,18 +41,16 @@ public class ArtemisEmbeddedConfigurationFactoryTests { public void defaultDataDir() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setPersistent(true); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); - assertThat(configuration.getJournalDirectory()) - .startsWith(System.getProperty("java.io.tmpdir")).endsWith("/journal"); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); + assertThat(configuration.getJournalDirectory()).startsWith(System.getProperty("java.io.tmpdir")) + .endsWith("/journal"); } @Test public void persistenceSetup() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setPersistent(true); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.isPersistenceEnabled()).isTrue(); assertThat(configuration.getJournalType()).isEqualTo(JournalType.NIO); } @@ -60,8 +58,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { @Test public void generatedClusterPassword() { ArtemisProperties properties = new ArtemisProperties(); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getClusterPassword().length()).isEqualTo(36); } @@ -69,18 +66,15 @@ public class ArtemisEmbeddedConfigurationFactoryTests { public void specificClusterPassword() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setClusterPassword("password"); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getClusterPassword()).isEqualTo("password"); } @Test public void hasDlqExpiryQueueAddressSettingsConfigured() { ArtemisProperties properties = new ArtemisProperties(); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); - Map addressesSettings = configuration - .getAddressesSettings(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); + Map addressesSettings = configuration.getAddressesSettings(); assertThat((Object) addressesSettings.get("#").getDeadLetterAddress()) .isEqualTo(SimpleString.toSimpleString("DLQ")); assertThat((Object) addressesSettings.get("#").getExpiryAddress()) @@ -90,10 +84,8 @@ public class ArtemisEmbeddedConfigurationFactoryTests { @Test public void hasDlqExpiryQueueConfigured() { ArtemisProperties properties = new ArtemisProperties(); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); - List addressConfigurations = configuration - .getAddressConfigurations(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); + List addressConfigurations = configuration.getAddressConfigurations(); assertThat(addressConfigurations).hasSize(2); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java index c39ad54f4c4..a6a7e35f85b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java @@ -102,11 +102,10 @@ public class JmxAutoConfigurationTests { this.context.refresh(); MBeanExporter mBeanExporter = this.context.getBean(MBeanExporter.class); assertThat(mBeanExporter).isNotNull(); - MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils - .getField(mBeanExporter, "namingStrategy"); + MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(mBeanExporter, + "namingStrategy"); assertThat(naming).hasFieldOrPropertyWithValue("defaultDomain", "my-test-domain"); - assertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", - true); + assertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); } @Test @@ -136,11 +135,10 @@ public class JmxAutoConfigurationTests { @Test public void customJmxDomain() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomJmxDomainConfiguration.class, - JmxAutoConfiguration.class, IntegrationAutoConfiguration.class); + this.context.register(CustomJmxDomainConfiguration.class, JmxAutoConfiguration.class, + IntegrationAutoConfiguration.class); this.context.refresh(); - IntegrationMBeanExporter mbeanExporter = this.context - .getBean(IntegrationMBeanExporter.class); + IntegrationMBeanExporter mbeanExporter = this.context.getBean(IntegrationMBeanExporter.class); assertThat(mbeanExporter).hasFieldOrPropertyWithValue("domain", "foo.my"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index 2ad211a9c14..4916260f6d4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -71,88 +71,64 @@ public class JooqAutoConfigurationTests { @Test public void noDataSource() { - this.contextRunner - .run((context) -> assertThat(context.getBeansOfType(DSLContext.class)) - .isEmpty()); + this.contextRunner.run((context) -> assertThat(context.getBeansOfType(DSLContext.class)).isEmpty()); } @Test public void jooqWithoutTx() { - this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(PlatformTransactionManager.class); - assertThat(context).doesNotHaveBean(SpringTransactionProvider.class); - DSLContext dsl = context.getBean(DSLContext.class); - dsl.execute("create table jooqtest (name varchar(255) primary key);"); - dsl.transaction(new AssertFetch(dsl, - "select count(*) as total from jooqtest;", "0")); - dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('foo');")); - dsl.transaction(new AssertFetch(dsl, - "select count(*) as total from jooqtest;", "1")); - assertThatExceptionOfType(DataIntegrityViolationException.class) - .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');"))); - dsl.transaction(new AssertFetch(dsl, - "select count(*) as total from jooqtest;", "2")); - }); + this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class).run((context) -> { + assertThat(context).doesNotHaveBean(PlatformTransactionManager.class); + assertThat(context).doesNotHaveBean(SpringTransactionProvider.class); + DSLContext dsl = context.getBean(DSLContext.class); + dsl.execute("create table jooqtest (name varchar(255) primary key);"); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); + assertThatExceptionOfType(DataIntegrityViolationException.class) + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); + }); } @Test public void jooqWithTx() { - this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, - TxManagerConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(PlatformTransactionManager.class); DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().dialect()) - .isEqualTo(SQLDialect.HSQLDB); - dsl.execute( - "create table jooqtest_tx (name varchar(255) primary key);"); - dsl.transaction(new AssertFetch(dsl, - "select count(*) as total from jooqtest_tx;", "0")); - dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest_tx (name) values ('foo');")); - dsl.transaction(new AssertFetch(dsl, - "select count(*) as total from jooqtest_tx;", "1")); - assertThatExceptionOfType(DataIntegrityViolationException.class) - .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('bar');", + assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); + dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy( + () -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", "insert into jooqtest (name) values ('foo');"))); - dsl.transaction(new AssertFetch(dsl, - "select count(*) as total from jooqtest_tx;", "1")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); }); } @Test public void customProvidersArePickedUp() { - this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, - TxManagerConfiguration.class, TestRecordMapperProvider.class, - TestRecordUnmapperProvider.class, TestRecordListenerProvider.class, + this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class, + TestRecordMapperProvider.class, TestRecordUnmapperProvider.class, TestRecordListenerProvider.class, TestExecuteListenerProvider.class, TestVisitListenerProvider.class, - TestTransactionListenerProvider.class, TestExecutorProvider.class) - .run((context) -> { + TestTransactionListenerProvider.class, TestExecutorProvider.class).run((context) -> { DSLContext dsl = context.getBean(DSLContext.class); assertThat(dsl.configuration().recordMapperProvider().getClass()) .isEqualTo(TestRecordMapperProvider.class); assertThat(dsl.configuration().recordUnmapperProvider().getClass()) .isEqualTo(TestRecordUnmapperProvider.class); - assertThat(dsl.configuration().executorProvider().getClass()) - .isEqualTo(TestExecutorProvider.class); - assertThat(dsl.configuration().recordListenerProviders().length) - .isEqualTo(1); - ExecuteListenerProvider[] executeListenerProviders = dsl - .configuration().executeListenerProviders(); + assertThat(dsl.configuration().executorProvider().getClass()).isEqualTo(TestExecutorProvider.class); + assertThat(dsl.configuration().recordListenerProviders().length).isEqualTo(1); + ExecuteListenerProvider[] executeListenerProviders = dsl.configuration().executeListenerProviders(); assertThat(executeListenerProviders.length).isEqualTo(2); - assertThat(executeListenerProviders[0]) - .isInstanceOf(DefaultExecuteListenerProvider.class); - assertThat(executeListenerProviders[1]) - .isInstanceOf(TestExecuteListenerProvider.class); - assertThat(dsl.configuration().visitListenerProviders().length) - .isEqualTo(1); - assertThat(dsl.configuration().transactionListenerProviders().length) - .isEqualTo(1); + assertThat(executeListenerProviders[0]).isInstanceOf(DefaultExecuteListenerProvider.class); + assertThat(executeListenerProviders[1]).isInstanceOf(TestExecuteListenerProvider.class); + assertThat(dsl.configuration().visitListenerProviders().length).isEqualTo(1); + assertThat(dsl.configuration().transactionListenerProviders().length).isEqualTo(1); }); } @@ -160,9 +136,8 @@ public class JooqAutoConfigurationTests { public void relaxedBindingOfSqlDialect() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") - .run((context) -> assertThat( - context.getBean(org.jooq.Configuration.class).dialect()) - .isEqualTo(SQLDialect.POSTGRES)); + .run((context) -> assertThat(context.getBean(org.jooq.Configuration.class).dialect()) + .isEqualTo(SQLDialect.POSTGRES)); } private static class AssertFetch implements TransactionalRunnable { @@ -181,8 +156,7 @@ public class JooqAutoConfigurationTests { @Override public void run(org.jooq.Configuration configuration) { - assertThat(this.dsl.fetch(this.sql).getValue(0, 0).toString()) - .isEqualTo(this.expected); + assertThat(this.dsl.fetch(this.sql).getValue(0, 0).toString()).isEqualTo(this.expected); } } @@ -212,8 +186,7 @@ public class JooqAutoConfigurationTests { @Bean public DataSource jooqDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:jooqtest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:jooqtest").username("sa").build(); } } @@ -231,8 +204,7 @@ public class JooqAutoConfigurationTests { protected static class TestRecordMapperProvider implements RecordMapperProvider { @Override - public RecordMapper provide(RecordType recordType, - Class aClass) { + public RecordMapper provide(RecordType recordType, Class aClass) { return null; } @@ -241,8 +213,7 @@ public class JooqAutoConfigurationTests { protected static class TestRecordUnmapperProvider implements RecordUnmapperProvider { @Override - public RecordUnmapper provide( - Class aClass, RecordType recordType) { + public RecordUnmapper provide(Class aClass, RecordType recordType) { return null; } @@ -258,8 +229,7 @@ public class JooqAutoConfigurationTests { } @Order(100) - protected static class TestExecuteListenerProvider - implements ExecuteListenerProvider { + protected static class TestExecuteListenerProvider implements ExecuteListenerProvider { @Override public ExecuteListener provide() { @@ -277,8 +247,7 @@ public class JooqAutoConfigurationTests { } - protected static class TestTransactionListenerProvider - implements TransactionListenerProvider { + protected static class TestTransactionListenerProvider implements TransactionListenerProvider { @Override public TransactionListener provide() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java index c0c0c7de474..5974c44a9eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,8 +84,7 @@ public class JooqExceptionTranslatorTests { given(configuration.dialect()).willReturn(this.dialect); given(context.sqlException()).willReturn(this.sqlException); this.exceptionTranslator.exception(context); - ArgumentCaptor captor = ArgumentCaptor - .forClass(RuntimeException.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(RuntimeException.class); verify(context).exception(captor.capture()); assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java index 705779ee595..f5b866dbd89 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java @@ -65,24 +65,21 @@ public class JooqPropertiesTests { @Test public void determineSqlDialectWithKnownUrl() { JooqProperties properties = load(); - SQLDialect sqlDialect = properties - .determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb")); + SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb")); assertThat(sqlDialect).isEqualTo(SQLDialect.H2); } @Test public void determineSqlDialectWithKnownUrlAndUserConfig() { JooqProperties properties = load("spring.jooq.sql-dialect=mysql"); - SQLDialect sqlDialect = properties - .determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb")); + SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb")); assertThat(sqlDialect).isEqualTo(SQLDialect.MYSQL); } @Test public void determineSqlDialectWithUnknownUrl() { JooqProperties properties = load(); - SQLDialect sqlDialect = properties - .determineSqlDialect(mockDataSource("jdbc:unknown://localhost")); + SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:unknown://localhost")); assertThat(sqlDialect).isEqualTo(SQLDialect.DEFAULT); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java index 3ce3477b4b6..afcc9cb6a01 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java @@ -42,8 +42,7 @@ public class SqlDialectLookupTests { } @Test - public void getSqlDialectWhenDataSourceIsUnknownShouldReturnDefault() - throws Exception { + public void getSqlDialectWhenDataSourceIsUnknownShouldReturnDefault() throws Exception { testGetSqlDialect("jdbc:idontexist:", SQLDialect.DEFAULT); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java index 95c6639f5ce..b718fe3a93f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java @@ -42,8 +42,7 @@ public class JsonbAutoConfigurationWithNoProviderTests { @Test public void jsonbBacksOffWhenThereIsNoProvider() { - this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(Jsonb.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Jsonb.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java index 3d6e765b196..26325c2e719 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java @@ -53,8 +53,7 @@ public class KafkaAutoConfigurationIntegrationTests { private static final String ADMIN_CREATED_TOPIC = "adminCreatedTopic"; - public static final EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1, - true, TEST_TOPIC); + public static final EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1, true, TEST_TOPIC); private AnnotationConfigApplicationContext context; @@ -78,20 +77,16 @@ public class KafkaAutoConfigurationIntegrationTests { @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testEndToEnd() throws Exception { - load(KafkaConfig.class, - "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString(), - "spring.kafka.consumer.group-id=testGroup", - "spring.kafka.consumer.auto-offset-reset=earliest"); - KafkaTemplate template = this.context - .getBean(KafkaTemplate.class); + load(KafkaConfig.class, "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString(), + "spring.kafka.consumer.group-id=testGroup", "spring.kafka.consumer.auto-offset-reset=earliest"); + KafkaTemplate template = this.context.getBean(KafkaTemplate.class); template.send(TEST_TOPIC, "foo", "bar"); Listener listener = this.context.getBean(Listener.class); assertThat(listener.latch.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(listener.key).isEqualTo("foo"); assertThat(listener.received).isEqualTo("bar"); - DefaultKafkaProducerFactory producerFactory = this.context - .getBean(DefaultKafkaProducerFactory.class); + DefaultKafkaProducerFactory producerFactory = this.context.getBean(DefaultKafkaProducerFactory.class); Producer producer = producerFactory.createProducer(); assertThat(producer.partitionsFor(ADMIN_CREATED_TOPIC).size()).isEqualTo(10); producer.close(); @@ -101,16 +96,14 @@ public class KafkaAutoConfigurationIntegrationTests { public void testStreams() { load(KafkaStreamsConfig.class, "spring.application.name:my-app", "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString()); - assertThat(this.context.getBean(StreamsBuilderFactoryBean.class).isAutoStartup()) - .isTrue(); + assertThat(this.context.getBean(StreamsBuilderFactoryBean.class).isAutoStartup()).isTrue(); } private void load(Class config, String... environment) { this.context = doLoad(new Class[] { config }, environment); } - private AnnotationConfigApplicationContext doLoad(Class[] configs, - String... environment) { + private AnnotationConfigApplicationContext doLoad(Class[] configs, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(configs); applicationContext.register(KafkaAutoConfiguration.class); @@ -153,8 +146,7 @@ public class KafkaAutoConfigurationIntegrationTests { private volatile String key; @KafkaListener(topics = TEST_TOPIC) - public void listen(String foo, - @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) { + public void listen(String foo, @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) { this.received = foo; this.key = key; this.latch.countDown(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java index 5c1c3859045..e9974b0ae66 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java @@ -94,77 +94,49 @@ public class KafkaAutoConfigurationTests { public void consumerProperties() { this.contextRunner.withPropertyValues("spring.kafka.bootstrap-servers=foo:1234", "spring.kafka.properties.foo=bar", "spring.kafka.properties.baz=qux", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.ssl.key-password=p1", - "spring.kafka.ssl.key-store-location=classpath:ksLoc", - "spring.kafka.ssl.key-store-password=p2", - "spring.kafka.ssl.key-store-type=PKCS12", - "spring.kafka.ssl.trust-store-location=classpath:tsLoc", - "spring.kafka.ssl.trust-store-password=p3", - "spring.kafka.ssl.trust-store-type=PKCS12", - "spring.kafka.ssl.protocol=TLSv1.2", - "spring.kafka.consumer.auto-commit-interval=123", - "spring.kafka.consumer.max-poll-records=42", - "spring.kafka.consumer.auto-offset-reset=earliest", + "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.ssl.key-password=p1", + "spring.kafka.ssl.key-store-location=classpath:ksLoc", "spring.kafka.ssl.key-store-password=p2", + "spring.kafka.ssl.key-store-type=PKCS12", "spring.kafka.ssl.trust-store-location=classpath:tsLoc", + "spring.kafka.ssl.trust-store-password=p3", "spring.kafka.ssl.trust-store-type=PKCS12", + "spring.kafka.ssl.protocol=TLSv1.2", "spring.kafka.consumer.auto-commit-interval=123", + "spring.kafka.consumer.max-poll-records=42", "spring.kafka.consumer.auto-offset-reset=earliest", "spring.kafka.consumer.client-id=ccid", // test override common - "spring.kafka.consumer.enable-auto-commit=false", - "spring.kafka.consumer.fetch-max-wait=456", - "spring.kafka.consumer.properties.fiz.buz=fix.fox", - "spring.kafka.consumer.fetch-min-size=1KB", - "spring.kafka.consumer.group-id=bar", - "spring.kafka.consumer.heartbeat-interval=234", + "spring.kafka.consumer.enable-auto-commit=false", "spring.kafka.consumer.fetch-max-wait=456", + "spring.kafka.consumer.properties.fiz.buz=fix.fox", "spring.kafka.consumer.fetch-min-size=1KB", + "spring.kafka.consumer.group-id=bar", "spring.kafka.consumer.heartbeat-interval=234", "spring.kafka.consumer.key-deserializer = org.apache.kafka.common.serialization.LongDeserializer", "spring.kafka.consumer.value-deserializer = org.apache.kafka.common.serialization.IntegerDeserializer") .run((context) -> { DefaultKafkaConsumerFactory consumerFactory = context .getBean(DefaultKafkaConsumerFactory.class); - Map configs = consumerFactory - .getConfigurationProperties(); + Map configs = consumerFactory.getConfigurationProperties(); // common assertThat(configs.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)) .isEqualTo(Collections.singletonList("foo:1234")); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)) - .isEqualTo("p1"); - assertThat( - (String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLoc"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)) - .isEqualTo("p2"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat((String) configs - .get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLoc"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)) - .isEqualTo("p3"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)) - .isEqualTo("TLSv1.2"); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p1"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLoc"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p2"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLoc"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p3"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); // consumer - assertThat(configs.get(ConsumerConfig.CLIENT_ID_CONFIG)) - .isEqualTo("ccid"); // override - assertThat(configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)) - .isEqualTo(Boolean.FALSE); - assertThat(configs.get(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)) - .isEqualTo(123); - assertThat(configs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)) - .isEqualTo("earliest"); - assertThat(configs.get(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)) - .isEqualTo(456); - assertThat(configs.get(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)) - .isEqualTo(1024); - assertThat(configs.get(ConsumerConfig.GROUP_ID_CONFIG)) - .isEqualTo("bar"); - assertThat(configs.get(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)) - .isEqualTo(234); + assertThat(configs.get(ConsumerConfig.CLIENT_ID_CONFIG)).isEqualTo("ccid"); // override + assertThat(configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)).isEqualTo(Boolean.FALSE); + assertThat(configs.get(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)).isEqualTo(123); + assertThat(configs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)).isEqualTo("earliest"); + assertThat(configs.get(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)).isEqualTo(456); + assertThat(configs.get(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)).isEqualTo(1024); + assertThat(configs.get(ConsumerConfig.GROUP_ID_CONFIG)).isEqualTo("bar"); + assertThat(configs.get(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)).isEqualTo(234); assertThat(configs.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)) .isEqualTo(LongDeserializer.class); - assertThat( - configs.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)) - .isEqualTo(IntegerDeserializer.class); - assertThat(configs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)) - .isEqualTo(42); + assertThat(configs.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)) + .isEqualTo(IntegerDeserializer.class); + assertThat(configs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(42); assertThat(configs.get("foo")).isEqualTo("bar"); assertThat(configs.get("baz")).isEqualTo("qux"); assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); @@ -175,70 +147,48 @@ public class KafkaAutoConfigurationTests { @Test public void producerProperties() { this.contextRunner.withPropertyValues("spring.kafka.clientId=cid", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.producer.acks=all", "spring.kafka.producer.batch-size=2KB", - "spring.kafka.producer.bootstrap-servers=bar:1234", // test + "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.producer.acks=all", + "spring.kafka.producer.batch-size=2KB", "spring.kafka.producer.bootstrap-servers=bar:1234", // test // override - "spring.kafka.producer.buffer-memory=4KB", - "spring.kafka.producer.compression-type=gzip", + "spring.kafka.producer.buffer-memory=4KB", "spring.kafka.producer.compression-type=gzip", "spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.LongSerializer", - "spring.kafka.producer.retries=2", - "spring.kafka.producer.properties.fiz.buz=fix.fox", + "spring.kafka.producer.retries=2", "spring.kafka.producer.properties.fiz.buz=fix.fox", "spring.kafka.producer.ssl.key-password=p4", "spring.kafka.producer.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.producer.ssl.key-store-password=p5", - "spring.kafka.producer.ssl.key-store-type=PKCS12", + "spring.kafka.producer.ssl.key-store-password=p5", "spring.kafka.producer.ssl.key-store-type=PKCS12", "spring.kafka.producer.ssl.trust-store-location=classpath:tsLocP", "spring.kafka.producer.ssl.trust-store-password=p6", - "spring.kafka.producer.ssl.trust-store-type=PKCS12", - "spring.kafka.producer.ssl.protocol=TLSv1.2", + "spring.kafka.producer.ssl.trust-store-type=PKCS12", "spring.kafka.producer.ssl.protocol=TLSv1.2", "spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.IntegerSerializer") .run((context) -> { DefaultKafkaProducerFactory producerFactory = context .getBean(DefaultKafkaProducerFactory.class); - Map configs = producerFactory - .getConfigurationProperties(); + Map configs = producerFactory.getConfigurationProperties(); // common - assertThat(configs.get(ProducerConfig.CLIENT_ID_CONFIG)) - .isEqualTo("cid"); + assertThat(configs.get(ProducerConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); // producer assertThat(configs.get(ProducerConfig.ACKS_CONFIG)).isEqualTo("all"); - assertThat(configs.get(ProducerConfig.BATCH_SIZE_CONFIG)) - .isEqualTo(2048); + assertThat(configs.get(ProducerConfig.BATCH_SIZE_CONFIG)).isEqualTo(2048); assertThat(configs.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) .isEqualTo(Collections.singletonList("bar:1234")); // override - assertThat(configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG)) - .isEqualTo(4096L); - assertThat(configs.get(ProducerConfig.COMPRESSION_TYPE_CONFIG)) - .isEqualTo("gzip"); - assertThat(configs.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) - .isEqualTo(LongSerializer.class); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)) - .isEqualTo("p4"); - assertThat( - (String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)) - .isEqualTo("p5"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat((String) configs - .get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)) - .isEqualTo("p6"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)) - .isEqualTo("TLSv1.2"); + assertThat(configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG)).isEqualTo(4096L); + assertThat(configs.get(ProducerConfig.COMPRESSION_TYPE_CONFIG)).isEqualTo("gzip"); + assertThat(configs.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(LongSerializer.class); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); assertThat(configs.get(ProducerConfig.RETRIES_CONFIG)).isEqualTo(2); assertThat(configs.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) .isEqualTo(IntegerSerializer.class); - assertThat( - context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)) - .isEmpty(); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)) - .isEmpty(); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).isEmpty(); assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); }); @@ -246,116 +196,78 @@ public class KafkaAutoConfigurationTests { @Test public void adminProperties() { - this.contextRunner.withPropertyValues("spring.kafka.clientId=cid", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.admin.fail-fast=true", - "spring.kafka.admin.properties.fiz.buz=fix.fox", - "spring.kafka.admin.ssl.key-password=p4", - "spring.kafka.admin.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.admin.ssl.key-store-password=p5", - "spring.kafka.admin.ssl.key-store-type=PKCS12", - "spring.kafka.admin.ssl.trust-store-location=classpath:tsLocP", - "spring.kafka.admin.ssl.trust-store-password=p6", - "spring.kafka.admin.ssl.trust-store-type=PKCS12", - "spring.kafka.admin.ssl.protocol=TLSv1.2").run((context) -> { + this.contextRunner + .withPropertyValues("spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", + "spring.kafka.admin.fail-fast=true", "spring.kafka.admin.properties.fiz.buz=fix.fox", + "spring.kafka.admin.ssl.key-password=p4", + "spring.kafka.admin.ssl.key-store-location=classpath:ksLocP", + "spring.kafka.admin.ssl.key-store-password=p5", "spring.kafka.admin.ssl.key-store-type=PKCS12", + "spring.kafka.admin.ssl.trust-store-location=classpath:tsLocP", + "spring.kafka.admin.ssl.trust-store-password=p6", + "spring.kafka.admin.ssl.trust-store-type=PKCS12", "spring.kafka.admin.ssl.protocol=TLSv1.2") + .run((context) -> { KafkaAdmin admin = context.getBean(KafkaAdmin.class); Map configs = admin.getConfig(); // common - assertThat(configs.get(AdminClientConfig.CLIENT_ID_CONFIG)) - .isEqualTo("cid"); + assertThat(configs.get(AdminClientConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); // admin - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)) - .isEqualTo("p4"); - assertThat( - (String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)) - .isEqualTo("p5"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat((String) configs - .get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)) - .isEqualTo("p6"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)) - .isEqualTo("TLSv1.2"); - assertThat( - context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)) - .isEmpty(); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); - assertThat(admin).hasFieldOrPropertyWithValue( - "fatalIfBrokerNotAvailable", true); + assertThat(admin).hasFieldOrPropertyWithValue("fatalIfBrokerNotAvailable", true); }); } @SuppressWarnings("unchecked") @Test public void streamsProperties() { - this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.kafka.client-id=cid", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.application.name=appName", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.streams.auto-startup=false", - "spring.kafka.streams.cache-max-size-buffering=1KB", - "spring.kafka.streams.client-id=override", - "spring.kafka.streams.properties.fiz.buz=fix.fox", - "spring.kafka.streams.replication-factor=2", - "spring.kafka.streams.state-dir=/tmp/state", - "spring.kafka.streams.ssl.key-password=p7", - "spring.kafka.streams.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.streams.ssl.key-store-password=p8", - "spring.kafka.streams.ssl.key-store-type=PKCS12", - "spring.kafka.streams.ssl.trust-store-location=classpath:tsLocP", - "spring.kafka.streams.ssl.trust-store-password=p9", - "spring.kafka.streams.ssl.trust-store-type=PKCS12", - "spring.kafka.streams.ssl.protocol=TLSv1.2") - .run((context) -> { - Properties configs = context.getBean( - KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class).asProperties(); - assertThat((List) configs - .get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - assertThat( - configs.get(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG)) - .isEqualTo(1024); - assertThat(configs.get(StreamsConfig.CLIENT_ID_CONFIG)) - .isEqualTo("override"); - assertThat(configs.get(StreamsConfig.REPLICATION_FACTOR_CONFIG)) - .isEqualTo(2); - assertThat(configs.get(StreamsConfig.STATE_DIR_CONFIG)) - .isEqualTo("/tmp/state"); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)) - .isEqualTo("p7"); - assertThat( - (String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)) - .isEqualTo("p8"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat((String) configs - .get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)) - .isEqualTo("p9"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)) - .isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)) - .isEqualTo("TLSv1.2"); - assertThat( - context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)) - .isEmpty(); + this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).withPropertyValues( + "spring.kafka.client-id=cid", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.application.name=appName", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", + "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cache-max-size-buffering=1KB", + "spring.kafka.streams.client-id=override", "spring.kafka.streams.properties.fiz.buz=fix.fox", + "spring.kafka.streams.replication-factor=2", "spring.kafka.streams.state-dir=/tmp/state", + "spring.kafka.streams.ssl.key-password=p7", + "spring.kafka.streams.ssl.key-store-location=classpath:ksLocP", + "spring.kafka.streams.ssl.key-store-password=p8", "spring.kafka.streams.ssl.key-store-type=PKCS12", + "spring.kafka.streams.ssl.trust-store-location=classpath:tsLocP", + "spring.kafka.streams.ssl.trust-store-password=p9", "spring.kafka.streams.ssl.trust-store-type=PKCS12", + "spring.kafka.streams.ssl.protocol=TLSv1.2").run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + assertThat(configs.get(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG)).isEqualTo(1024); + assertThat(configs.get(StreamsConfig.CLIENT_ID_CONFIG)).isEqualTo("override"); + assertThat(configs.get(StreamsConfig.REPLICATION_FACTOR_CONFIG)).isEqualTo(2); + assertThat(configs.get(StreamsConfig.STATE_DIR_CONFIG)).isEqualTo("/tmp/state"); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p7"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p8"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p9"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); - assertThat(context.getBean( - KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME)) - .isNotNull(); + assertThat(context.getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME)) + .isNotNull(); }); } @@ -367,33 +279,31 @@ public class KafkaAutoConfigurationTests { "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.streams.auto-startup=false") .run((context) -> { - Properties configs = context.getBean( - KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class).asProperties(); - assertThat((List) configs - .get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)) - .isEqualTo("my-test-app"); + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)).isEqualTo("my-test-app"); }); } @Test public void streamsWithCustomKafkaConfiguration() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, - TestKafkaStreamsConfiguration.class) + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) .withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.streams.auto-startup=false") .run((context) -> { - Properties configs = context.getBean( - KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class).asProperties(); + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); assertThat(configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) .isEqualTo("localhost:9094, localhost:9095"); - assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)) - .isEqualTo("test-id"); + assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)).isEqualTo("test-id"); }); } @@ -407,32 +317,28 @@ public class KafkaAutoConfigurationTests { "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.streams.auto-startup=false") .run((context) -> { - Properties configs = context.getBean( - KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class).asProperties(); - assertThat((List) configs - .get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - verify(context.getBean("&firstStreamsBuilderFactoryBean", - StreamsBuilderFactoryBean.class), never()) - .setAutoStartup(false); - verify(context.getBean("&secondStreamsBuilderFactoryBean", - StreamsBuilderFactoryBean.class), never()) - .setAutoStartup(false); + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + verify(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class), never()) + .setAutoStartup(false); + verify(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class), + never()).setAutoStartup(false); }); } @Test public void streamsApplicationIdIsMandatory() { - this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure() - .hasMessageContaining("spring.kafka.streams.application-id") - .hasMessageContaining( - "This property is mandatory and fallback 'spring.application.name' is not set either."); + this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("spring.kafka.streams.application-id") + .hasMessageContaining( + "This property is mandatory and fallback 'spring.application.name' is not set either."); - }); + }); } @Test @@ -448,68 +354,48 @@ public class KafkaAutoConfigurationTests { public void listenerProperties() { this.contextRunner .withPropertyValues("spring.kafka.template.default-topic=testTopic", - "spring.kafka.listener.ack-mode=MANUAL", - "spring.kafka.listener.client-id=client", - "spring.kafka.listener.ack-count=123", - "spring.kafka.listener.ack-time=456", - "spring.kafka.listener.concurrency=3", - "spring.kafka.listener.poll-timeout=2000", - "spring.kafka.listener.no-poll-threshold=2.5", - "spring.kafka.listener.type=batch", - "spring.kafka.listener.idle-event-interval=1s", - "spring.kafka.listener.monitor-interval=45", + "spring.kafka.listener.ack-mode=MANUAL", "spring.kafka.listener.client-id=client", + "spring.kafka.listener.ack-count=123", "spring.kafka.listener.ack-time=456", + "spring.kafka.listener.concurrency=3", "spring.kafka.listener.poll-timeout=2000", + "spring.kafka.listener.no-poll-threshold=2.5", "spring.kafka.listener.type=batch", + "spring.kafka.listener.idle-event-interval=1s", "spring.kafka.listener.monitor-interval=45", "spring.kafka.listener.log-container-config=true", - "spring.kafka.listener.missing-topics-fatal=false", - "spring.kafka.jaas.enabled=true", - "spring.kafka.producer.transaction-id-prefix=foo", - "spring.kafka.jaas.login-module=foo", - "spring.kafka.jaas.control-flag=REQUISITE", - "spring.kafka.jaas.options.useKeyTab=true") + "spring.kafka.listener.missing-topics-fatal=false", "spring.kafka.jaas.enabled=true", + "spring.kafka.producer.transaction-id-prefix=foo", "spring.kafka.jaas.login-module=foo", + "spring.kafka.jaas.control-flag=REQUISITE", "spring.kafka.jaas.options.useKeyTab=true") .run((context) -> { DefaultKafkaProducerFactory producerFactory = context .getBean(DefaultKafkaProducerFactory.class); DefaultKafkaConsumerFactory consumerFactory = context .getBean(DefaultKafkaConsumerFactory.class); - KafkaTemplate kafkaTemplate = context - .getBean(KafkaTemplate.class); + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context .getBean(KafkaListenerContainerFactory.class); - assertThat(kafkaTemplate.getMessageConverter()) - .isInstanceOf(MessagingMessageConverter.class); - assertThat(kafkaTemplate).hasFieldOrPropertyWithValue( - "producerFactory", producerFactory); + assertThat(kafkaTemplate.getMessageConverter()).isInstanceOf(MessagingMessageConverter.class); + assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("producerFactory", producerFactory); assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); - assertThat(kafkaListenerContainerFactory.getConsumerFactory()) - .isEqualTo(consumerFactory); - ContainerProperties containerProperties = kafkaListenerContainerFactory - .getContainerProperties(); - assertThat(containerProperties.getAckMode()) - .isEqualTo(AckMode.MANUAL); + assertThat(kafkaListenerContainerFactory.getConsumerFactory()).isEqualTo(consumerFactory); + ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); + assertThat(containerProperties.getAckMode()).isEqualTo(AckMode.MANUAL); assertThat(containerProperties.getClientId()).isEqualTo("client"); assertThat(containerProperties.getAckCount()).isEqualTo(123); assertThat(containerProperties.getAckTime()).isEqualTo(456L); assertThat(containerProperties.getPollTimeout()).isEqualTo(2000L); assertThat(containerProperties.getNoPollThreshold()).isEqualTo(2.5f); - assertThat(containerProperties.getIdleEventInterval()) - .isEqualTo(1000L); + assertThat(containerProperties.getIdleEventInterval()).isEqualTo(1000L); assertThat(containerProperties.getMonitorInterval()).isEqualTo(45); assertThat(containerProperties.isLogContainerConfig()).isTrue(); assertThat(containerProperties.isMissingTopicsFatal()).isFalse(); - assertThat(ReflectionTestUtils.getField(kafkaListenerContainerFactory, - "concurrency")).isEqualTo(3); + assertThat(ReflectionTestUtils.getField(kafkaListenerContainerFactory, "concurrency")).isEqualTo(3); assertThat(kafkaListenerContainerFactory.isBatchListener()).isTrue(); - assertThat( - context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)) - .hasSize(1); - KafkaJaasLoginModuleInitializer jaas = context - .getBean(KafkaJaasLoginModuleInitializer.class); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).hasSize(1); + KafkaJaasLoginModuleInitializer jaas = context.getBean(KafkaJaasLoginModuleInitializer.class); assertThat(jaas).hasFieldOrPropertyWithValue("loginModule", "foo"); assertThat(jaas).hasFieldOrPropertyWithValue("controlFlag", AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)) - .hasSize(1); - assertThat(((Map) ReflectionTestUtils.getField(jaas, - "options"))).containsExactly(entry("useKeyTab", "true")); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).hasSize(1); + assertThat(((Map) ReflectionTestUtils.getField(jaas, "options"))) + .containsExactly(entry("useKeyTab", "true")); }); } @@ -519,46 +405,38 @@ public class KafkaAutoConfigurationTests { Listener listenerProperties = new KafkaProperties().getListener(); AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context .getBean(KafkaListenerContainerFactory.class); - ContainerProperties containerProperties = kafkaListenerContainerFactory - .getContainerProperties(); - assertThat(containerProperties.isMissingTopicsFatal()) - .isEqualTo(listenerProperties.isMissingTopicsFatal()); + ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); + assertThat(containerProperties.isMissingTopicsFatal()).isEqualTo(listenerProperties.isMissingTopicsFatal()); }); } @Test public void testKafkaTemplateRecordMessageConverters() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") - .run((context) -> { - KafkaTemplate kafkaTemplate = context - .getBean(KafkaTemplate.class); - assertThat(kafkaTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); + .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); + assertThat(kafkaTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); }); } @Test public void testConcurrentKafkaListenerContainerFactoryWithCustomMessageConverter() { - this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue( - "messageConverter", context.getBean("myMessageConverter")); - }); + this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class).run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("messageConverter", + context.getBean("myMessageConverter")); + }); } @Test public void testConcurrentKafkaListenerContainerFactoryInBatchModeWithCustomMessageConverter() { this.contextRunner - .withUserConfiguration(BatchMessageConverterConfiguration.class, - MessageConverterConfiguration.class) + .withUserConfiguration(BatchMessageConverterConfiguration.class, MessageConverterConfiguration.class) .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue( - "messageConverter", + assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("messageConverter", context.getBean("myBatchMessageConverter")); }); } @@ -569,40 +447,32 @@ public class KafkaAutoConfigurationTests { .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); - Object messageConverter = ReflectionTestUtils - .getField(kafkaListenerContainerFactory, "messageConverter"); - assertThat(messageConverter) - .isInstanceOf(BatchMessagingMessageConverter.class); - assertThat(((BatchMessageConverter) messageConverter) - .getRecordMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); + Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, + "messageConverter"); + assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); + assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()) + .isSameAs(context.getBean("myMessageConverter")); }); } @Test public void testConcurrentKafkaListenerContainerFactoryInBatchModeWithNoMessageConverter() { - this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch") - .run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - Object messageConverter = ReflectionTestUtils - .getField(kafkaListenerContainerFactory, "messageConverter"); - assertThat(messageConverter) - .isInstanceOf(BatchMessagingMessageConverter.class); - assertThat(((BatchMessageConverter) messageConverter) - .getRecordMessageConverter()).isNull(); - }); + this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, "messageConverter"); + assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); + assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()).isNull(); + }); } @Test public void testConcurrentKafkaListenerContainerFactoryWithCustomErrorHandler() { - this.contextRunner.withUserConfiguration(ErrorHandlerConfiguration.class) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", - context.getBean("errorHandler")); - }); + this.contextRunner.withUserConfiguration(ErrorHandlerConfiguration.class).run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", context.getBean("errorHandler")); + }); } @Test @@ -618,12 +488,11 @@ public class KafkaAutoConfigurationTests { @Test public void concurrentKafkaListenerContainerFactoryInBatchModeWhenBatchErrorHandlerNotAvailableShouldBeNull() { - this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch") - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", null); - }); + this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", null); + }); } @Test @@ -638,23 +507,19 @@ public class KafkaAutoConfigurationTests { @Test public void testConcurrentKafkaListenerContainerFactoryWithDefaultTransactionManager() { - this.contextRunner - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") - .run((context) -> { - assertThat(context).hasSingleBean(KafkaAwareTransactionManager.class); - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory.getContainerProperties().getTransactionManager()) - .isSameAs( - context.getBean(KafkaAwareTransactionManager.class)); - }); + this.contextRunner.withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { + assertThat(context).hasSingleBean(KafkaAwareTransactionManager.class); + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory.getContainerProperties().getTransactionManager()) + .isSameAs(context.getBean(KafkaAwareTransactionManager.class)); + }); } @Test public void testConcurrentKafkaListenerContainerFactoryWithCustomTransactionManager() { this.contextRunner.withUserConfiguration(TransactionManagerConfiguration.class) - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") - .run((context) -> { + .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory.getContainerProperties().getTransactionManager()) @@ -664,27 +529,22 @@ public class KafkaAutoConfigurationTests { @Test public void testConcurrentKafkaListenerContainerFactoryWithCustomAfterRollbackProcessor() { - this.contextRunner - .withUserConfiguration(AfterRollbackProcessorConfiguration.class) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue( - "afterRollbackProcessor", - context.getBean("afterRollbackProcessor")); - }); + this.contextRunner.withUserConfiguration(AfterRollbackProcessorConfiguration.class).run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("afterRollbackProcessor", + context.getBean("afterRollbackProcessor")); + }); } @Test public void testConcurrentKafkaListenerContainerFactoryWithCustomRebalanceListener() { - this.contextRunner.withUserConfiguration(RebalanceListenerConfiguration.class) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory.getContainerProperties()) - .hasFieldOrPropertyWithValue("consumerRebalanceListener", - context.getBean("rebalanceListener")); - }); + this.contextRunner.withUserConfiguration(RebalanceListenerConfiguration.class).run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory.getContainerProperties()).hasFieldOrPropertyWithValue("consumerRebalanceListener", + context.getBean("rebalanceListener")); + }); } @Test @@ -692,8 +552,8 @@ public class KafkaAutoConfigurationTests { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue( - "replyTemplate", context.getBean(KafkaTemplate.class)); + assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("replyTemplate", + context.getBean(KafkaTemplate.class)); }); } @@ -744,8 +604,7 @@ public class KafkaAutoConfigurationTests { @Primary public PlatformTransactionManager chainedTransactionManager( KafkaTransactionManager kafkaTransactionManager) { - return new ChainedKafkaTransactionManager( - kafkaTransactionManager); + return new ChainedKafkaTransactionManager(kafkaTransactionManager); } } @@ -784,8 +643,7 @@ public class KafkaAutoConfigurationTests { @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME) public KafkaStreamsConfiguration kafkaStreamsConfiguration() { Map streamsProperties = new HashMap<>(); - streamsProperties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, - "localhost:9094, localhost:9095"); + streamsProperties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9094, localhost:9095"); streamsProperties.put(StreamsConfig.APPLICATION_ID_CONFIG, "test-id"); return new KafkaStreamsConfiguration(streamsProperties); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java index 4642c96a302..16df62e88d0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java @@ -53,48 +53,37 @@ public class LdapAutoConfigurationTests { @Test public void contextSourceWithSingleUrl() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123") - .run((context) -> { - LdapContextSource contextSource = context - .getBean(LdapContextSource.class); - assertThat(contextSource.getUrls()) - .containsExactly("ldap://localhost:123"); - }); + this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123").run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123"); + }); } @Test public void contextSourceWithSeveralUrls() { - this.contextRunner - .withPropertyValues( - "spring.ldap.urls:ldap://localhost:123,ldap://mycompany:123") + this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123,ldap://mycompany:123") .run((context) -> { - LdapContextSource contextSource = context - .getBean(LdapContextSource.class); + LdapContextSource contextSource = context.getBean(LdapContextSource.class); LdapProperties ldapProperties = context.getBean(LdapProperties.class); - assertThat(contextSource.getUrls()).containsExactly( - "ldap://localhost:123", "ldap://mycompany:123"); + assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123", "ldap://mycompany:123"); assertThat(ldapProperties.getUrls()).hasSize(2); }); } @Test public void contextSourceWithExtraCustomization() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123", - "spring.ldap.username:root", "spring.ldap.password:secret", - "spring.ldap.anonymous-read-only:true", + this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", + "spring.ldap.password:secret", "spring.ldap.anonymous-read-only:true", "spring.ldap.base:cn=SpringDevelopers", - "spring.ldap.baseEnvironment.java.naming.security.authentication:DIGEST-MD5") - .run((context) -> { - LdapContextSource contextSource = context - .getBean(LdapContextSource.class); + "spring.ldap.baseEnvironment.java.naming.security.authentication:DIGEST-MD5").run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); assertThat(contextSource.getUserDn()).isEqualTo("root"); assertThat(contextSource.getPassword()).isEqualTo("secret"); assertThat(contextSource.isAnonymousReadOnly()).isTrue(); - assertThat(contextSource.getBaseLdapPathAsString()) - .isEqualTo("cn=SpringDevelopers"); + assertThat(contextSource.getBaseLdapPathAsString()).isEqualTo("cn=SpringDevelopers"); LdapProperties ldapProperties = context.getBean(LdapProperties.class); - assertThat(ldapProperties.getBaseEnvironment()).containsEntry( - "java.naming.security.authentication", "DIGEST-MD5"); + assertThat(ldapProperties.getBaseEnvironment()).containsEntry("java.naming.security.authentication", + "DIGEST-MD5"); }); } @@ -106,14 +95,11 @@ public class LdapAutoConfigurationTests { @Test public void contextSourceWithUserProvidedPooledContextSource() { - this.contextRunner.withUserConfiguration(PooledContextSourceConfig.class) - .run((context) -> { - LdapContextSource contextSource = context - .getBean(LdapContextSource.class); - assertThat(contextSource.getUrls()) - .containsExactly("ldap://localhost:389"); - assertThat(contextSource.isAnonymousReadOnly()).isFalse(); - }); + this.contextRunner.withUserConfiguration(PooledContextSourceConfig.class).run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:389"); + assertThat(contextSource.isAnonymousReadOnly()).isFalse(); + }); } @Configuration(proxyBeanMethods = false) @@ -121,10 +107,8 @@ public class LdapAutoConfigurationTests { @Bean @Primary - public PooledContextSource pooledContextSource( - LdapContextSource ldapContextSource) { - PooledContextSource pooledContextSource = new PooledContextSource( - new PoolConfig()); + public PooledContextSource pooledContextSource(LdapContextSource ldapContextSource) { + PooledContextSource pooledContextSource = new PooledContextSource(new PoolConfig()); pooledContextSource.setContextSource(ldapContextSource); return pooledContextSource; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java index 078f371da46..292f17df6be 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java @@ -44,56 +44,45 @@ import static org.assertj.core.api.Assertions.assertThat; public class EmbeddedLdapAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); @Test public void testSetDefaultPort() { this.contextRunner - .withPropertyValues("spring.ldap.embedded.port:1234", - "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .withPropertyValues("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org") .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.getListenPort()).isEqualTo(1234); }); } @Test public void testRandomPortWithEnvironment() { - this.contextRunner - .withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); - assertThat(server.getListenPort()).isEqualTo(context.getEnvironment() - .getProperty("local.ldap.port", Integer.class)); - }); + this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getListenPort()) + .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); + }); } @Test public void testRandomPortWithValueAnnotation() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .applyTo(context); - context.register(EmbeddedLdapAutoConfiguration.class, - LdapClientConfiguration.class, + TestPropertyValues.of("spring.ldap.embedded.base-dn:dc=spring,dc=org").applyTo(context); + context.register(EmbeddedLdapAutoConfiguration.class, LdapClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class); context.refresh(); LDAPConnection connection = context.getBean(LDAPConnection.class); - assertThat(connection.getConnectedPort()).isEqualTo( - context.getEnvironment().getProperty("local.ldap.port", Integer.class)); + assertThat(connection.getConnectedPort()) + .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); } @Test public void testSetCredentials() { - this.contextRunner - .withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", - "spring.ldap.embedded.credential.username:uid=root", - "spring.ldap.embedded.credential.password:boot") + this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", + "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot") .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); BindResult result = server.bind("uid=root", "boot"); assertThat(result).isNotNull(); }); @@ -101,87 +90,59 @@ public class EmbeddedLdapAutoConfigurationTests { @Test public void testSetPartitionSuffix() { - this.contextRunner - .withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); - assertThat(server.getBaseDNs()) - .containsExactly(new DN("dc=spring,dc=org")); - }); + this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getBaseDNs()).containsExactly(new DN("dc=spring,dc=org")); + }); } @Test public void testSetLdifFile() { - this.contextRunner - .withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); - assertThat(server - .countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")) - .isEqualTo(5); - }); + this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); + }); } @Test public void testQueryEmbeddedLdap() { - this.contextRunner - .withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)) - .run((context) -> { - assertThat(context.getBeanNamesForType(LdapTemplate.class).length) - .isEqualTo(1); + this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") + .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)).run((context) -> { + assertThat(context.getBeanNamesForType(LdapTemplate.class).length).isEqualTo(1); LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); - assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")) - .hasSize(4); + assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")).hasSize(4); }); } @Test public void testDisableSchemaValidation() { - this.contextRunner - .withPropertyValues("spring.ldap.embedded.validation.enabled:false", - "spring.ldap.embedded.base-dn:dc=spring,dc=org") - .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); + this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.enabled:false", + "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.getSchema()).isNull(); }); } @Test public void testCustomSchemaValidation() { - this.contextRunner.withPropertyValues( - "spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", + this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")) - .isNotNull(); - assertThat( - server.getSchema().getAttributeType("exampleAttributeName")) - .isNotNull(); + assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")).isNotNull(); + assertThat(server.getSchema().getAttributeType("exampleAttributeName")).isNotNull(); }); } @Test public void testMultiBaseDn() { - this.contextRunner - .withPropertyValues( - "spring.ldap.embedded.ldif:classpath:schema-multi-basedn.ldif", - "spring.ldap.embedded.base-dn[0]:dc=spring,dc=org", - "spring.ldap.embedded.base-dn[1]:dc=pivotal,dc=io") + this.contextRunner.withPropertyValues("spring.ldap.embedded.ldif:classpath:schema-multi-basedn.ldif", + "spring.ldap.embedded.base-dn[0]:dc=spring,dc=org", "spring.ldap.embedded.base-dn[1]:dc=pivotal,dc=io") .run((context) -> { - InMemoryDirectoryServer server = context - .getBean(InMemoryDirectoryServer.class); - assertThat(server - .countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")) - .isEqualTo(5); - assertThat(server.countEntriesBelow("c=Sweden,dc=pivotal,dc=io")) - .isEqualTo(2); + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); + assertThat(server.countEntriesBelow("c=Sweden,dc=pivotal,dc=io")).isEqualTo(2); }); } @@ -189,8 +150,7 @@ public class EmbeddedLdapAutoConfigurationTests { static class LdapClientConfiguration { @Bean - public LDAPConnection ldapConnection(@Value("${local.ldap.port}") int port) - throws LDAPException { + public LDAPConnection ldapConnection(@Value("${local.ldap.port}") int port) throws LDAPException { LDAPConnection con = new LDAPConnection(); con.connect("localhost", port); return con; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java index afcc9e8f840..991685cdfa7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java @@ -69,9 +69,8 @@ public class LiquibaseAutoConfigurationTests { @BeforeEach public void init() { - new LiquibaseServiceLocatorApplicationListener().onApplicationEvent( - new ApplicationStartingEvent(new SpringApplication(Object.class), - new String[0])); + new LiquibaseServiceLocatorApplicationListener() + .onApplicationEvent(new ApplicationStartingEvent(new SpringApplication(Object.class), new String[0])); } private ApplicationContextRunner contextRunner = new ApplicationContextRunner() @@ -80,19 +79,16 @@ public class LiquibaseAutoConfigurationTests { @Test public void backsOffWithNoDataSourceBeanAndNoLiquibaseUrl() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); } @Test public void createsDataSourceWithNoDataSourceBeanAndLiquibaseUrl() { - this.contextRunner - .withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:liquibase") + this.contextRunner.withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:liquibase") .run(assertLiquibase((liquibase) -> { DataSource dataSource = liquibase.getDataSource(); assertThat(((HikariDataSource) dataSource).isClosed()).isTrue(); - assertThat(((HikariDataSource) dataSource).getJdbcUrl()) - .isEqualTo("jdbc:hsqldb:mem:liquibase"); + assertThat(((HikariDataSource) dataSource).getJdbcUrl()).isEqualTo("jdbc:hsqldb:mem:liquibase"); })); } @@ -100,8 +96,7 @@ public class LiquibaseAutoConfigurationTests { public void defaultSpringLiquibase() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .run(assertLiquibase((liquibase) -> { - assertThat(liquibase.getChangeLog()).isEqualTo( - "classpath:/db/changelog/db.changelog-master.yaml"); + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); assertThat(liquibase.getContexts()).isNull(); assertThat(liquibase.getDefaultSchema()).isNull(); assertThat(liquibase.isDropFirst()).isFalse(); @@ -111,8 +106,7 @@ public class LiquibaseAutoConfigurationTests { @Test public void changelogXml() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"))); } @@ -120,19 +114,16 @@ public class LiquibaseAutoConfigurationTests { @Test public void changelogJson() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") - .run(assertLiquibase( - (liquibase) -> assertThat(liquibase.getChangeLog()).isEqualTo( - "classpath:/db/changelog/db.changelog-override.json"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.json"))); } @Test public void changelogSql() { Assume.javaEight(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) .isEqualTo("classpath:/db/changelog/db.changelog-override.sql"))); } @@ -142,14 +133,11 @@ public class LiquibaseAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .run(assertLiquibase((liquibase) -> { LiquibaseProperties properties = new LiquibaseProperties(); - assertThat(liquibase.getDatabaseChangeLogTable()) - .isEqualTo(properties.getDatabaseChangeLogTable()); + assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo(properties.getDatabaseChangeLogTable()); assertThat(liquibase.getDatabaseChangeLogLockTable()) .isEqualTo(properties.getDatabaseChangeLogLockTable()); - assertThat(liquibase.isDropFirst()) - .isEqualTo(properties.isDropFirst()); - assertThat(liquibase.isTestRollbackOnUpdate()) - .isEqualTo(properties.isTestRollbackOnUpdate()); + assertThat(liquibase.isDropFirst()).isEqualTo(properties.isDropFirst()); + assertThat(liquibase.isTestRollbackOnUpdate()).isEqualTo(properties.isTestRollbackOnUpdate()); })); } @@ -157,17 +145,14 @@ public class LiquibaseAutoConfigurationTests { public void overrideContexts() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.contexts:test, production") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()) - .isEqualTo("test, production"))); + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()).isEqualTo("test, production"))); } @Test public void overrideDefaultSchema() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.default-schema:public") - .run(assertLiquibase( - (liquibase) -> assertThat(liquibase.getDefaultSchema()) - .isEqualTo("public"))); + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getDefaultSchema()).isEqualTo("public"))); } @Test @@ -181,18 +166,13 @@ public class LiquibaseAutoConfigurationTests { SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); assertThat(liquibase.getLiquibaseSchema()).isEqualTo("public"); assertThat(liquibase.getLiquibaseTablespace()).isEqualTo("infra"); - assertThat(liquibase.getDatabaseChangeLogTable()) - .isEqualTo("LIQUI_LOG"); - assertThat(liquibase.getDatabaseChangeLogLockTable()) - .isEqualTo("LIQUI_LOCK"); - JdbcTemplate jdbcTemplate = new JdbcTemplate( - context.getBean(DataSource.class)); - assertThat(jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM public.LIQUI_LOG", Integer.class)) - .isEqualTo(1); - assertThat(jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM public.LIQUI_LOCK", Integer.class)) - .isEqualTo(1); + assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo("LIQUI_LOG"); + assertThat(liquibase.getDatabaseChangeLogLockTable()).isEqualTo("LIQUI_LOCK"); + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOG", Integer.class)) + .isEqualTo(1); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOCK", Integer.class)) + .isEqualTo(1); }); } @@ -200,8 +180,7 @@ public class LiquibaseAutoConfigurationTests { public void overrideDropFirst() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.drop-first:true") - .run(assertLiquibase( - (liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); + .run(assertLiquibase((liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); } @Test @@ -211,8 +190,7 @@ public class LiquibaseAutoConfigurationTests { .run(assertLiquibase((liquibase) -> { DataSource dataSource = liquibase.getDataSource(); assertThat(((HikariDataSource) dataSource).isClosed()).isTrue(); - assertThat(((HikariDataSource) dataSource).getJdbcUrl()) - .isEqualTo("jdbc:hsqldb:mem:liquibase"); + assertThat(((HikariDataSource) dataSource).getJdbcUrl()).isEqualTo("jdbc:hsqldb:mem:liquibase"); })); } @@ -220,23 +198,20 @@ public class LiquibaseAutoConfigurationTests { public void overrideUser() { String jdbcUrl = "jdbc:hsqldb:mem:normal"; this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:" + jdbcUrl, - "spring.datasource.username:not-sa", "spring.liquibase.user:sa") + .withPropertyValues("spring.datasource.url:" + jdbcUrl, "spring.datasource.username:not-sa", + "spring.liquibase.user:sa") .run(assertLiquibase((liquibase) -> { DataSource dataSource = liquibase.getDataSource(); assertThat(((HikariDataSource) dataSource).isClosed()).isTrue(); - assertThat(((HikariDataSource) dataSource).getJdbcUrl()) - .isEqualTo(jdbcUrl); - assertThat(((HikariDataSource) dataSource).getUsername()) - .isEqualTo("sa"); + assertThat(((HikariDataSource) dataSource).getJdbcUrl()).isEqualTo(jdbcUrl); + assertThat(((HikariDataSource) dataSource).getUsername()).isEqualTo("sa"); })); } @Test public void overrideTestRollbackOnUpdate() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.test-rollback-on-update:true") - .run((context) -> { + .withPropertyValues("spring.liquibase.test-rollback-on-update:true").run((context) -> { SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); assertThat(liquibase.isTestRollbackOnUpdate()).isTrue(); }); @@ -245,12 +220,9 @@ public class LiquibaseAutoConfigurationTests { @Test public void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.liquibase.change-log:classpath:/no-such-changelog.yaml") - .run((context) -> { + .withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml").run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); }); } @@ -268,18 +240,16 @@ public class LiquibaseAutoConfigurationTests { public void overrideLabels() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.labels:test, production") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabels()) - .isEqualTo("test, production"))); + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabels()).isEqualTo("test, production"))); } @Test @SuppressWarnings("unchecked") public void testOverrideParameters() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.parameters.foo:bar") - .run(assertLiquibase((liquibase) -> { - Map parameters = (Map) ReflectionTestUtils - .getField(liquibase, "parameters"); + .withPropertyValues("spring.liquibase.parameters.foo:bar").run(assertLiquibase((liquibase) -> { + Map parameters = (Map) ReflectionTestUtils.getField(liquibase, + "parameters"); assertThat(parameters.containsKey("foo")).isTrue(); assertThat(parameters.get("foo")).isEqualTo("bar"); })); @@ -289,12 +259,9 @@ public class LiquibaseAutoConfigurationTests { public void rollbackFile(@TempDir Path temp) throws IOException { File file = Files.createTempFile(temp, "rollback-file", "sql").toFile(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues( - "spring.liquibase.rollbackFile:" + file.getAbsolutePath()) - .run((context) -> { + .withPropertyValues("spring.liquibase.rollbackFile:" + file.getAbsolutePath()).run((context) -> { SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - File actualFile = (File) ReflectionTestUtils.getField(liquibase, - "rollbackFile"); + File actualFile = (File) ReflectionTestUtils.getField(liquibase, "rollbackFile"); assertThat(actualFile).isEqualTo(file).exists(); assertThat(contentOf(file)).contains("DROP TABLE PUBLIC.customer;"); }); @@ -302,26 +269,23 @@ public class LiquibaseAutoConfigurationTests { @Test public void liquibaseDataSource() { - this.contextRunner.withUserConfiguration(LiquibaseDataSourceConfiguration.class, - EmbeddedDataSourceConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.getDataSource()) - .isEqualTo(context.getBean("liquibaseDataSource")); + assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); }); } @Test public void liquibaseDataSourceWithoutDataSourceAutoConfiguration() { - this.contextRunner.withUserConfiguration(LiquibaseDataSourceConfiguration.class) - .run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.getDataSource()) - .isEqualTo(context.getBean("liquibaseDataSource")); - }); + this.contextRunner.withUserConfiguration(LiquibaseDataSourceConfiguration.class).run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); + }); } - private ContextConsumer assertLiquibase( - Consumer consumer) { + private ContextConsumer assertLiquibase(Consumer consumer) { return (context) -> { assertThat(context).hasSingleBean(SpringLiquibase.class); SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); @@ -335,15 +299,13 @@ public class LiquibaseAutoConfigurationTests { @Bean @Primary public DataSource normalDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa") - .build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa").build(); } @LiquibaseDataSource @Bean public DataSource liquibaseDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:liquibasetest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:liquibasetest").username("sa").build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java index 54f427f8c0f..381fbb2eb88 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java @@ -64,8 +64,7 @@ public class ConditionEvaluationReportLoggingListenerTests { this.initializer.initialize(context); context.register(Config.class); context.refresh(); - withDebugLogging(() -> this.initializer - .onApplicationEvent(new ContextRefreshedEvent(context))); + withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context))); assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT"); } @@ -74,10 +73,9 @@ public class ConditionEvaluationReportLoggingListenerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); - assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies( - (ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent( - new ApplicationFailedEvent(new SpringApplication(), new String[0], - context, ex)))); + assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) + .satisfies((ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT"); } @@ -86,13 +84,11 @@ public class ConditionEvaluationReportLoggingListenerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); - assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) - .satisfies((ex) -> this.initializer.onApplicationEvent( - new ApplicationFailedEvent(new SpringApplication(), new String[0], - context, ex))); - assertThat(capturedOutput).contains("Error starting" - + " ApplicationContext. To display the conditions report re-run" - + " your application with 'debug' enabled."); + assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies((ex) -> this.initializer + .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex))); + assertThat(capturedOutput) + .contains("Error starting" + " ApplicationContext. To display the conditions report re-run" + + " your application with 'debug' enabled."); } @Test @@ -100,13 +96,10 @@ public class ConditionEvaluationReportLoggingListenerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(Config.class); - ConditionEvaluationReport.get(context.getBeanFactory()) - .recordExclusions(Arrays.asList("com.foo.Bar")); + ConditionEvaluationReport.get(context.getBeanFactory()).recordExclusions(Arrays.asList("com.foo.Bar")); context.refresh(); - withDebugLogging(() -> this.initializer - .onApplicationEvent(new ContextRefreshedEvent(context))); - assertThat(capturedOutput) - .contains("not a servlet web application (OnWebApplicationCondition)"); + withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context))); + assertThat(capturedOutput).contains("not a servlet web application (OnWebApplicationCondition)"); } @Test @@ -142,22 +135,20 @@ public class ConditionEvaluationReportLoggingListenerTests { @Test public void listenerSupportsOnlyInfoAndDebug() { - assertThatIllegalArgumentException().isThrownBy( - () -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) .withMessageContaining("LogLevel must be INFO or DEBUG"); } @Test public void noErrorIfNotInitialized(CapturedOutput capturedOutput) { - this.initializer - .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), - new String[0], null, new RuntimeException("Planned"))); + this.initializer.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null, + new RuntimeException("Planned"))); assertThat(capturedOutput).contains("Unable to provide the conditions report"); } private void withDebugLogging(Runnable runnable) { - LoggerContext context = (LoggerContext) StaticLoggerBinder.getSingleton() - .getLoggerFactory(); + LoggerContext context = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); Logger logger = context.getLogger(ConditionEvaluationReportLoggingListener.class); Level currentLevel = logger.getLevel(); logger.setLevel(Level.DEBUG); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java index 781da249bfc..e8467c07664 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java @@ -50,9 +50,8 @@ import static org.mockito.Mockito.verify; */ public class MailSenderAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, - MailSenderValidatorAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(MailSenderAutoConfiguration.class, MailSenderValidatorAutoConfiguration.class)); private ClassLoader threadContextClassLoader; @@ -61,19 +60,16 @@ public class MailSenderAutoConfigurationTests { @BeforeEach public void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @AfterEach public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -84,29 +80,23 @@ public class MailSenderAutoConfigurationTests { @Test public void smtpHostSet() { String host = "192.168.1.234"; - this.contextRunner.withPropertyValues("spring.mail.host:" + host) - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getHost()).isEqualTo(host); - assertThat(mailSender.getPort()) - .isEqualTo(JavaMailSenderImpl.DEFAULT_PORT); - assertThat(mailSender.getProtocol()) - .isEqualTo(JavaMailSenderImpl.DEFAULT_PROTOCOL); - }); + this.contextRunner.withPropertyValues("spring.mail.host:" + host).run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getHost()).isEqualTo(host); + assertThat(mailSender.getPort()).isEqualTo(JavaMailSenderImpl.DEFAULT_PORT); + assertThat(mailSender.getProtocol()).isEqualTo(JavaMailSenderImpl.DEFAULT_PROTOCOL); + }); } @Test public void smtpHostWithSettings() { String host = "192.168.1.234"; - this.contextRunner.withPropertyValues("spring.mail.host:" + host, - "spring.mail.port:42", "spring.mail.username:john", - "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", + this.contextRunner.withPropertyValues("spring.mail.host:" + host, "spring.mail.port:42", + "spring.mail.username:john", "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", "spring.mail.protocol:smtps").run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); assertThat(mailSender.getHost()).isEqualTo(host); assertThat(mailSender.getPort()).isEqualTo(42); assertThat(mailSender.getUsername()).isEqualTo("john"); @@ -118,31 +108,28 @@ public class MailSenderAutoConfigurationTests { @Test public void smtpHostWithJavaMailProperties() { - this.contextRunner.withPropertyValues("spring.mail.host:localhost", - "spring.mail.properties.mail.smtp.auth:true").run((context) -> { + this.contextRunner + .withPropertyValues("spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true") + .run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getJavaMailProperties().get("mail.smtp.auth")) - .isEqualTo("true"); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getJavaMailProperties().get("mail.smtp.auth")).isEqualTo("true"); }); } @Test public void smtpHostNotSet() { - this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(MailSender.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(MailSender.class)); } @Test public void mailSenderBackOff() { this.contextRunner.withUserConfiguration(ManualMailConfiguration.class) - .withPropertyValues("spring.mail.host:smtp.acme.org", - "spring.mail.user:user", "spring.mail.password:secret") + .withPropertyValues("spring.mail.host:smtp.acme.org", "spring.mail.user:user", + "spring.mail.password:secret") .run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); assertThat(mailSender.getUsername()).isNull(); assertThat(mailSender.getPassword()).isNull(); }); @@ -161,25 +148,22 @@ public class MailSenderAutoConfigurationTests { } private void testJndiSessionLookup(Session session, String jndiName) { - this.contextRunner.withPropertyValues("spring.mail.jndi-name:" + jndiName) - .run((context) -> { - assertThat(context).hasSingleBean(Session.class); - Session sessionBean = context.getBean(Session.class); - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - assertThat(sessionBean).isEqualTo(session); - assertThat(context.getBean(JavaMailSenderImpl.class).getSession()) - .isEqualTo(sessionBean); - }); + this.contextRunner.withPropertyValues("spring.mail.jndi-name:" + jndiName).run((context) -> { + assertThat(context).hasSingleBean(Session.class); + Session sessionBean = context.getBean(Session.class); + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + assertThat(sessionBean).isEqualTo(session); + assertThat(context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); + }); } @Test public void jndiSessionIgnoredIfJndiNameNotSet() { configureJndiSession("foo"); - this.contextRunner.withPropertyValues("spring.mail.host:smtp.acme.org") - .run((context) -> { - assertThat(context).doesNotHaveBean(Session.class); - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - }); + this.contextRunner.withPropertyValues("spring.mail.host:smtp.acme.org").run((context) -> { + assertThat(context).doesNotHaveBean(Session.class); + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + }); } @Test @@ -193,36 +177,31 @@ public class MailSenderAutoConfigurationTests { @Test public void jndiSessionNotAvailableWithJndiName() { - this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining( - "Unable to find Session in JNDI location foo"); - }); + this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo").run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Unable to find Session in JNDI location foo"); + }); } @Test public void jndiSessionTakesPrecedenceOverProperties() { Session session = configureJndiSession("foo"); - this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", - "spring.mail.host:localhost").run((context) -> { + this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.host:localhost") + .run((context) -> { assertThat(context).hasSingleBean(Session.class); Session sessionBean = context.getBean(Session.class); assertThat(sessionBean).isEqualTo(session); - assertThat(context.getBean(JavaMailSenderImpl.class).getSession()) - .isEqualTo(sessionBean); + assertThat(context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); }); } @Test public void defaultEncodingWithProperties() { - this.contextRunner.withPropertyValues("spring.mail.host:localhost", - "spring.mail.default-encoding:UTF-16").run((context) -> { + this.contextRunner.withPropertyValues("spring.mail.host:localhost", "spring.mail.default-encoding:UTF-16") + .run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); }); } @@ -230,11 +209,10 @@ public class MailSenderAutoConfigurationTests { @Test public void defaultEncodingWithJndi() { configureJndiSession("foo"); - this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", - "spring.mail.default-encoding:UTF-16").run((context) -> { + this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.default-encoding:UTF-16") + .run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); }); } @@ -242,12 +220,9 @@ public class MailSenderAutoConfigurationTests { @Test public void connectionOnStartup() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) - .withPropertyValues("spring.mail.host:10.0.0.23", - "spring.mail.test-connection:true") - .run((context) -> { + .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true").run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); verify(mailSender, times(1)).testConnection(); }); } @@ -255,12 +230,10 @@ public class MailSenderAutoConfigurationTests { @Test public void connectionOnStartupNotCalled() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) - .withPropertyValues("spring.mail.host:10.0.0.23", - "spring.mail.test-connection:false") + .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:false") .run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context - .getBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); verify(mailSender, never()).testConnection(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java index de17802e347..b92ee39ea10 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java @@ -44,45 +44,40 @@ public class MongoAutoConfigurationTests { @Test public void clientExists() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test public void optionsAdded() { - this.contextRunner.withUserConfiguration(OptionsConfig.class) - .run((context) -> assertThat(context.getBean(MongoClient.class) - .getMongoClientOptions().getSocketTimeout()).isEqualTo(300)); + this.contextRunner.withUserConfiguration(OptionsConfig.class).run( + (context) -> assertThat(context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()) + .isEqualTo(300)); } @Test public void optionsAddedButNoHost() { - this.contextRunner.withUserConfiguration(OptionsConfig.class) - .run((context) -> assertThat(context.getBean(MongoClient.class) - .getMongoClientOptions().getSocketTimeout()).isEqualTo(300)); + this.contextRunner.withUserConfiguration(OptionsConfig.class).run( + (context) -> assertThat(context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()) + .isEqualTo(300)); } @Test public void optionsSslConfig() { - this.contextRunner.withUserConfiguration(SslOptionsConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(MongoClient.class); - MongoClient mongo = context.getBean(MongoClient.class); - MongoClientOptions options = mongo.getMongoClientOptions(); - assertThat(options.isSslEnabled()).isTrue(); - assertThat(options.getSocketFactory()) - .isSameAs(context.getBean("mySocketFactory")); - }); + this.contextRunner.withUserConfiguration(SslOptionsConfig.class).run((context) -> { + assertThat(context).hasSingleBean(MongoClient.class); + MongoClient mongo = context.getBean(MongoClient.class); + MongoClientOptions options = mongo.getMongoClientOptions(); + assertThat(options.isSslEnabled()).isTrue(); + assertThat(options.getSocketFactory()).isSameAs(context.getBean("mySocketFactory")); + }); } @Test public void doesNotCreateMongoClientWhenAlreadyDefined() { - this.contextRunner.withUserConfiguration(FallbackMongoClientConfig.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(MongoClient.class); - assertThat(context) - .hasSingleBean(com.mongodb.client.MongoClient.class); - }); + this.contextRunner.withUserConfiguration(FallbackMongoClientConfig.class).run((context) -> { + assertThat(context).doesNotHaveBean(MongoClient.class); + assertThat(context).hasSingleBean(com.mongodb.client.MongoClient.class); + }); } @Configuration(proxyBeanMethods = false) @@ -100,8 +95,7 @@ public class MongoAutoConfigurationTests { @Bean public MongoClientOptions mongoClientOptions(SocketFactory socketFactory) { - return MongoClientOptions.builder().sslEnabled(true) - .socketFactory(socketFactory).build(); + return MongoClientOptions.builder().sslEnabled(true).socketFactory(socketFactory).build(); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java index 6022ed9b9c3..a4124662fc2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java @@ -94,8 +94,7 @@ public class MongoClientFactoryTests { @Test public void uriCanBeCustomized() { MongoProperties properties = new MongoProperties(); - properties.setUri("mongodb://user:secret@mongo1.example.com:12345," - + "mongo2.example.com:23456/test"); + properties.setUri("mongodb://user:secret@mongo1.example.com:12345," + "mongo2.example.com:23456/test"); MongoClient client = createMongoClient(properties); List allAddresses = getAllAddresses(client); assertThat(allAddresses).hasSize(2); @@ -121,8 +120,7 @@ public class MongoClientFactoryTests { return createMongoClient(properties, null); } - private MongoClient createMongoClient(MongoProperties properties, - Environment environment) { + private MongoClient createMongoClient(MongoProperties properties, Environment environment) { return new MongoClientFactory(properties, environment).createMongoClient(null); } @@ -140,14 +138,13 @@ public class MongoClientFactoryTests { return client.getCredentialsList(); } - private void assertServerAddress(ServerAddress serverAddress, String expectedHost, - int expectedPort) { + private void assertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) { assertThat(serverAddress.getHost()).isEqualTo(expectedHost); assertThat(serverAddress.getPort()).isEqualTo(expectedPort); } - private void assertMongoCredential(MongoCredential credentials, - String expectedUsername, String expectedPassword, String expectedSource) { + private void assertMongoCredential(MongoCredential credentials, String expectedUsername, String expectedPassword, + String expectedSource) { assertThat(credentials.getUserName()).isEqualTo(expectedUsername); assertThat(credentials.getPassword()).isEqualTo(expectedPassword.toCharArray()); assertThat(credentials.getSource()).isEqualTo(expectedSource); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java index 5ea10c1940c..eaf529aa630 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java @@ -76,38 +76,27 @@ public class MongoPropertiesTests { builder.requiredReplicaSetName("testReplicaSetName"); MongoClientOptions options = builder.build(); MongoProperties properties = new MongoProperties(); - MongoClient client = new MongoClientFactory(properties, null) - .createMongoClient(options); + MongoClient client = new MongoClientFactory(properties, null).createMongoClient(options); MongoClientOptions wrapped = client.getMongoClientOptions(); assertThat(wrapped.isAlwaysUseMBeans()).isEqualTo(options.isAlwaysUseMBeans()); - assertThat(wrapped.getConnectionsPerHost()) - .isEqualTo(options.getConnectionsPerHost()); + assertThat(wrapped.getConnectionsPerHost()).isEqualTo(options.getConnectionsPerHost()); assertThat(wrapped.getConnectTimeout()).isEqualTo(options.getConnectTimeout()); - assertThat(wrapped.isCursorFinalizerEnabled()) - .isEqualTo(options.isCursorFinalizerEnabled()); + assertThat(wrapped.isCursorFinalizerEnabled()).isEqualTo(options.isCursorFinalizerEnabled()); assertThat(wrapped.getDescription()).isEqualTo(options.getDescription()); assertThat(wrapped.getMaxWaitTime()).isEqualTo(options.getMaxWaitTime()); assertThat(wrapped.getSocketTimeout()).isEqualTo(options.getSocketTimeout()); assertThat(wrapped.isSocketKeepAlive()).isEqualTo(options.isSocketKeepAlive()); assertThat(wrapped.getThreadsAllowedToBlockForConnectionMultiplier()) .isEqualTo(options.getThreadsAllowedToBlockForConnectionMultiplier()); - assertThat(wrapped.getMinConnectionsPerHost()) - .isEqualTo(options.getMinConnectionsPerHost()); - assertThat(wrapped.getMaxConnectionIdleTime()) - .isEqualTo(options.getMaxConnectionIdleTime()); - assertThat(wrapped.getMaxConnectionLifeTime()) - .isEqualTo(options.getMaxConnectionLifeTime()); - assertThat(wrapped.getHeartbeatFrequency()) - .isEqualTo(options.getHeartbeatFrequency()); - assertThat(wrapped.getMinHeartbeatFrequency()) - .isEqualTo(options.getMinHeartbeatFrequency()); - assertThat(wrapped.getHeartbeatConnectTimeout()) - .isEqualTo(options.getHeartbeatConnectTimeout()); - assertThat(wrapped.getHeartbeatSocketTimeout()) - .isEqualTo(options.getHeartbeatSocketTimeout()); + assertThat(wrapped.getMinConnectionsPerHost()).isEqualTo(options.getMinConnectionsPerHost()); + assertThat(wrapped.getMaxConnectionIdleTime()).isEqualTo(options.getMaxConnectionIdleTime()); + assertThat(wrapped.getMaxConnectionLifeTime()).isEqualTo(options.getMaxConnectionLifeTime()); + assertThat(wrapped.getHeartbeatFrequency()).isEqualTo(options.getHeartbeatFrequency()); + assertThat(wrapped.getMinHeartbeatFrequency()).isEqualTo(options.getMinHeartbeatFrequency()); + assertThat(wrapped.getHeartbeatConnectTimeout()).isEqualTo(options.getHeartbeatConnectTimeout()); + assertThat(wrapped.getHeartbeatSocketTimeout()).isEqualTo(options.getHeartbeatSocketTimeout()); assertThat(wrapped.getLocalThreshold()).isEqualTo(options.getLocalThreshold()); - assertThat(wrapped.getRequiredReplicaSetName()) - .isEqualTo(options.getRequiredReplicaSetName()); + assertThat(wrapped.getRequiredReplicaSetName()).isEqualTo(options.getRequiredReplicaSetName()); } @Test @@ -116,8 +105,7 @@ public class MongoPropertiesTests { properties.setHost("localhost"); properties.setPort(27017); properties.setUri("mongodb://mongo1.example.com:12345"); - MongoClient client = new MongoClientFactory(properties, null) - .createMongoClient(null); + MongoClient client = new MongoClientFactory(properties, null).createMongoClient(null); List allAddresses = getAllAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345); @@ -128,8 +116,7 @@ public class MongoPropertiesTests { MongoProperties properties = new MongoProperties(); properties.setHost("localhost"); properties.setPort(27017); - MongoClient client = new MongoClientFactory(properties, null) - .createMongoClient(null); + MongoClient client = new MongoClientFactory(properties, null).createMongoClient(null); List allAddresses = getAllAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "localhost", 27017); @@ -139,8 +126,7 @@ public class MongoPropertiesTests { public void onlyUriSetShouldUseThat() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://mongo1.example.com:12345"); - MongoClient client = new MongoClientFactory(properties, null) - .createMongoClient(null); + MongoClient client = new MongoClientFactory(properties, null).createMongoClient(null); List allAddresses = getAllAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345); @@ -149,8 +135,7 @@ public class MongoPropertiesTests { @Test public void noCustomAddressAndNoUriUsesDefaultUri() { MongoProperties properties = new MongoProperties(); - MongoClient client = new MongoClientFactory(properties, null) - .createMongoClient(null); + MongoClient client = new MongoClientFactory(properties, null).createMongoClient(null); List allAddresses = getAllAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "localhost", 27017); @@ -166,16 +151,14 @@ public class MongoPropertiesTests { @Test public void canBindAutoIndexCreation() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.data.mongodb.autoIndexCreation:true") - .applyTo(context); + TestPropertyValues.of("spring.data.mongodb.autoIndexCreation:true").applyTo(context); context.register(Config.class); context.refresh(); MongoProperties properties = context.getBean(MongoProperties.class); assertThat(properties.isAutoIndexCreation()).isTrue(); } - private void assertServerAddress(ServerAddress serverAddress, String expectedHost, - int expectedPort) { + private void assertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) { assertThat(serverAddress.getHost()).isEqualTo(expectedHost); assertThat(serverAddress.getPort()).isEqualTo(expectedPort); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java index 44ff13cf669..33e713cd2b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java @@ -50,27 +50,24 @@ import static org.mockito.Mockito.mock; public class MongoReactiveAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); @Test public void clientExists() { - this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test public void optionsAdded() { this.contextRunner.withPropertyValues("spring.data.mongodb.host:localhost") .withUserConfiguration(OptionsConfig.class) - .run((context) -> assertThat(getSettings(context).getSocketSettings() - .getReadTimeout(TimeUnit.SECONDS)).isEqualTo(300)); + .run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) + .isEqualTo(300)); } @Test public void optionsAddedButNoHost() { - this.contextRunner - .withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") + this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") .withUserConfiguration(OptionsConfig.class) .run((context) -> assertThat(getSettings(context).getReadPreference()) .isEqualTo(ReadPreference.nearest())); @@ -78,14 +75,12 @@ public class MongoReactiveAutoConfigurationTests { @Test public void optionsSslConfig() { - this.contextRunner - .withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") + this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") .withUserConfiguration(SslOptionsConfig.class).run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); MongoClientSettings settings = getSettings(context); assertThat(settings.getApplicationName()).isEqualTo("test-config"); - assertThat(settings.getStreamFactoryFactory()) - .isSameAs(context.getBean("myStreamFactoryFactory")); + assertThat(settings.getStreamFactoryFactory()).isSameAs(context.getBean("myStreamFactoryFactory")); }); } @@ -96,8 +91,7 @@ public class MongoReactiveAutoConfigurationTests { assertThat(context).hasSingleBean(MongoClient.class); StreamFactoryFactory factory = getSettings(context).getStreamFactoryFactory(); assertThat(factory).isInstanceOf(NettyStreamFactoryFactory.class); - EventLoopGroup eventLoopGroup = (EventLoopGroup) ReflectionTestUtils - .getField(factory, "eventLoopGroup"); + EventLoopGroup eventLoopGroup = (EventLoopGroup) ReflectionTestUtils.getField(factory, "eventLoopGroup"); assertThat(eventLoopGroup.isShutdown()).isFalse(); eventLoopGroupReference.set(eventLoopGroup); }); @@ -106,13 +100,11 @@ public class MongoReactiveAutoConfigurationTests { @Test public void customizerOverridesAutoConfig() { - this.contextRunner.withPropertyValues( - "spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") + this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") .withUserConfiguration(SimpleCustomizerConfig.class).run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); MongoClientSettings settings = getSettings(context); - assertThat(settings.getApplicationName()) - .isEqualTo("overridden-name"); + assertThat(settings.getApplicationName()).isEqualTo("overridden-name"); assertThat(settings.getStreamFactoryFactory()) .isEqualTo(SimpleCustomizerConfig.streamFactoryFactory); }); @@ -121,8 +113,7 @@ public class MongoReactiveAutoConfigurationTests { @SuppressWarnings("deprecation") private MongoClientSettings getSettings(ApplicationContext context) { MongoClient client = context.getBean(MongoClient.class); - return (MongoClientSettings) ReflectionTestUtils.getField(client.getSettings(), - "wrapped"); + return (MongoClientSettings) ReflectionTestUtils.getField(client.getSettings(), "wrapped"); } @Configuration(proxyBeanMethods = false) @@ -131,9 +122,7 @@ public class MongoReactiveAutoConfigurationTests { @Bean public MongoClientSettings mongoClientSettings() { return MongoClientSettings.builder().readPreference(ReadPreference.nearest()) - .applyToSocketSettings( - (socket) -> socket.readTimeout(300, TimeUnit.SECONDS)) - .build(); + .applyToSocketSettings((socket) -> socket.readTimeout(300, TimeUnit.SECONDS)).build(); } } @@ -142,8 +131,7 @@ public class MongoReactiveAutoConfigurationTests { static class SslOptionsConfig { @Bean - public MongoClientSettings mongoClientSettings( - StreamFactoryFactory streamFactoryFactory) { + public MongoClientSettings mongoClientSettings(StreamFactoryFactory streamFactoryFactory) { return MongoClientSettings.builder().applicationName("test-config") .streamFactoryFactory(streamFactoryFactory).build(); } @@ -151,8 +139,7 @@ public class MongoReactiveAutoConfigurationTests { @Bean public StreamFactoryFactory myStreamFactoryFactory() { StreamFactoryFactory streamFactoryFactory = mock(StreamFactoryFactory.class); - given(streamFactoryFactory.create(any(), any())) - .willReturn(mock(StreamFactory.class)); + given(streamFactoryFactory.create(any(), any())).willReturn(mock(StreamFactory.class)); return streamFactoryFactory; } @@ -166,8 +153,7 @@ public class MongoReactiveAutoConfigurationTests { @Bean public MongoClientSettingsBuilderCustomizer customizer() { - return (clientSettingsBuilder) -> clientSettingsBuilder - .applicationName("overridden-name") + return (clientSettingsBuilder) -> clientSettingsBuilder.applicationName("overridden-name") .streamFactoryFactory(streamFactoryFactory); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java index fd3e6f20e3d..ea819b63cca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java @@ -98,8 +98,7 @@ public class ReactiveMongoClientFactoryTests { @Test public void uriCanBeCustomized() { MongoProperties properties = new MongoProperties(); - properties.setUri("mongodb://user:secret@mongo1.example.com:12345," - + "mongo2.example.com:23456/test"); + properties.setUri("mongodb://user:secret@mongo1.example.com:12345," + "mongo2.example.com:23456/test"); MongoClient client = createMongoClient(properties); List allAddresses = extractServerAddresses(client); assertThat(allAddresses).hasSize(2); @@ -123,9 +122,8 @@ public class ReactiveMongoClientFactoryTests { properties.setUri("mongodb://127.0.0.1:1234/mydb"); properties.setUsername("user"); properties.setPassword("secret".toCharArray()); - assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)) - .withMessageContaining("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)).withMessageContaining( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); } @Test @@ -134,9 +132,8 @@ public class ReactiveMongoClientFactoryTests { properties.setUri("mongodb://127.0.0.1:1234/mydb"); properties.setHost("localhost"); properties.setPort(4567); - assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)) - .withMessageContaining("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)).withMessageContaining( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); } @Test @@ -153,8 +150,7 @@ public class ReactiveMongoClientFactoryTests { @Test public void customizerIsInvoked() { MongoProperties properties = new MongoProperties(); - MongoClientSettingsBuilderCustomizer customizer = mock( - MongoClientSettingsBuilderCustomizer.class); + MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); createMongoClient(properties, this.environment, customizer); verify(customizer).customize(any(MongoClientSettings.Builder.class)); } @@ -163,8 +159,7 @@ public class ReactiveMongoClientFactoryTests { public void customizerIsInvokedWhenHostIsSet() { MongoProperties properties = new MongoProperties(); properties.setHost("localhost"); - MongoClientSettingsBuilderCustomizer customizer = mock( - MongoClientSettingsBuilderCustomizer.class); + MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); createMongoClient(properties, this.environment, customizer); verify(customizer).customize(any(MongoClientSettings.Builder.class)); } @@ -173,8 +168,7 @@ public class ReactiveMongoClientFactoryTests { public void customizerIsInvokedForEmbeddedMongo() { MongoProperties properties = new MongoProperties(); this.environment.setProperty("local.mongo.port", "27017"); - MongoClientSettingsBuilderCustomizer customizer = mock( - MongoClientSettingsBuilderCustomizer.class); + MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); createMongoClient(properties, this.environment, customizer); verify(customizer).customize(any(MongoClientSettings.Builder.class)); } @@ -183,11 +177,10 @@ public class ReactiveMongoClientFactoryTests { return createMongoClient(properties, this.environment); } - private MongoClient createMongoClient(MongoProperties properties, - Environment environment, + private MongoClient createMongoClient(MongoProperties properties, Environment environment, MongoClientSettingsBuilderCustomizer... customizers) { - return new ReactiveMongoClientFactory(properties, environment, - Arrays.asList(customizers)).createMongoClient(null); + return new ReactiveMongoClientFactory(properties, environment, Arrays.asList(customizers)) + .createMongoClient(null); } private List extractServerAddresses(MongoClient client) { @@ -202,18 +195,16 @@ public class ReactiveMongoClientFactoryTests { @SuppressWarnings("deprecation") private MongoClientSettings getSettings(MongoClient client) { - return (MongoClientSettings) ReflectionTestUtils.getField(client.getSettings(), - "wrapped"); + return (MongoClientSettings) ReflectionTestUtils.getField(client.getSettings(), "wrapped"); } - private void assertServerAddress(ServerAddress serverAddress, String expectedHost, - int expectedPort) { + private void assertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) { assertThat(serverAddress.getHost()).isEqualTo(expectedHost); assertThat(serverAddress.getPort()).isEqualTo(expectedPort); } - private void assertMongoCredential(MongoCredential credentials, - String expectedUsername, String expectedPassword, String expectedSource) { + private void assertMongoCredential(MongoCredential credentials, String expectedUsername, String expectedPassword, + String expectedSource) { assertThat(credentials.getUserName()).isEqualTo(expectedUsername); assertThat(credentials.getPassword()).isEqualTo(expectedPassword.toCharArray()); assertThat(credentials.getSource()).isEqualTo(expectedSource); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java index 26bda8ee3d5..e1395887e32 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java @@ -86,13 +86,13 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void customFeatures() { - EnumSet features = EnumSet.of(Feature.TEXT_SEARCH, Feature.SYNC_DELAY, - Feature.ONLY_WITH_SSL, Feature.NO_HTTP_INTERFACE_ARG); + EnumSet features = EnumSet.of(Feature.TEXT_SEARCH, Feature.SYNC_DELAY, Feature.ONLY_WITH_SSL, + Feature.NO_HTTP_INTERFACE_ARG); if (isWindows()) { features.add(Feature.ONLY_WINDOWS_2008_SERVER); } - load("spring.mongodb.embedded.features=" + String.join(", ", - features.stream().map(Feature::name).collect(Collectors.toList()))); + load("spring.mongodb.embedded.features=" + + String.join(", ", features.stream().map(Feature::name).collect(Collectors.toList()))); assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()) .containsExactlyElementsOf(features); } @@ -102,8 +102,7 @@ public class EmbeddedMongoAutoConfigurationTests { load(); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); MongoClient client = this.context.getBean(MongoClient.class); - Integer mongoPort = Integer - .valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); + Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); assertThat(getPort(client)).isEqualTo(mongoPort); } @@ -112,8 +111,7 @@ public class EmbeddedMongoAutoConfigurationTests { load("spring.data.mongodb.port=0"); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); MongoClient client = this.context.getBean(MongoClient.class); - Integer mongoPort = Integer - .valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); + Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); assertThat(getPort(client)).isEqualTo(mongoPort); } @@ -121,8 +119,7 @@ public class EmbeddedMongoAutoConfigurationTests { public void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() { load(MongoClientConfiguration.class); MongoClient client = this.context.getBean(MongoClient.class); - Integer mongoPort = Integer - .valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); + Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); assertThat(getPort(client)).isEqualTo(mongoPort); } @@ -132,11 +129,9 @@ public class EmbeddedMongoAutoConfigurationTests { parent.refresh(); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); - this.context.register(EmbeddedMongoAutoConfiguration.class, - MongoClientConfiguration.class); + this.context.register(EmbeddedMongoAutoConfiguration.class, MongoClientConfiguration.class); this.context.refresh(); - assertThat(parent.getEnvironment().getProperty("local.mongo.port")) - .isNotNull(); + assertThat(parent.getEnvironment().getProperty("local.mongo.port")).isNotNull(); } } @@ -153,8 +148,7 @@ public class EmbeddedMongoAutoConfigurationTests { public void mongoWritesToCustomDatabaseDir(@TempDir Path temp) throws IOException { File customDatabaseDir = new File(temp.toFile(), "custom-database-dir"); FileSystemUtils.deleteRecursively(customDatabaseDir); - load("spring.mongodb.embedded.storage.databaseDir=" - + customDatabaseDir.getPath()); + load("spring.mongodb.embedded.storage.databaseDir=" + customDatabaseDir.getPath()); assertThat(customDatabaseDir).isDirectory(); assertThat(customDatabaseDir.listFiles()).isNotEmpty(); } @@ -162,51 +156,44 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void customOpLogSizeIsAppliedToConfiguration() { load("spring.mongodb.embedded.storage.oplogSize=1024KB"); - assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()) - .isEqualTo(1); + assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()).isEqualTo(1); } @Test public void customOpLogSizeUsesMegabytesPerDefault() { load("spring.mongodb.embedded.storage.oplogSize=10"); - assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()) - .isEqualTo(10); + assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()).isEqualTo(10); } @Test public void customReplicaSetNameIsAppliedToConfiguration() { load("spring.mongodb.embedded.storage.replSetName=testing"); - assertThat( - this.context.getBean(IMongodConfig.class).replication().getReplSetName()) - .isEqualTo("testing"); + assertThat(this.context.getBean(IMongodConfig.class).replication().getReplSetName()).isEqualTo("testing"); } @Test public void customizeDownloadConfiguration() { load(DownloadConfigBuilderCustomizerConfiguration.class); IRuntimeConfig runtimeConfig = this.context.getBean(IRuntimeConfig.class); - IDownloadConfig downloadConfig = (IDownloadConfig) new DirectFieldAccessor( - runtimeConfig.getArtifactStore()).getPropertyValue("downloadConfig"); + IDownloadConfig downloadConfig = (IDownloadConfig) new DirectFieldAccessor(runtimeConfig.getArtifactStore()) + .getPropertyValue("downloadConfig"); assertThat(downloadConfig.getUserAgent()).isEqualTo("Test User Agent"); } @Test public void shutdownHookIsNotRegistered() { load(); - assertThat(this.context.getBean(MongodExecutable.class).isRegisteredJobKiller()) - .isFalse(); + assertThat(this.context.getBean(MongodExecutable.class).isRegisteredJobKiller()).isFalse(); } - private void assertVersionConfiguration(String configuredVersion, - String expectedVersion) { + private void assertVersionConfiguration(String configuredVersion, String expectedVersion) { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.data.mongodb.port=0").applyTo(this.context); if (configuredVersion != null) { - TestPropertyValues.of("spring.mongodb.embedded.version=" + configuredVersion) - .applyTo(this.context); + TestPropertyValues.of("spring.mongodb.embedded.version=" + configuredVersion).applyTo(this.context); } - this.context.register(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class); + this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + EmbeddedMongoAutoConfiguration.class); this.context.refresh(); MongoTemplate mongo = this.context.getBean(MongoTemplate.class); Document buildInfo = mongo.executeCommand("{ buildInfo: 1 }"); @@ -256,8 +243,7 @@ public class EmbeddedMongoAutoConfigurationTests { @Bean public DownloadConfigBuilderCustomizer testDownloadConfigBuilderCustomizer() { - return (downloadConfigBuilder) -> downloadConfigBuilder - .userAgent("Test User Agent"); + return (downloadConfigBuilder) -> downloadConfigBuilder.userAgent("Test User Agent"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java index 431387ad588..5ed54e1dbb7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java @@ -48,8 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.main.web-application-type=reactive") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") public class MustacheAutoConfigurationReactiveIntegrationTests { @Autowired @@ -57,22 +56,21 @@ public class MustacheAutoConfigurationReactiveIntegrationTests { @Test public void testHomePage() { - String result = this.client.get().uri("/").exchange().expectStatus().isOk() - .expectBody(String.class).returnResult().getResponseBody(); + String result = this.client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) + .returnResult().getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @Test public void testPartialPage() { - String result = this.client.get().uri("/partial").exchange().expectStatus().isOk() - .expectBody(String.class).returnResult().getResponseBody(); + String result = this.client.get().uri("/partial").exchange().expectStatus().isOk().expectBody(String.class) + .returnResult().getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @Configuration(proxyBeanMethods = false) - @Import({ ReactiveWebServerFactoryAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ ReactiveWebServerFactoryAutoConfiguration.class, WebFluxAutoConfiguration.class, + HttpHandlerAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @Controller public static class Application { @@ -94,9 +92,8 @@ public class MustacheAutoConfigurationReactiveIntegrationTests { @Bean public MustacheViewResolver viewResolver() { - Mustache.Compiler compiler = Mustache.compiler().withLoader( - new MustacheResourceTemplateLoader("classpath:/mustache-templates/", - ".html")); + Mustache.Compiler compiler = Mustache.compiler() + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); MustacheViewResolver resolver = new MustacheViewResolver(compiler); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java index 52d736dd2d6..3bfe6db6804 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java @@ -81,15 +81,13 @@ public class MustacheAutoConfigurationServletIntegrationTests { @Test public void testHomePage() { - String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, - String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, String.class); assertThat(body.contains("Hello World")).isTrue(); } @Test public void testPartialPage() { - String body = new TestRestTemplate() - .getForObject("http://localhost:" + this.port + "/partial", String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port + "/partial", String.class); assertThat(body.contains("Hello World")).isTrue(); } @@ -116,9 +114,8 @@ public class MustacheAutoConfigurationServletIntegrationTests { @Bean public MustacheViewResolver viewResolver() { - Mustache.Compiler compiler = Mustache.compiler().withLoader( - new MustacheResourceTemplateLoader("classpath:/mustache-templates/", - ".html")); + Mustache.Compiler compiler = Mustache.compiler() + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); MustacheViewResolver resolver = new MustacheViewResolver(compiler); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); @@ -134,8 +131,7 @@ public class MustacheAutoConfigurationServletIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, + @Import({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java index d3b8b49af6b..323ad205443 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java @@ -44,56 +44,45 @@ public class MustacheAutoConfigurationTests { public void registerBeansForServletApp() { loadWithServlet(null); assertThat(this.webContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); - assertThat(this.webContext.getBeansOfType(MustacheResourceTemplateLoader.class)) - .hasSize(1); + assertThat(this.webContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); assertThat(this.webContext.getBeansOfType(MustacheViewResolver.class)).hasSize(1); } @Test public void registerCompilerForServletApp() { loadWithServlet(CustomCompilerConfiguration.class); - assertThat(this.webContext.getBeansOfType(MustacheResourceTemplateLoader.class)) - .hasSize(1); + assertThat(this.webContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); assertThat(this.webContext.getBeansOfType(MustacheViewResolver.class)).hasSize(1); assertThat(this.webContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); - assertThat(this.webContext.getBean(Mustache.Compiler.class).standardsMode) - .isTrue(); + assertThat(this.webContext.getBean(Mustache.Compiler.class).standardsMode).isTrue(); } @Test public void registerBeansForReactiveApp() { loadWithReactive(null); - assertThat(this.reactiveWebContext.getBeansOfType(Mustache.Compiler.class)) - .hasSize(1); + assertThat(this.reactiveWebContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); + assertThat(this.reactiveWebContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); + assertThat(this.reactiveWebContext.getBeansOfType(MustacheViewResolver.class)).isEmpty(); assertThat(this.reactiveWebContext - .getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); - assertThat(this.reactiveWebContext.getBeansOfType(MustacheViewResolver.class)) - .isEmpty(); - assertThat(this.reactiveWebContext.getBeansOfType( - org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class)) + .getBeansOfType(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class)) .hasSize(1); } @Test public void registerCompilerForReactiveApp() { loadWithReactive(CustomCompilerConfiguration.class); - assertThat(this.reactiveWebContext.getBeansOfType(Mustache.Compiler.class)) - .hasSize(1); + assertThat(this.reactiveWebContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); + assertThat(this.reactiveWebContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); + assertThat(this.reactiveWebContext.getBeansOfType(MustacheViewResolver.class)).isEmpty(); assertThat(this.reactiveWebContext - .getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); - assertThat(this.reactiveWebContext.getBeansOfType(MustacheViewResolver.class)) - .isEmpty(); - assertThat(this.reactiveWebContext.getBeansOfType( - org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class)) + .getBeansOfType(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class)) .hasSize(1); - assertThat(this.reactiveWebContext.getBean(Mustache.Compiler.class).standardsMode) - .isTrue(); + assertThat(this.reactiveWebContext.getBean(Mustache.Compiler.class).standardsMode).isTrue(); } private void loadWithServlet(Class config) { this.webContext = new AnnotationConfigServletWebApplicationContext(); - TestPropertyValues.of("spring.mustache.prefix=classpath:/mustache-templates/") - .applyTo(this.webContext); + TestPropertyValues.of("spring.mustache.prefix=classpath:/mustache-templates/").applyTo(this.webContext); if (config != null) { this.webContext.register(config); } @@ -103,8 +92,7 @@ public class MustacheAutoConfigurationTests { private void loadWithReactive(Class config) { this.reactiveWebContext = new AnnotationConfigReactiveWebApplicationContext(); - TestPropertyValues.of("spring.mustache.prefix=classpath:/mustache-templates/") - .applyTo(this.reactiveWebContext); + TestPropertyValues.of("spring.mustache.prefix=classpath:/mustache-templates/").applyTo(this.reactiveWebContext); if (config != null) { this.reactiveWebContext.register(config); } @@ -122,10 +110,8 @@ public class MustacheAutoConfigurationTests { protected static class CustomCompilerConfiguration { @Bean - public Mustache.Compiler compiler( - Mustache.TemplateLoader mustacheTemplateLoader) { - return Mustache.compiler().standardsMode(true) - .withLoader(mustacheTemplateLoader); + public Mustache.Compiler compiler(Mustache.TemplateLoader mustacheTemplateLoader) { + return Mustache.compiler().standardsMode(true).withLoader(mustacheTemplateLoader); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java index f8d5afb126e..be3aeafc4d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java @@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.NONE, - properties = { "env.FOO=There", "foo=World" }) +@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = { "env.FOO=There", "foo=World" }) public class MustacheStandaloneIntegrationTests { @Autowired @@ -46,32 +45,28 @@ public class MustacheStandaloneIntegrationTests { @Test public void directCompilation() { - assertThat(this.compiler.compile("Hello: {{world}}") - .execute(Collections.singletonMap("world", "World"))) - .isEqualTo("Hello: World"); + assertThat(this.compiler.compile("Hello: {{world}}").execute(Collections.singletonMap("world", "World"))) + .isEqualTo("Hello: World"); } @Test public void environmentCollectorCompoundKey() { - assertThat(this.compiler.compile("Hello: {{env.foo}}").execute(new Object())) - .isEqualTo("Hello: There"); + assertThat(this.compiler.compile("Hello: {{env.foo}}").execute(new Object())).isEqualTo("Hello: There"); } @Test public void environmentCollectorCompoundKeyStandard() { - assertThat(this.compiler.standardsMode(true).compile("Hello: {{env.foo}}") - .execute(new Object())).isEqualTo("Hello: There"); + assertThat(this.compiler.standardsMode(true).compile("Hello: {{env.foo}}").execute(new Object())) + .isEqualTo("Hello: There"); } @Test public void environmentCollectorSimpleKey() { - assertThat(this.compiler.compile("Hello: {{foo}}").execute(new Object())) - .isEqualTo("Hello: World"); + assertThat(this.compiler.compile("Hello: {{foo}}").execute(new Object())).isEqualTo("Hello: World"); } @Configuration(proxyBeanMethods = false) - @Import({ MustacheAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ MustacheAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected static class Application { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java index b93ec599faa..31dc8198d64 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java @@ -69,9 +69,8 @@ public abstract class AbstractJpaAutoConfigurationTests { this.autoConfiguredClass = autoConfiguredClass; this.contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestConfiguration.class).withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, autoConfiguredClass)); + .withUserConfiguration(TestConfiguration.class).withConfiguration(AutoConfigurations.of( + DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, autoConfiguredClass)); } protected ApplicationContextRunner contextRunner() { @@ -80,17 +79,14 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void notConfiguredIfDataSourceIsNotAvailable() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) + new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) .run(assertJpaIsNotAutoConfigured()); } @Test public void notConfiguredIfNoSingleDataSourceCandidateIsAvailable() { - new ApplicationContextRunner() - .withUserConfiguration(TestTwoDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) - .run(assertJpaIsNotAutoConfigured()); + new ApplicationContextRunner().withUserConfiguration(TestTwoDataSourcesConfiguration.class) + .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)).run(assertJpaIsNotAutoConfigured()); } protected ContextConsumer assertJpaIsNotAutoConfigured() { @@ -113,74 +109,57 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void configuredWithSingleCandidateDataSource() { - this.contextRunner - .withUserConfiguration(TestTwoDataSourcesAndPrimaryConfiguration.class) - .run((context) -> { - assertThat(context).getBeans(DataSource.class).hasSize(2); - assertThat(context).hasSingleBean(JpaTransactionManager.class); - assertThat(context).hasSingleBean(EntityManagerFactory.class); - }); + this.contextRunner.withUserConfiguration(TestTwoDataSourcesAndPrimaryConfiguration.class).run((context) -> { + assertThat(context).getBeans(DataSource.class).hasSize(2); + assertThat(context).hasSingleBean(JpaTransactionManager.class); + assertThat(context).hasSingleBean(EntityManagerFactory.class); + }); } @Test public void jtaTransactionManagerTakesPrecedence() { - this.contextRunner - .withConfiguration(AutoConfigurations - .of(DataSourceTransactionManagerAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class)) .run((context) -> { assertThat(context).hasSingleBean(DataSource.class); assertThat(context).hasSingleBean(JpaTransactionManager.class); - assertThat(context).getBean("transactionManager") - .isInstanceOf(JpaTransactionManager.class); + assertThat(context).getBean("transactionManager").isInstanceOf(JpaTransactionManager.class); }); } @Test public void openEntityManagerInViewInterceptorIsCreated() { - new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") + new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context) - .hasSingleBean(OpenEntityManagerInViewInterceptor.class)); + .run((context) -> assertThat(context).hasSingleBean(OpenEntityManagerInViewInterceptor.class)); } @Test public void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterPresent() { - new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") + new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestFilterConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context) - .doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test public void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterRegistrationPresent() { - new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") + new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestFilterRegistrationConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context) - .doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test public void openEntityManagerInViewInterceptorAutoConfigurationBacksOffWhenManuallyRegistered() { - new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") + new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestInterceptorManualConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context) - .getBean(OpenEntityManagerInViewInterceptor.class) + .run((context) -> assertThat(context).getBean(OpenEntityManagerInViewInterceptor.class) .isExactlyInstanceOf( TestInterceptorManualConfiguration.ManualOpenEntityManagerInViewInterceptor.class)); } @@ -188,22 +167,17 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void openEntityManagerInViewInterceptorIsNotRegisteredWhenExplicitlyOff() { new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.jpa.open-in-view=false") + .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false") .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of( - DataSourceAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context) - .doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test public void customJpaProperties() { - this.contextRunner - .withPropertyValues("spring.jpa.properties.a:b", - "spring.jpa.properties.a.b:c", "spring.jpa.properties.c:d") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", + "spring.jpa.properties.c:d").run((context) -> { LocalContainerEntityManagerFactoryBean bean = context .getBean(LocalContainerEntityManagerFactoryBean.class); Map map = bean.getJpaPropertyMap(); @@ -215,9 +189,7 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() { - this.contextRunner - .withUserConfiguration( - TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) + this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) .run((context) -> { LocalContainerEntityManagerFactoryBean factoryBean = context .getBean(LocalContainerEntityManagerFactoryBean.class); @@ -228,12 +200,9 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void usesManuallyDefinedEntityManagerFactoryIfAvailable() { - this.contextRunner - .withUserConfiguration( - TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) + this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) .run((context) -> { - EntityManagerFactory factoryBean = context - .getBean(EntityManagerFactory.class); + EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); Map map = factoryBean.getProperties(); assertThat(map.get("configured")).isEqualTo("manually"); }); @@ -241,25 +210,19 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void usesManuallyDefinedTransactionManagerBeanIfAvailable() { - this.contextRunner - .withUserConfiguration(TestConfigurationWithTransactionManager.class) - .run((context) -> { - PlatformTransactionManager txManager = context - .getBean(PlatformTransactionManager.class); - assertThat(txManager).isInstanceOf(CustomJpaTransactionManager.class); - }); + this.contextRunner.withUserConfiguration(TestConfigurationWithTransactionManager.class).run((context) -> { + PlatformTransactionManager txManager = context.getBean(PlatformTransactionManager.class); + assertThat(txManager).isInstanceOf(CustomJpaTransactionManager.class); + }); } @Test public void customPersistenceUnitManager() { - this.contextRunner - .withUserConfiguration( - TestConfigurationWithCustomPersistenceUnitManager.class) + this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitManager.class) .run((context) -> { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context .getBean(LocalContainerEntityManagerFactoryBean.class); - assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue( - "persistenceUnitManager", + assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue("persistenceUnitManager", context.getBean(PersistenceUnitManager.class)); }); } @@ -342,20 +305,18 @@ public abstract class AbstractJpaAutoConfigurationTests { return new ManualOpenEntityManagerInViewInterceptor(); } - protected static class ManualOpenEntityManagerInViewInterceptor - extends OpenEntityManagerInViewInterceptor { + protected static class ManualOpenEntityManagerInViewInterceptor extends OpenEntityManagerInViewInterceptor { } } @Configuration(proxyBeanMethods = false) - protected static class TestConfigurationWithLocalContainerEntityManagerFactoryBean - extends TestConfiguration { + protected static class TestConfigurationWithLocalContainerEntityManagerFactoryBean extends TestConfiguration { @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory( - DataSource dataSource, JpaVendorAdapter adapter) { + public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, + JpaVendorAdapter adapter) { LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setJpaVendorAdapter(adapter); factoryBean.setDataSource(dataSource); @@ -370,12 +331,10 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - protected static class TestConfigurationWithEntityManagerFactory - extends TestConfiguration { + protected static class TestConfigurationWithEntityManagerFactory extends TestConfiguration { @Bean - public EntityManagerFactory entityManagerFactory(DataSource dataSource, - JpaVendorAdapter adapter) { + public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter adapter) { LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setJpaVendorAdapter(adapter); factoryBean.setDataSource(dataSource); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java index 730788f06d9..2148c05ae9d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java @@ -57,22 +57,17 @@ public class CustomHibernateJpaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class)); + .withUserConfiguration(TestConfiguration.class).withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)); @Test public void namingStrategyDelegatorTakesPrecedence() { - this.contextRunner.withPropertyValues( - "spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" - + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" + + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator").run((context) -> { JpaProperties jpaProperties = context.getBean(JpaProperties.class); - HibernateProperties hibernateProperties = context - .getBean(HibernateProperties.class); + HibernateProperties hibernateProperties = context.getBean(HibernateProperties.class); Map properties = hibernateProperties - .determineHibernateProperties(jpaProperties.getProperties(), - new HibernateSettings()); + .determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); assertThat(properties.get("hibernate.ejb.naming_strategy")).isNull(); }); } @@ -80,43 +75,31 @@ public class CustomHibernateJpaAutoConfigurationTests { @Test public void namingStrategyBeansAreUsed() { this.contextRunner.withUserConfiguration(NamingStrategyConfiguration.class) - .withPropertyValues( - "spring.datasource.url:jdbc:h2:mem:naming-strategy-beans") - .run((context) -> { - HibernateJpaConfiguration jpaConfiguration = context - .getBean(HibernateJpaConfiguration.class); - Map hibernateProperties = jpaConfiguration - .getVendorProperties(); - assertThat(hibernateProperties - .get("hibernate.implicit_naming_strategy")).isEqualTo( - NamingStrategyConfiguration.implicitNamingStrategy); - assertThat(hibernateProperties - .get("hibernate.physical_naming_strategy")).isEqualTo( - NamingStrategyConfiguration.physicalNamingStrategy); + .withPropertyValues("spring.datasource.url:jdbc:h2:mem:naming-strategy-beans").run((context) -> { + HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); + Map hibernateProperties = jpaConfiguration.getVendorProperties(); + assertThat(hibernateProperties.get("hibernate.implicit_naming_strategy")) + .isEqualTo(NamingStrategyConfiguration.implicitNamingStrategy); + assertThat(hibernateProperties.get("hibernate.physical_naming_strategy")) + .isEqualTo(NamingStrategyConfiguration.physicalNamingStrategy); }); } @Test public void hibernatePropertiesCustomizersAreAppliedInOrder() { - this.contextRunner - .withUserConfiguration(HibernatePropertiesCustomizerConfiguration.class) - .run((context) -> { - HibernateJpaConfiguration jpaConfiguration = context - .getBean(HibernateJpaConfiguration.class); - Map hibernateProperties = jpaConfiguration - .getVendorProperties(); - assertThat(hibernateProperties.get("test.counter")).isEqualTo(2); - }); + this.contextRunner.withUserConfiguration(HibernatePropertiesCustomizerConfiguration.class).run((context) -> { + HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); + Map hibernateProperties = jpaConfiguration.getVendorProperties(); + assertThat(hibernateProperties.get("test.counter")).isEqualTo(2); + }); } @Test public void defaultDatabaseIsSet() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:h2:mem:testdb", "spring.datasource.initialization-mode:never").run((context) -> { - HibernateJpaVendorAdapter bean = context - .getBean(HibernateJpaVendorAdapter.class); - Database database = (Database) ReflectionTestUtils.getField(bean, - "database"); + HibernateJpaVendorAdapter bean = context.getBean(HibernateJpaVendorAdapter.class); + Database database = (Database) ReflectionTestUtils.getField(bean, "database"); assertThat(database).isEqualTo(Database.DEFAULT); }); } @@ -135,8 +118,7 @@ public class CustomHibernateJpaAutoConfigurationTests { DataSource dataSource = mock(DataSource.class); try { given(dataSource.getConnection()).willReturn(mock(Connection.class)); - given(dataSource.getConnection().getMetaData()) - .willReturn(mock(DatabaseMetaData.class)); + given(dataSource.getConnection().getMetaData()).willReturn(mock(DatabaseMetaData.class)); } catch (SQLException ex) { // Do nothing diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java index 3eb09ab78c0..bb35f8ef77d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java @@ -41,8 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class Hibernate2ndLevelCacheIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, - DataSourceAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)) .withPropertyValues("spring.datasource.initialization-mode=never") .withUserConfiguration(TestConfiguration.class); @@ -51,12 +50,12 @@ public class Hibernate2ndLevelCacheIntegrationTests { public void hibernate2ndLevelCacheWithJCacheAndEhCache3() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; - this.contextRunner.withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation, - "spring.jpa.properties.hibernate.cache.region.factory_class=jcache", - "spring.jpa.properties.hibernate.cache.provider=" + cachingProviderFqn, - "spring.jpa.properties.hibernate.javax.cache.uri=" + configLocation) + this.contextRunner + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation, + "spring.jpa.properties.hibernate.cache.region.factory_class=jcache", + "spring.jpa.properties.hibernate.cache.provider=" + cachingProviderFqn, + "spring.jpa.properties.hibernate.javax.cache.uri=" + configLocation) .run((context) -> assertThat(context).hasNotFailed()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java index e502a42a3a6..3fe317e3e75 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java @@ -40,8 +40,8 @@ import static org.mockito.Mockito.mock; public class HibernateDefaultDdlAutoProviderTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)) .withPropertyValues("spring.datasource.initialization-mode:never"); @Test @@ -49,9 +49,7 @@ public class HibernateDefaultDdlAutoProviderTests { this.contextRunner.run((context) -> { HibernateDefaultDdlAutoProvider ddlAutoProvider = new HibernateDefaultDdlAutoProvider( Collections.emptyList()); - assertThat( - ddlAutoProvider.getDefaultDdlAuto(context.getBean(DataSource.class))) - .isEqualTo("create-drop"); + assertThat(ddlAutoProvider.getDefaultDdlAuto(context.getBean(DataSource.class))).isEqualTo("create-drop"); }); } @@ -60,8 +58,7 @@ public class HibernateDefaultDdlAutoProviderTests { this.contextRunner.run((context) -> { DataSource dataSource = context.getBean(DataSource.class); SchemaManagementProvider provider = mock(SchemaManagementProvider.class); - given(provider.getSchemaManagement(dataSource)) - .willReturn(SchemaManagement.MANAGED); + given(provider.getSchemaManagement(dataSource)).willReturn(SchemaManagement.MANAGED); HibernateDefaultDdlAutoProvider ddlAutoProvider = new HibernateDefaultDdlAutoProvider( Collections.singletonList(provider)); assertThat(ddlAutoProvider.getDefaultDdlAuto(dataSource)).isEqualTo("none"); @@ -73,12 +70,10 @@ public class HibernateDefaultDdlAutoProviderTests { this.contextRunner.run((context) -> { DataSource dataSource = context.getBean(DataSource.class); SchemaManagementProvider provider = mock(SchemaManagementProvider.class); - given(provider.getSchemaManagement(dataSource)) - .willReturn(SchemaManagement.UNMANAGED); + given(provider.getSchemaManagement(dataSource)).willReturn(SchemaManagement.UNMANAGED); HibernateDefaultDdlAutoProvider ddlAutoProvider = new HibernateDefaultDdlAutoProvider( Collections.singletonList(provider)); - assertThat(ddlAutoProvider.getDefaultDdlAuto(dataSource)) - .isEqualTo("create-drop"); + assertThat(ddlAutoProvider.getDefaultDdlAuto(dataSource)).isEqualTo("create-drop"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java index 34c715e3e90..226ed3ed4f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java @@ -85,8 +85,7 @@ import static org.mockito.Mockito.mock; * @author Kazuki Shimizu * @author Stephane Nicoll */ -public class HibernateJpaAutoConfigurationTests - extends AbstractJpaAutoConfigurationTests { +public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTests { public HibernateJpaAutoConfigurationTests() { super(HibernateJpaAutoConfiguration.class); @@ -98,10 +97,8 @@ public class HibernateJpaAutoConfigurationTests // Missing: "spring.datasource.schema:classpath:/ddl.sql").run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining("ddl.sql"); - assertThat(context.getStartupFailure()) - .hasMessageContaining("spring.datasource.schema"); + assertThat(context.getStartupFailure()).hasMessageContaining("ddl.sql"); + assertThat(context.getStartupFailure()).hasMessageContaining("spring.datasource.schema"); }); } @@ -110,24 +107,19 @@ public class HibernateJpaAutoConfigurationTests // This can't succeed because the data SQL is executed immediately after the // schema // and Hibernate hasn't initialized yet at that point - contextRunner().withPropertyValues("spring.datasource.data:classpath:/city.sql") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(BeanCreationException.class); - }); + contextRunner().withPropertyValues("spring.datasource.data:classpath:/city.sql").run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class); + }); } @Test public void testDataScriptRunsEarly() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) .withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.jpa.show-sql=true", - "spring.jpa.hibernate.ddl-auto:create-drop", + .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", "spring.datasource.data:classpath:/city.sql") - .run((context) -> assertThat( - context.getBean(TestInitializedJpaConfiguration.class).called) - .isTrue()); + .run((context) -> assertThat(context.getBean(TestInitializedJpaConfiguration.class).called).isTrue()); } @Test @@ -143,45 +135,40 @@ public class HibernateJpaAutoConfigurationTests public void testFlywayPlusValidation() { contextRunner() .withPropertyValues("spring.datasource.initialization-mode:never", - "spring.flyway.locations:classpath:db/city", - "spring.jpa.hibernate.ddl-auto:validate") + "spring.flyway.locations:classpath:db/city", "spring.jpa.hibernate.ddl-auto:validate") .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) .run((context) -> assertThat(context).hasNotFailed()); } @Test public void testLiquibasePlusValidation() { - contextRunner().withPropertyValues("spring.datasource.initialization-mode:never", - "spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", - "spring.jpa.hibernate.ddl-auto:validate") - .withConfiguration( - AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + contextRunner() + .withPropertyValues("spring.datasource.initialization-mode:never", + "spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", + "spring.jpa.hibernate.ddl-auto:validate") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) .run((context) -> assertThat(context).hasNotFailed()); } @Test public void hibernateDialectIsNotSetByDefault() { contextRunner().run(assertJpaVendorAdapter( - (adapter) -> assertThat(adapter.getJpaPropertyMap()) - .doesNotContainKeys("hibernate.dialect"))); + (adapter) -> assertThat(adapter.getJpaPropertyMap()).doesNotContainKeys("hibernate.dialect"))); } @Test public void hibernateDialectIsSetWhenDatabaseIsSet() { contextRunner().withPropertyValues("spring.jpa.database=H2") - .run(assertJpaVendorAdapter( - (adapter) -> assertThat(adapter.getJpaPropertyMap()).contains( - entry("hibernate.dialect", H2Dialect.class.getName())))); + .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) + .contains(entry("hibernate.dialect", H2Dialect.class.getName())))); } @Test public void hibernateDialectIsSetWhenDatabasePlatformIsSet() { String databasePlatform = TestH2Dialect.class.getName(); - contextRunner() - .withPropertyValues("spring.jpa.database-platform=" + databasePlatform) - .run(assertJpaVendorAdapter( - (adapter) -> assertThat(adapter.getJpaPropertyMap()) - .contains(entry("hibernate.dialect", databasePlatform)))); + contextRunner().withPropertyValues("spring.jpa.database-platform=" + databasePlatform) + .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) + .contains(entry("hibernate.dialect", databasePlatform)))); } private ContextConsumer assertJpaVendorAdapter( @@ -195,8 +182,7 @@ public class HibernateJpaAutoConfigurationTests @Test public void jtaDefaultPlatform() { - contextRunner() - .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) + contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) .run(assertJtaPlatform(SpringJtaPlatform.class)); } @@ -204,8 +190,7 @@ public class HibernateJpaAutoConfigurationTests public void jtaCustomPlatform() { contextRunner() .withPropertyValues( - "spring.jpa.properties.hibernate.transaction.jta.platform:" - + TestJtaPlatform.class.getName()) + "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) .run(assertJtaPlatform(TestJtaPlatform.class)); } @@ -215,25 +200,19 @@ public class HibernateJpaAutoConfigurationTests contextRunner().run(assertJtaPlatform(NoJtaPlatform.class)); } - private ContextConsumer assertJtaPlatform( - Class expectedType) { + private ContextConsumer assertJtaPlatform(Class expectedType) { return (context) -> { - SessionFactoryImpl sessionFactory = context - .getBean(LocalContainerEntityManagerFactoryBean.class) + SessionFactoryImpl sessionFactory = context.getBean(LocalContainerEntityManagerFactoryBean.class) .getNativeEntityManagerFactory().unwrap(SessionFactoryImpl.class); - assertThat(sessionFactory.getServiceRegistry().getService(JtaPlatform.class)) - .isInstanceOf(expectedType); + assertThat(sessionFactory.getServiceRegistry().getService(JtaPlatform.class)).isInstanceOf(expectedType); }; } @Test public void jtaCustomTransactionManagerUsingProperties() { - contextRunner() - .withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") - .run((context) -> { - JpaTransactionManager transactionManager = context - .getBean(JpaTransactionManager.class); + contextRunner().withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true").run((context) -> { + JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); }); @@ -242,11 +221,9 @@ public class HibernateJpaAutoConfigurationTests @Test public void autoConfigurationBacksOffWithSeveralDataSources() { contextRunner() - .withConfiguration(AutoConfigurations.of( - DataSourceTransactionManagerAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class)) - .withUserConfiguration(TestTwoDataSourcesConfiguration.class) - .run((context) -> { + .withUserConfiguration(TestTwoDataSourcesConfiguration.class).run((context) -> { assertThat(context).hasNotFailed(); assertThat(context).doesNotHaveBean(EntityManagerFactory.class); }); @@ -254,71 +231,58 @@ public class HibernateJpaAutoConfigurationTests @Test public void providerDisablesAutoCommitIsConfigured() { - contextRunner().withPropertyValues( - "spring.datasource.type:" + HikariDataSource.class.getName(), + contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:false").run((context) -> { - Map jpaProperties = context - .getBean(LocalContainerEntityManagerFactoryBean.class) + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat(jpaProperties).contains(entry( - "hibernate.connection.provider_disables_autocommit", "true")); + assertThat(jpaProperties) + .contains(entry("hibernate.connection.provider_disables_autocommit", "true")); }); } @Test public void providerDisablesAutoCommitIsNotConfiguredIfAutoCommitIsEnabled() { - contextRunner().withPropertyValues( - "spring.datasource.type:" + HikariDataSource.class.getName(), + contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:true").run((context) -> { - Map jpaProperties = context - .getBean(LocalContainerEntityManagerFactoryBean.class) + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat(jpaProperties).doesNotContainKeys( - "hibernate.connection.provider_disables_autocommit"); + assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); }); } @Test public void providerDisablesAutoCommitIsNotConfiguredIfPropertyIsSet() { - contextRunner().withPropertyValues( - "spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false", - "spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false") + contextRunner() + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false", + "spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false") .run((context) -> { - Map jpaProperties = context - .getBean(LocalContainerEntityManagerFactoryBean.class) + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat(jpaProperties).contains( - entry("hibernate.connection.provider_disables_autocommit", - "false")); + assertThat(jpaProperties) + .contains(entry("hibernate.connection.provider_disables_autocommit", "false")); }); } @Test public void providerDisablesAutoCommitIsNotConfiguredWithJta() { - contextRunner() - .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .withPropertyValues( - "spring.datasource.type:" + HikariDataSource.class.getName(), + contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:false") .run((context) -> { - Map jpaProperties = context - .getBean(LocalContainerEntityManagerFactoryBean.class) + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat(jpaProperties).doesNotContainKeys( - "hibernate.connection.provider_disables_autocommit"); + assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); }); } @Test public void customResourceMapping() { contextRunner().withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues( - "spring.datasource.data:classpath:/db/non-annotated-data.sql", + .withPropertyValues("spring.datasource.data:classpath:/db/non-annotated-data.sql", "spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml") .run((context) -> { - EntityManager em = context.getBean(EntityManagerFactory.class) - .createEntityManager(); + EntityManager em = context.getBean(EntityManagerFactory.class).createEntityManager(); NonAnnotatedEntity found = em.find(NonAnnotatedEntity.class, 2000L); assertThat(found).isNotNull(); assertThat(found.getValue()).isEqualTo("Test"); @@ -327,34 +291,24 @@ public class HibernateJpaAutoConfigurationTests @Test public void physicalNamingStrategyCanBeUsed() { - contextRunner() - .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class) - .run((context) -> { - Map hibernateProperties = context - .getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties) - .contains(entry("hibernate.physical_naming_strategy", - context.getBean("testPhysicalNamingStrategy"))); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); - }); + contextRunner().withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class).run((context) -> { + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) + .getVendorProperties(); + assertThat(hibernateProperties).contains( + entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy"))); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + }); } @Test public void implicitNamingStrategyCanBeUsed() { - contextRunner() - .withUserConfiguration(TestImplicitNamingStrategyConfiguration.class) - .run((context) -> { - Map hibernateProperties = context - .getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties) - .contains(entry("hibernate.implicit_naming_strategy", - context.getBean("testImplicitNamingStrategy"))); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); - }); + contextRunner().withUserConfiguration(TestImplicitNamingStrategyConfiguration.class).run((context) -> { + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) + .getVendorProperties(); + assertThat(hibernateProperties).contains( + entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + }); } @Test @@ -362,62 +316,46 @@ public class HibernateJpaAutoConfigurationTests contextRunner() .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) - .withPropertyValues( - "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", + .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") .run((context) -> { - Map hibernateProperties = context - .getBean(HibernateJpaConfiguration.class) + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) .getVendorProperties(); assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", - context.getBean("testPhysicalNamingStrategy")), - entry("hibernate.implicit_naming_strategy", - context.getBean("testImplicitNamingStrategy"))); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")), + entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); }); } @Test public void hibernatePropertiesCustomizerTakesPrecedenceOverStrategyInstancesAndNamingStrategyProperties() { contextRunner() - .withUserConfiguration( - TestHibernatePropertiesCustomizerConfiguration.class, - TestPhysicalNamingStrategyConfiguration.class, - TestImplicitNamingStrategyConfiguration.class) - .withPropertyValues( - "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", + .withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class, + TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) + .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") .run((context) -> { - Map hibernateProperties = context - .getBean(HibernateJpaConfiguration.class) + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) .getVendorProperties(); TestHibernatePropertiesCustomizerConfiguration configuration = context - .getBean( - TestHibernatePropertiesCustomizerConfiguration.class); + .getBean(TestHibernatePropertiesCustomizerConfiguration.class); assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", - configuration.physicalNamingStrategy), - entry("hibernate.implicit_naming_strategy", - configuration.implicitNamingStrategy)); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + entry("hibernate.physical_naming_strategy", configuration.physicalNamingStrategy), + entry("hibernate.implicit_naming_strategy", configuration.implicitNamingStrategy)); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); }); } @Test public void eventListenerCanBeRegisteredAsBeans() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) - .withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.jpa.show-sql=true", - "spring.jpa.hibernate.ddl-auto:create-drop", - "spring.datasource.data:classpath:/city.sql") + .withClassLoader(new HideDataScriptClassLoader()).withPropertyValues("spring.jpa.show-sql=true", + "spring.jpa.hibernate.ddl-auto:create-drop", "spring.datasource.data:classpath:/city.sql") .run((context) -> { // See CityListener assertThat(context).hasSingleBean(City.class); - assertThat(context.getBean(City.class).getName()) - .isEqualTo("Washington"); + assertThat(context.getBean(City.class).getName()).isEqualTo("Washington"); }); } @@ -429,16 +367,11 @@ public class HibernateJpaAutoConfigurationTests @Test public void withSyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { - contextRunner() - .withUserConfiguration(JpaUsingApplicationListenerConfiguration.class) - .withPropertyValues("spring.datasource.initialization-mode=never") - .run((context) -> { + contextRunner().withUserConfiguration(JpaUsingApplicationListenerConfiguration.class) + .withPropertyValues("spring.datasource.initialization-mode=never").run((context) -> { assertThat(context).hasNotFailed(); - assertThat(context - .getBean(EventCapturingApplicationListener.class).events - .stream() - .filter(DataSourceSchemaCreatedEvent.class::isInstance)) - .hasSize(1); + assertThat(context.getBean(EventCapturingApplicationListener.class).events.stream() + .filter(DataSourceSchemaCreatedEvent.class::isInstance)).hasSize(1); }); } @@ -447,24 +380,20 @@ public class HibernateJpaAutoConfigurationTests contextRunner() .withUserConfiguration(AsyncBootstrappingConfiguration.class, JpaUsingApplicationListenerConfiguration.class) - .withPropertyValues("spring.datasource.initialization-mode=never") - .run((context) -> { + .withPropertyValues("spring.datasource.initialization-mode=never").run((context) -> { assertThat(context).hasNotFailed(); EventCapturingApplicationListener listener = context .getBean(EventCapturingApplicationListener.class); long end = System.currentTimeMillis() + 30000; - while ((System.currentTimeMillis() < end) - && !dataSourceSchemaCreatedEventReceived(listener)) { + while ((System.currentTimeMillis() < end) && !dataSourceSchemaCreatedEventReceived(listener)) { Thread.sleep(100); } - assertThat(listener.events.stream() - .filter(DataSourceSchemaCreatedEvent.class::isInstance)) - .hasSize(1); + assertThat(listener.events.stream().filter(DataSourceSchemaCreatedEvent.class::isInstance)) + .hasSize(1); }); } - private boolean dataSourceSchemaCreatedEventReceived( - EventCapturingApplicationListener listener) { + private boolean dataSourceSchemaCreatedEventReceived(EventCapturingApplicationListener listener) { for (ApplicationEvent event : listener.events) { if (event instanceof DataSourceSchemaCreatedEvent) { return true; @@ -480,8 +409,7 @@ public class HibernateJpaAutoConfigurationTests private boolean called; @Autowired - public void validateDataSourceIsInitialized( - EntityManagerFactory entityManagerFactory) { + public void validateDataSourceIsInitialized(EntityManagerFactory entityManagerFactory) { // Inject the entity manager to validate it is initialized at the injection // point EntityManager entityManager = entityManagerFactory.createEntityManager(); @@ -523,10 +451,8 @@ public class HibernateJpaAutoConfigurationTests @Bean public HibernatePropertiesCustomizer testHibernatePropertiesCustomizer() { return (hibernateProperties) -> { - hibernateProperties.put("hibernate.physical_naming_strategy", - this.physicalNamingStrategy); - hibernateProperties.put("hibernate.implicit_naming_strategy", - this.implicitNamingStrategy); + hibernateProperties.put("hibernate.physical_naming_strategy", this.physicalNamingStrategy); + hibernateProperties.put("hibernate.implicit_naming_strategy", this.implicitNamingStrategy); }; } @@ -537,8 +463,7 @@ public class HibernateJpaAutoConfigurationTests @Bean public HibernatePropertiesCustomizer disableBeanContainerHibernatePropertiesCustomizer() { - return (hibernateProperties) -> hibernateProperties - .remove(AvailableSettings.BEAN_CONTAINER); + return (hibernateProperties) -> hibernateProperties.remove(AvailableSettings.BEAN_CONTAINER); } } @@ -579,8 +504,7 @@ public class HibernateJpaAutoConfigurationTests private static class HideDataScriptClassLoader extends URLClassLoader { - private static final List HIDDEN_RESOURCES = Arrays - .asList("schema-all.sql", "schema.sql"); + private static final List HIDDEN_RESOURCES = Arrays.asList("schema-all.sql", "schema.sql"); HideDataScriptClassLoader() { super(new URL[0], HideDataScriptClassLoader.class.getClassLoader()); @@ -600,13 +524,11 @@ public class HibernateJpaAutoConfigurationTests static class JpaUsingApplicationListenerConfiguration { @Bean - public EventCapturingApplicationListener jpaUsingApplicationListener( - EntityManagerFactory emf) { + public EventCapturingApplicationListener jpaUsingApplicationListener(EntityManagerFactory emf) { return new EventCapturingApplicationListener(); } - static class EventCapturingApplicationListener - implements ApplicationListener { + static class EventCapturingApplicationListener implements ApplicationListener { private final List events = new ArrayList<>(); @@ -628,8 +550,7 @@ public class HibernateJpaAutoConfigurationTests } @Bean - public EntityManagerFactoryBuilderCustomizer asyncBootstrappingCustomizer( - ThreadPoolTaskExecutor executor) { + public EntityManagerFactoryBuilderCustomizer asyncBootstrappingCustomizer(ThreadPoolTaskExecutor executor) { return (builder) -> builder.setBootstrapExecutor(executor); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java index d8a94f3db82..0687ab45b21 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java @@ -61,84 +61,66 @@ public class HibernatePropertiesTests { @Test public void noCustomNamingStrategy() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> { - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); - assertThat(hibernateProperties).containsEntry( - AvailableSettings.PHYSICAL_NAMING_STRATEGY, + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + assertThat(hibernateProperties).containsEntry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, SpringPhysicalNamingStrategy.class.getName()); - assertThat(hibernateProperties).containsEntry( - AvailableSettings.IMPLICIT_NAMING_STRATEGY, + assertThat(hibernateProperties).containsEntry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, SpringImplicitNamingStrategy.class.getName()); })); } @Test public void hibernate5CustomNamingStrategies() { - this.contextRunner.withPropertyValues( - "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", - "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") + this.contextRunner + .withPropertyValues("spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", + "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") .run(assertHibernateProperties((hibernateProperties) -> { assertThat(hibernateProperties).contains( - entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, - "com.example.Implicit"), - entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, - "com.example.Physical")); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), + entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); })); } @Test public void hibernate5CustomNamingStrategiesViaJpaProperties() { - this.contextRunner.withPropertyValues( - "spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", - "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") + this.contextRunner + .withPropertyValues("spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", + "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") .run(assertHibernateProperties((hibernateProperties) -> { // You can override them as we don't provide any default assertThat(hibernateProperties).contains( - entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, - "com.example.Implicit"), - entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, - "com.example.Physical")); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), + entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); })); } @Test public void useNewIdGeneratorMappingsDefault() { - this.contextRunner.run(assertHibernateProperties( - (hibernateProperties) -> assertThat(hibernateProperties).containsEntry( - AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"))); + this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) + .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"))); } @Test public void useNewIdGeneratorMappingsFalse() { - this.contextRunner - .withPropertyValues( - "spring.jpa.hibernate.use-new-id-generator-mappings:false") - .run(assertHibernateProperties( - (hibernateProperties) -> assertThat(hibernateProperties) - .containsEntry( - AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, - "false"))); + this.contextRunner.withPropertyValues("spring.jpa.hibernate.use-new-id-generator-mappings:false") + .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) + .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"))); } @Test public void scannerUsesDisabledScannerByDefault() { - this.contextRunner.run(assertHibernateProperties( - (hibernateProperties) -> assertThat(hibernateProperties).containsEntry( - AvailableSettings.SCANNER, - "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); + this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) + .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); } @Test public void scannerCanBeCustomized() { this.contextRunner.withPropertyValues( "spring.jpa.properties.hibernate.archive.scanner:org.hibernate.boot.archive.scan.internal.StandardScanner") - .run(assertHibernateProperties((hibernateProperties) -> assertThat( - hibernateProperties).containsEntry(AvailableSettings.SCANNER, - "org.hibernate.boot.archive.scan.internal.StandardScanner"))); + .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties).containsEntry( + AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner"))); } @Test @@ -149,16 +131,13 @@ public class HibernatePropertiesTests { @Test public void defaultDdlAutoIsNotInvokedIfHibernateSpecificPropertyIsSet() { - this.contextRunner - .withPropertyValues("spring.jpa.properties.hibernate.hbm2ddl.auto=create") + this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.hbm2ddl.auto=create") .run(assertDefaultDdlAutoNotInvoked("create")); } - private ContextConsumer assertDefaultDdlAutoNotInvoked( - String expectedDdlAuto) { + private ContextConsumer assertDefaultDdlAutoNotInvoked(String expectedDdlAuto) { return assertHibernateProperties((hibernateProperties) -> { - assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, - expectedDdlAuto); + assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, expectedDdlAuto); verify(this.ddlAutoSupplier, never()).get(); }); } @@ -168,9 +147,8 @@ public class HibernatePropertiesTests { return (context) -> { assertThat(context).hasSingleBean(JpaProperties.class); assertThat(context).hasSingleBean(HibernateProperties.class); - Map hibernateProperties = context - .getBean(HibernateProperties.class).determineHibernateProperties( - context.getBean(JpaProperties.class).getProperties(), + Map hibernateProperties = context.getBean(HibernateProperties.class) + .determineHibernateProperties(context.getBean(JpaProperties.class).getProperties(), new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); consumer.accept(hibernateProperties); }; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java index d1e796e3b32..0ca8fbbd55f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java @@ -71,8 +71,7 @@ public class JpaPropertiesTests { @SuppressWarnings("deprecation") public void determineDatabaseWithKnownUrl() { this.contextRunner.run(assertJpaProperties((properties) -> { - Database database = properties - .determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); + Database database = properties.determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); assertThat(database).isEqualTo(Database.H2); })); } @@ -81,12 +80,10 @@ public class JpaPropertiesTests { @Deprecated @SuppressWarnings("deprecation") public void determineDatabaseWithKnownUrlAndUserConfig() { - this.contextRunner.withPropertyValues("spring.jpa.database=mysql") - .run(assertJpaProperties((properties) -> { - Database database = properties - .determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); - assertThat(database).isEqualTo(Database.MYSQL); - })); + this.contextRunner.withPropertyValues("spring.jpa.database=mysql").run(assertJpaProperties((properties) -> { + Database database = properties.determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); + assertThat(database).isEqualTo(Database.MYSQL); + })); } @Test @@ -94,8 +91,7 @@ public class JpaPropertiesTests { @SuppressWarnings("deprecation") public void determineDatabaseWithUnknownUrl() { this.contextRunner.run(assertJpaProperties((properties) -> { - Database database = properties - .determineDatabase(mockDataSource("jdbc:unknown://localhost")); + Database database = properties.determineDatabase(mockDataSource("jdbc:unknown://localhost")); assertThat(database).isEqualTo(Database.DEFAULT); })); } @@ -126,8 +122,7 @@ public class JpaPropertiesTests { return ds; } - private ContextConsumer assertJpaProperties( - Consumer consumer) { + private ContextConsumer assertJpaProperties(Consumer consumer) { return (context) -> { assertThat(context).hasSingleBean(JpaProperties.class); consumer.accept(context.getBean(JpaProperties.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java index 7591a8a3682..650df9f0251 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java @@ -80,76 +80,59 @@ public class QuartzAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getJobStoreClass()) - .isAssignableFrom(RAMJobStore.class); + assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(RAMJobStore.class); }); } @Test public void withDataSourceUseMemoryByDefault() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> { + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)).run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getJobStoreClass()) - .isAssignableFrom(RAMJobStore.class); + assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(RAMJobStore.class); }); } @Test public void withDataSource() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceJobStore("dataSource")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc").run(assertDataSourceJobStore("dataSource")); } @Test public void withDataSourceNoTransactionManager() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceJobStore("dataSource")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc").run(assertDataSourceJobStore("dataSource")); } @Test public void dataSourceWithQuartzDataSourceQualifierUsedWhenMultiplePresent() { - this.contextRunner - .withUserConfiguration(QuartzJobsConfiguration.class, - MultipleDataSourceConfiguration.class) + this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class, MultipleDataSourceConfiguration.class) .withPropertyValues("spring.quartz.job-store-type=jdbc") .run(assertDataSourceJobStore("quartzDataSource")); } - private ContextConsumer assertDataSourceJobStore( - String datasourceName) { + private ContextConsumer assertDataSourceJobStore(String datasourceName) { return (context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getJobStoreClass()) - .isAssignableFrom(LocalDataSourceJobStore.class); - JdbcTemplate jdbcTemplate = new JdbcTemplate( - context.getBean(datasourceName, DataSource.class)); - assertThat(jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM QRTZ_JOB_DETAILS", Integer.class)).isEqualTo(2); - assertThat(jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM QRTZ_SIMPLE_TRIGGERS", Integer.class)) - .isEqualTo(0); + assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(LocalDataSourceJobStore.class); + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(datasourceName, DataSource.class)); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_JOB_DETAILS", Integer.class)) + .isEqualTo(2); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_SIMPLE_TRIGGERS", Integer.class)) + .isEqualTo(0); }; } @Test public void withTaskExecutor() { this.contextRunner.withUserConfiguration(MockExecutorConfiguration.class) - .withPropertyValues( - "spring.quartz.properties.org.quartz.threadPool.threadCount=50") - .run((context) -> { + .withPropertyValues("spring.quartz.properties.org.quartz.threadPool.threadCount=50").run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50); @@ -161,51 +144,41 @@ public class QuartzAutoConfigurationTests { @Test public void withOverwriteExistingJobs() { this.contextRunner.withUserConfiguration(OverwriteTriggerConfiguration.class) - .withPropertyValues("spring.quartz.overwrite-existing-jobs=true") - .run((context) -> { + .withPropertyValues("spring.quartz.overwrite-existing-jobs=true").run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); - Trigger fooTrigger = scheduler - .getTrigger(TriggerKey.triggerKey("fooTrigger")); + Trigger fooTrigger = scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger")); assertThat(fooTrigger).isNotNull(); - assertThat(((SimpleTrigger) fooTrigger).getRepeatInterval()) - .isEqualTo(30000); + assertThat(((SimpleTrigger) fooTrigger).getRepeatInterval()).isEqualTo(30000); }); } @Test public void withConfiguredJobAndTrigger(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class) - .withPropertyValues("test-name=withConfiguredJobAndTrigger") - .run((context) -> { + .withPropertyValues("test-name=withConfiguredJobAndTrigger").run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))) - .isNotNull(); - assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))) - .isNotNull(); + assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull(); + assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull(); Thread.sleep(1000L); - assertThat(capturedOutput).contains("withConfiguredJobAndTrigger") - .contains("jobDataValue"); + assertThat(capturedOutput).contains("withConfiguredJobAndTrigger").contains("jobDataValue"); }); } @Test public void withConfiguredCalendars() { - this.contextRunner.withUserConfiguration(QuartzCalendarsConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getCalendar("weekly")).isNotNull(); - assertThat(scheduler.getCalendar("monthly")).isNotNull(); - }); + this.contextRunner.withUserConfiguration(QuartzCalendarsConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getCalendar("weekly")).isNotNull(); + assertThat(scheduler.getCalendar("monthly")).isNotNull(); + }); } @Test public void withQuartzProperties() { - this.contextRunner - .withPropertyValues( - "spring.quartz.properties.org.quartz.scheduler.instanceId=FOO") + this.contextRunner.withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceId=FOO") .run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); @@ -215,93 +188,76 @@ public class QuartzAutoConfigurationTests { @Test public void withCustomizer() { - this.contextRunner.withUserConfiguration(QuartzCustomConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getSchedulerName()).isEqualTo("fooScheduler"); - }); + this.contextRunner.withUserConfiguration(QuartzCustomConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getSchedulerName()).isEqualTo("fooScheduler"); + }); } @Test public void validateDefaultProperties() { - this.contextRunner.withUserConfiguration(ManualSchedulerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(SchedulerFactoryBean.class); - SchedulerFactoryBean schedulerFactory = context - .getBean(SchedulerFactoryBean.class); - QuartzProperties properties = new QuartzProperties(); - assertThat(properties.isAutoStartup()) - .isEqualTo(schedulerFactory.isAutoStartup()); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue( - "startupDelay", - (int) properties.getStartupDelay().getSeconds()); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue( - "waitForJobsToCompleteOnShutdown", - properties.isWaitForJobsToCompleteOnShutdown()); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue( - "overwriteExistingJobs", - properties.isOverwriteExistingJobs()); + this.contextRunner.withUserConfiguration(ManualSchedulerConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(SchedulerFactoryBean.class); + SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); + QuartzProperties properties = new QuartzProperties(); + assertThat(properties.isAutoStartup()).isEqualTo(schedulerFactory.isAutoStartup()); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("startupDelay", + (int) properties.getStartupDelay().getSeconds()); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("waitForJobsToCompleteOnShutdown", + properties.isWaitForJobsToCompleteOnShutdown()); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("overwriteExistingJobs", + properties.isOverwriteExistingJobs()); - }); + }); } @Test public void withCustomConfiguration() { - this.contextRunner.withPropertyValues("spring.quartz.auto-startup=false", - "spring.quartz.startup-delay=1m", + this.contextRunner.withPropertyValues("spring.quartz.auto-startup=false", "spring.quartz.startup-delay=1m", "spring.quartz.wait-for-jobs-to-complete-on-shutdown=true", "spring.quartz.overwrite-existing-jobs=true").run((context) -> { assertThat(context).hasSingleBean(SchedulerFactoryBean.class); - SchedulerFactoryBean schedulerFactory = context - .getBean(SchedulerFactoryBean.class); + SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); assertThat(schedulerFactory.isAutoStartup()).isFalse(); - assertThat(schedulerFactory) - .hasFieldOrPropertyWithValue("startupDelay", 60); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue( - "waitForJobsToCompleteOnShutdown", true); - assertThat(schedulerFactory) - .hasFieldOrPropertyWithValue("overwriteExistingJobs", true); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("startupDelay", 60); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("waitForJobsToCompleteOnShutdown", true); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("overwriteExistingJobs", true); }); } @Test public void schedulerNameWithDedicatedProperty() { - this.contextRunner - .withPropertyValues("spring.quartz.scheduler-name=testScheduler") + this.contextRunner.withPropertyValues("spring.quartz.scheduler-name=testScheduler") .run(assertSchedulerName("testScheduler")); } @Test public void schedulerNameWithQuartzProperty() { - this.contextRunner.withPropertyValues( - "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") + this.contextRunner + .withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") .run(assertSchedulerName("testScheduler")); } @Test public void schedulerNameWithDedicatedPropertyTakesPrecedence() { - this.contextRunner.withPropertyValues( - "spring.quartz.scheduler-name=specificTestScheduler", - "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") + this.contextRunner + .withPropertyValues("spring.quartz.scheduler-name=specificTestScheduler", + "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") .run(assertSchedulerName("specificTestScheduler")); } @Test public void schedulerNameUseBeanNameByDefault() { - this.contextRunner.withPropertyValues() - .run(assertSchedulerName("quartzScheduler")); + this.contextRunner.withPropertyValues().run(assertSchedulerName("quartzScheduler")); } - private ContextConsumer assertSchedulerName( - String schedulerName) { + private ContextConsumer assertSchedulerName(String schedulerName) { return (context) -> { assertThat(context).hasSingleBean(SchedulerFactoryBean.class); - SchedulerFactoryBean schedulerFactory = context - .getBean(SchedulerFactoryBean.class); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("schedulerName", - schedulerName); + SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("schedulerName", schedulerName); }; } @@ -316,14 +272,12 @@ public class QuartzAutoConfigurationTests { @Bean public JobDetail fooJob() { - return JobBuilder.newJob().ofType(FooJob.class).withIdentity("fooJob") - .storeDurably().build(); + return JobBuilder.newJob().ofType(FooJob.class).withIdentity("fooJob").storeDurably().build(); } @Bean public JobDetail barJob() { - return JobBuilder.newJob().ofType(FooJob.class).withIdentity("barJob") - .storeDurably().build(); + return JobBuilder.newJob().ofType(FooJob.class).withIdentity("barJob").storeDurably().build(); } } @@ -339,11 +293,11 @@ public class QuartzAutoConfigurationTests { @Bean public Trigger fooTrigger(JobDetail jobDetail) { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(10).repeatForever(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10) + .repeatForever(); - return TriggerBuilder.newTrigger().forJob(jobDetail) - .withIdentity("fooTrigger").withSchedule(scheduleBuilder).build(); + return TriggerBuilder.newTrigger().forJob(jobDetail).withIdentity("fooTrigger") + .withSchedule(scheduleBuilder).build(); } } @@ -354,11 +308,11 @@ public class QuartzAutoConfigurationTests { @Bean public Trigger anotherFooTrigger(JobDetail fooJob) { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(30).repeatForever(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(30) + .repeatForever(); - return TriggerBuilder.newTrigger().forJob(fooJob).withIdentity("fooTrigger") - .withSchedule(scheduleBuilder).build(); + return TriggerBuilder.newTrigger().forJob(fooJob).withIdentity("fooTrigger").withSchedule(scheduleBuilder) + .build(); } } @@ -393,8 +347,7 @@ public class QuartzAutoConfigurationTests { @Bean public SchedulerFactoryBeanCustomizer customizer() { - return (schedulerFactoryBean) -> schedulerFactoryBean - .setSchedulerName("fooScheduler"); + return (schedulerFactoryBean) -> schedulerFactoryBean.setSchedulerName("fooScheduler"); } } @@ -410,8 +363,7 @@ public class QuartzAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - protected static class MultipleDataSourceConfiguration - extends BaseQuartzConfiguration { + protected static class MultipleDataSourceConfiguration extends BaseQuartzConfiguration { @Bean @Primary @@ -451,8 +403,7 @@ public class QuartzAutoConfigurationTests { @Override protected void executeInternal(JobExecutionContext context) { - System.out.println(this.env.getProperty("test-name", "unknown") + " - " - + this.jobDataKey); + System.out.println(this.env.getProperty("test-name", "unknown") + " - " + this.jobDataKey); } public void setJobDataKey(String jobDataKey) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java index 81be24ef566..88cdf9eb898 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java @@ -42,22 +42,20 @@ import static org.assertj.core.api.Assertions.assertThat; public class QuartzDataSourceInitializerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)) .withPropertyValues("spring.datasource.url=" + String.format( - "jdbc:h2:mem:test-%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", - UUID.randomUUID().toString())); + "jdbc:h2:mem:test-%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", UUID.randomUUID().toString())); @Test public void commentPrefixCanBeCustomized() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.quartz.jdbc.comment-prefix=##", - "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_@@platform@@.sql") + this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( + "spring.quartz.jdbc.comment-prefix=##", + "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_@@platform@@.sql") .run((context) -> { JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); - assertThat(jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM QRTZ_TEST_TABLE", Integer.class)) - .isEqualTo(0); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_TEST_TABLE", Integer.class)) + .isEqualTo(0); }); } @@ -66,10 +64,9 @@ public class QuartzDataSourceInitializerTests { static class TestConfiguration { @Bean - public QuartzDataSourceInitializer initializer(DataSource dataSource, - ResourceLoader resourceLoader, QuartzProperties properties) { - return new QuartzDataSourceInitializer(dataSource, resourceLoader, - properties); + public QuartzDataSourceInitializer initializer(DataSource dataSource, ResourceLoader resourceLoader, + QuartzProperties properties) { + return new QuartzDataSourceInitializer(dataSource, resourceLoader, properties); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/core/ReactorCoreAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/core/ReactorCoreAutoConfigurationTests.java index bdb6d03ad4e..14dda20cc7b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/core/ReactorCoreAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/core/ReactorCoreAutoConfigurationTests.java @@ -52,23 +52,18 @@ class ReactorCoreAutoConfigurationTests { @Test void debugOperatorIsSetWithProperty() { - this.contextRunner.withPropertyValues("spring.reactor.debug=true") - .run(assertDebugOperator(true)); + this.contextRunner.withPropertyValues("spring.reactor.debug=true").run(assertDebugOperator(true)); } @Test @Deprecated void debugOperatorIsSetWithDeprecatedProperty() { - this.contextRunner - .withPropertyValues("spring.reactor.stacktrace-mode.enabled=true") + this.contextRunner.withPropertyValues("spring.reactor.stacktrace-mode.enabled=true") .run(assertDebugOperator(true)); } - private ContextConsumer assertDebugOperator( - boolean expected) { - return (context) -> assertThat( - ReflectionTestUtils.getField(Hooks.class, "GLOBAL_TRACE")) - .isEqualTo(expected); + private ContextConsumer assertDebugOperator(boolean expected) { + return (context) -> assertThat(ReflectionTestUtils.getField(Hooks.class, "GLOBAL_TRACE")).isEqualTo(expected); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java index 25f4d88032f..c979f46e9b0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class RSocketMessagingAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class); @Test @@ -53,22 +52,18 @@ public class RSocketMessagingAutoConfigurationTests { @Test public void shouldFailOnMissingStrategies() { - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) + new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) .run((context) -> { assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getMessage()) - .contains("No qualifying bean of type " - + "'org.springframework.messaging.rsocket.RSocketStrategies' available"); + assertThat(context.getStartupFailure().getMessage()).contains("No qualifying bean of type " + + "'org.springframework.messaging.rsocket.RSocketStrategies' available"); }); } @Test public void shouldUseCustomMessageHandlerAcceptor() { this.contextRunner.withUserConfiguration(CustomMessageHandlerAcceptor.class) - .run((context) -> assertThat(context) - .getBeanNames(MessageHandlerAcceptor.class) + .run((context) -> assertThat(context).getBeanNames(MessageHandlerAcceptor.class) .containsOnly("customMessageHandlerAcceptor")); } @@ -77,8 +72,7 @@ public class RSocketMessagingAutoConfigurationTests { @Bean public RSocketStrategies rSocketStrategies() { - return RSocketStrategies.builder() - .encoder(CharSequenceEncoder.textPlainOnly()) + return RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) .decoder(StringDecoder.textPlainOnly()).build(); } @@ -90,8 +84,7 @@ public class RSocketMessagingAutoConfigurationTests { @Bean public MessageHandlerAcceptor customMessageHandlerAcceptor() { MessageHandlerAcceptor acceptor = new MessageHandlerAcceptor(); - RSocketStrategies strategies = RSocketStrategies.builder() - .encoder(CharSequenceEncoder.textPlainOnly()) + RSocketStrategies strategies = RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) .decoder(StringDecoder.textPlainOnly()).build(); acceptor.setRSocketStrategies(strategies); return acceptor; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java index 571babbafa4..d295a6b0144 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java @@ -34,36 +34,29 @@ import static org.mockito.Mockito.mock; */ public class RSocketRequesterAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, - RSocketRequesterAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)); @Test public void shouldCreateBuilder() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(RSocketRequester.Builder.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RSocketRequester.Builder.class)); } @Test public void shouldGetPrototypeScopedBean() { this.contextRunner.run((context) -> { - RSocketRequester.Builder first = context - .getBean(RSocketRequester.Builder.class); - RSocketRequester.Builder second = context - .getBean(RSocketRequester.Builder.class); + RSocketRequester.Builder first = context.getBean(RSocketRequester.Builder.class); + RSocketRequester.Builder second = context.getBean(RSocketRequester.Builder.class); assertThat(first).isNotEqualTo(second); }); } @Test public void shouldNotCreateBuilderIfAlreadyPresent() { - this.contextRunner.withUserConfiguration(CustomRSocketRequesterBuilder.class) - .run((context) -> { - RSocketRequester.Builder builder = context - .getBean(RSocketRequester.Builder.class); - assertThat(builder).isInstanceOf(MyRSocketRequesterBuilder.class); - }); + this.contextRunner.withUserConfiguration(CustomRSocketRequesterBuilder.class).run((context) -> { + RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); + assertThat(builder).isInstanceOf(MyRSocketRequesterBuilder.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java index 67acf51d487..7a3fd5805af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java @@ -43,19 +43,15 @@ public class RSocketServerAutoConfigurationTests { @Test public void shouldNotCreateBeansByDefault() { ApplicationContextRunner contextRunner = createContextRunner(); - contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class) - .doesNotHaveBean(RSocketServerBootstrap.class)); + contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); } @Test public void shouldNotCreateDefaultBeansForReactiveWebAppWithoutMapping() { ReactiveWebApplicationContextRunner contextRunner = createReactiveWebContextRunner(); - contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class) - .doesNotHaveBean(RSocketServerBootstrap.class)); + contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); } @Test @@ -64,10 +60,8 @@ public class RSocketServerAutoConfigurationTests { contextRunner .withPropertyValues("spring.rsocket.server.transport=tcp", "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context) - .doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class) - .doesNotHaveBean(RSocketServerBootstrap.class)); + .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); } @Test @@ -76,29 +70,24 @@ public class RSocketServerAutoConfigurationTests { contextRunner .withPropertyValues("spring.rsocket.server.transport=websocket", "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context) - .hasSingleBean(RSocketWebSocketNettyRouteProvider.class)); + .run((context) -> assertThat(context).hasSingleBean(RSocketWebSocketNettyRouteProvider.class)); } @Test public void shouldCreateDefaultBeansForRSocketServerWhenPortIsSet() { ReactiveWebApplicationContextRunner contextRunner = createReactiveWebContextRunner(); - contextRunner.withPropertyValues("spring.rsocket.server.port=0") - .run((context) -> assertThat(context) - .hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class)); + contextRunner.withPropertyValues("spring.rsocket.server.port=0").run((context) -> assertThat(context) + .hasSingleBean(RSocketServerFactory.class).hasSingleBean(RSocketServerBootstrap.class)); } private ApplicationContextRunner createContextRunner() { - return new ApplicationContextRunner() - .withUserConfiguration(BaseConfiguration.class).withConfiguration( - AutoConfigurations.of(RSocketServerAutoConfiguration.class)); + return new ApplicationContextRunner().withUserConfiguration(BaseConfiguration.class) + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); } private ReactiveWebApplicationContextRunner createReactiveWebContextRunner() { - return new ReactiveWebApplicationContextRunner() - .withUserConfiguration(BaseConfiguration.class).withConfiguration( - AutoConfigurations.of(RSocketServerAutoConfiguration.class)); + return new ReactiveWebApplicationContextRunner().withUserConfiguration(BaseConfiguration.class) + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); } @Configuration @@ -108,8 +97,7 @@ public class RSocketServerAutoConfigurationTests { public MessageHandlerAcceptor messageHandlerAcceptor() { MessageHandlerAcceptor messageHandlerAcceptor = new MessageHandlerAcceptor(); messageHandlerAcceptor.setRSocketStrategies(RSocketStrategies.builder() - .encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.textPlainOnly()).build()); + .encoder(CharSequenceEncoder.textPlainOnly()).decoder(StringDecoder.textPlainOnly()).build()); return messageHandlerAcceptor; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java index c9348992120..5fd8d8ceceb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java @@ -45,8 +45,8 @@ import static org.assertj.core.api.Assertions.assertThat; public class RSocketStrategiesAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(BaseConfiguration.class).withConfiguration( - AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class)); + .withUserConfiguration(BaseConfiguration.class) + .withConfiguration(AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class)); @Test public void shouldCreateDefaultBeans() { @@ -54,18 +54,13 @@ public class RSocketStrategiesAutoConfigurationTests { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); RSocketStrategies strategies = context.getBean(RSocketStrategies.class); assertThat(strategies.decoders()).hasSize(3); - assertThat(strategies.decoders().get(0)) - .isInstanceOf(Jackson2CborDecoder.class); - assertThat(strategies.decoders().get(1)) - .isInstanceOf(Jackson2JsonDecoder.class); + assertThat(strategies.decoders().get(0)).isInstanceOf(Jackson2CborDecoder.class); + assertThat(strategies.decoders().get(1)).isInstanceOf(Jackson2JsonDecoder.class); assertThat(strategies.decoders().get(2)).isInstanceOf(StringDecoder.class); assertThat(strategies.encoders()).hasSize(3); - assertThat(strategies.encoders().get(0)) - .isInstanceOf(Jackson2CborEncoder.class); - assertThat(strategies.encoders().get(1)) - .isInstanceOf(Jackson2JsonEncoder.class); - assertThat(strategies.encoders().get(2)) - .isInstanceOf(CharSequenceEncoder.class); + assertThat(strategies.encoders().get(0)).isInstanceOf(Jackson2CborEncoder.class); + assertThat(strategies.encoders().get(1)).isInstanceOf(Jackson2JsonEncoder.class); + assertThat(strategies.encoders().get(2)).isInstanceOf(CharSequenceEncoder.class); }); } @@ -73,23 +68,18 @@ public class RSocketStrategiesAutoConfigurationTests { public void shouldUseCustomStrategies() { this.contextRunner.withUserConfiguration(UserStrategies.class).run((context) -> { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); - assertThat(context.getBeanNamesForType(RSocketStrategies.class)) - .contains("customRSocketStrategies"); + assertThat(context.getBeanNamesForType(RSocketStrategies.class)).contains("customRSocketStrategies"); }); } @Test public void shouldUseStrategiesCustomizer() { - this.contextRunner.withUserConfiguration(StrategiesCustomizer.class) - .run((context) -> { - assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); - RSocketStrategies strategies = context - .getBean(RSocketStrategies.class); - assertThat(strategies.decoders()).hasSize(4) - .hasAtLeastOneElementOfType(ByteArrayDecoder.class); - assertThat(strategies.encoders()).hasSize(4) - .hasAtLeastOneElementOfType(ByteArrayEncoder.class); - }); + this.contextRunner.withUserConfiguration(StrategiesCustomizer.class).run((context) -> { + assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); + RSocketStrategies strategies = context.getBean(RSocketStrategies.class); + assertThat(strategies.decoders()).hasSize(4).hasAtLeastOneElementOfType(ByteArrayDecoder.class); + assertThat(strategies.encoders()).hasSize(4).hasAtLeastOneElementOfType(ByteArrayEncoder.class); + }); } @Configuration @@ -112,8 +102,7 @@ public class RSocketStrategiesAutoConfigurationTests { @Bean public RSocketStrategies customRSocketStrategies() { - return RSocketStrategies.builder() - .encoder(CharSequenceEncoder.textPlainOnly()) + return RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) .decoder(StringDecoder.textPlainOnly()).build(); } @@ -124,8 +113,7 @@ public class RSocketStrategiesAutoConfigurationTests { @Bean public RSocketStrategiesCustomizer myCustomizer() { - return (strategies) -> strategies.encoder(new ByteArrayEncoder()) - .decoder(new ByteArrayDecoder()); + return (strategies) -> strategies.encoder(new ByteArrayEncoder()).decoder(new ByteArrayDecoder()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java index 0110a93eab1..bf18eb8bef7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java @@ -56,51 +56,37 @@ public class RSocketWebSocketNettyRouteProviderTests { @Test public void webEndpointsShouldWork() throws Exception { - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(HttpHandlerAutoConfiguration.class, - WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - JacksonAutoConfiguration.class, - CodecsAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class, - RSocketServerAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, - RSocketRequesterAutoConfiguration.class)) - .withUserConfiguration(WebConfiguration.class) - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> { - ReactiveWebServerApplicationContext serverContext = (ReactiveWebServerApplicationContext) context - .getSourceApplicationContext(); - RSocketRequester requester = createRSocketRequester(context, - serverContext.getWebServer()); - TestProtocol rsocketResponse = requester.route("websocket") - .data(new TestProtocol("rsocket")) - .retrieveMono(TestProtocol.class) - .block(Duration.ofSeconds(3)); - assertThat(rsocketResponse.getName()).isEqualTo("rsocket"); - WebTestClient client = createWebTestClient( - serverContext.getWebServer()); - client.get().uri("/protocol").exchange().expectStatus().isOk() - .expectBody().jsonPath("name", "http"); - }); + new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) + .withConfiguration( + AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class, RSocketServerAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)) + .withUserConfiguration(WebConfiguration.class) + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> { + ReactiveWebServerApplicationContext serverContext = (ReactiveWebServerApplicationContext) context + .getSourceApplicationContext(); + RSocketRequester requester = createRSocketRequester(context, serverContext.getWebServer()); + TestProtocol rsocketResponse = requester.route("websocket").data(new TestProtocol("rsocket")) + .retrieveMono(TestProtocol.class).block(Duration.ofSeconds(3)); + assertThat(rsocketResponse.getName()).isEqualTo("rsocket"); + WebTestClient client = createWebTestClient(serverContext.getWebServer()); + client.get().uri("/protocol").exchange().expectStatus().isOk().expectBody().jsonPath("name", + "http"); + }); } private WebTestClient createWebTestClient(WebServer server) { - return WebTestClient.bindToServer() - .baseUrl("http://localhost:" + server.getPort()).build(); + return WebTestClient.bindToServer().baseUrl("http://localhost:" + server.getPort()).build(); } - private RSocketRequester createRSocketRequester(ApplicationContext context, - WebServer server) { + private RSocketRequester createRSocketRequester(ApplicationContext context, WebServer server) { int port = server.getPort(); - RSocketRequester.Builder builder = context - .getBean(RSocketRequester.Builder.class); - return builder.connectWebSocket(URI.create("ws://localhost:" + port + "/rsocket")) - .block(); + RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); + return builder.connectWebSocket(URI.create("ws://localhost:" + port + "/rsocket")).block(); } @Configuration(proxyBeanMethods = false) @@ -112,10 +98,8 @@ public class RSocketWebSocketNettyRouteProviderTests { } @Bean - public NettyReactiveWebServerFactory customServerFactory( - RSocketWebSocketNettyRouteProvider routeProvider) { - NettyReactiveWebServerFactory serverFactory = new NettyReactiveWebServerFactory( - 0); + public NettyReactiveWebServerFactory customServerFactory(RSocketWebSocketNettyRouteProvider routeProvider) { + NettyReactiveWebServerFactory serverFactory = new NettyReactiveWebServerFactory(0); serverFactory.addRouteProviders(routeProvider); return serverFactory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java index c1d50ac50c4..6b22408abfd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java @@ -37,8 +37,7 @@ import org.springframework.test.context.ContextConfiguration; * * @author Dave Syer */ -@ContextConfiguration(classes = JpaUserDetailsTests.Main.class, - loader = SpringBootContextLoader.class) +@ContextConfiguration(classes = JpaUserDetailsTests.Main.class, loader = SpringBootContextLoader.class) @DirtiesContext public class JpaUserDetailsTests { @@ -51,8 +50,8 @@ public class JpaUserDetailsTests { } @Import({ EmbeddedDataSourceConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, SecurityAutoConfiguration.class }) + HibernateJpaAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + SecurityAutoConfiguration.class }) public static class Main { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java index 26e4caa8391..ead7f3c5abf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java @@ -73,24 +73,22 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); - assertThat(adaptedProvider.getAuthorizationUri()) - .isEqualTo("https://example.com/auth"); + assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://example.com/auth"); assertThat(adaptedProvider.getTokenUri()).isEqualTo("https://example.com/token"); UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/info"); - assertThat(userInfoEndpoint.getAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.AuthenticationMethod.FORM); + assertThat(userInfoEndpoint.getAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.FORM); assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo("sub"); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://example.com/jwk"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); - assertThat(adapted.getClientAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.POST); - assertThat(adapted.getAuthorizationGrantType()).isEqualTo( - org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); - assertThat(adapted.getRedirectUriTemplate()) - .isEqualTo("https://example.com/redirect"); + assertThat(adapted.getClientAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.POST); + assertThat(adapted.getAuthorizationGrantType()) + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + assertThat(adapted.getRedirectUriTemplate()).isEqualTo("https://example.com/redirect"); assertThat(adapted.getScopes()).containsExactly("user"); assertThat(adapted.getClientName()).isEqualTo("clientName"); } @@ -107,26 +105,20 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); - assertThat(adaptedProvider.getAuthorizationUri()) - .isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); - assertThat(adaptedProvider.getTokenUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v4/token"); + assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); + assertThat(adaptedProvider.getTokenUri()).isEqualTo("https://www.googleapis.com/oauth2/v4/token"); UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); - assertThat(userInfoEndpoint.getUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); - assertThat(userInfoEndpoint.getUserNameAttributeName()) - .isEqualTo(IdTokenClaimNames.SUB); - assertThat(adaptedProvider.getJwkSetUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); + assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); + assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo(IdTokenClaimNames.SUB); + assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); - assertThat(adapted.getClientAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC); - assertThat(adapted.getAuthorizationGrantType()).isEqualTo( - org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); - assertThat(adapted.getRedirectUriTemplate()) - .isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); + assertThat(adapted.getClientAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC); + assertThat(adapted.getAuthorizationGrantType()) + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + assertThat(adapted.getRedirectUriTemplate()).isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); } @@ -141,28 +133,22 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); - assertThat(adaptedProvider.getAuthorizationUri()) - .isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); - assertThat(adaptedProvider.getTokenUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v4/token"); + assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); + assertThat(adaptedProvider.getTokenUri()).isEqualTo("https://www.googleapis.com/oauth2/v4/token"); UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); - assertThat(userInfoEndpoint.getUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); - assertThat(userInfoEndpoint.getUserNameAttributeName()) - .isEqualTo(IdTokenClaimNames.SUB); - assertThat(userInfoEndpoint.getAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); - assertThat(adaptedProvider.getJwkSetUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); + assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); + assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo(IdTokenClaimNames.SUB); + assertThat(userInfoEndpoint.getAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); - assertThat(adapted.getClientAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.POST); - assertThat(adapted.getAuthorizationGrantType()).isEqualTo( - org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); - assertThat(adapted.getRedirectUriTemplate()) - .isEqualTo("https://example.com/redirect"); + assertThat(adapted.getClientAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.POST); + assertThat(adapted.getAuthorizationGrantType()) + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + assertThat(adapted.getRedirectUriTemplate()).isEqualTo("https://example.com/redirect"); assertThat(adapted.getScopes()).containsExactly("user"); assertThat(adapted.getClientName()).isEqualTo("clientName"); } @@ -174,8 +160,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setProvider("missing"); properties.getRegistration().put("registration", registration); assertThatIllegalStateException() - .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties)) + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) .withMessageContaining("Unknown provider ID 'missing'"); } @@ -190,26 +175,21 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("google"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); - assertThat(adaptedProvider.getAuthorizationUri()) - .isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); - assertThat(adaptedProvider.getTokenUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v4/token"); + assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); + assertThat(adaptedProvider.getTokenUri()).isEqualTo("https://www.googleapis.com/oauth2/v4/token"); UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); - assertThat(userInfoEndpoint.getUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); - assertThat(userInfoEndpoint.getAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); - assertThat(adaptedProvider.getJwkSetUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); + assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); + assertThat(userInfoEndpoint.getAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("google"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); - assertThat(adapted.getClientAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC); - assertThat(adapted.getAuthorizationGrantType()).isEqualTo( - org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); - assertThat(adapted.getRedirectUriTemplate()) - .isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); + assertThat(adapted.getClientAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC); + assertThat(adapted.getAuthorizationGrantType()) + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + assertThat(adapted.getRedirectUriTemplate()).isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); } @@ -220,15 +200,12 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); properties.getRegistration().put("missing", registration); assertThatIllegalStateException() - .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties)) - .withMessageContaining( - "Provider ID must be specified for client registration 'missing'"); + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) + .withMessageContaining("Provider ID must be specified for client registration 'missing'"); } @Test - public void oidcProviderConfigurationWhenProviderNotSpecifiedOnRegistration() - throws Exception { + public void oidcProviderConfigurationWhenProviderNotSpecifiedOnRegistration() throws Exception { Registration login = new OAuth2ClientProperties.Registration(); login.setClientId("clientId"); login.setClientSecret("clientSecret"); @@ -236,8 +213,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void oidcProviderConfigurationWhenProviderSpecifiedOnRegistration() - throws Exception { + public void oidcProviderConfigurationWhenProviderSpecifiedOnRegistration() throws Exception { OAuth2ClientProperties.Registration login = new Registration(); login.setProvider("okta-oidc"); login.setClientId("clientId"); @@ -246,14 +222,12 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void oidcProviderConfigurationWithCustomConfigurationOverridesProviderDefaults() - throws Exception { + public void oidcProviderConfigurationWithCustomConfigurationOverridesProviderDefaults() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); setupMockResponse(issuer); - OAuth2ClientProperties.Registration registration = createRegistration( - "okta-oidc"); + OAuth2ClientProperties.Registration registration = createRegistration("okta-oidc"); Provider provider = createProvider(); provider.setIssuerUri(issuer); OAuth2ClientProperties properties = new OAuth2ClientProperties(); @@ -263,17 +237,13 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("okta"); ProviderDetails providerDetails = adapted.getProviderDetails(); - assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(ClientAuthenticationMethod.POST); - assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); + assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.POST); + assertThat(adapted.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRegistrationId()).isEqualTo("okta"); assertThat(adapted.getClientName()).isEqualTo(issuer); assertThat(adapted.getScopes()).containsOnly("user"); - assertThat(adapted.getRedirectUriTemplate()) - .isEqualTo("https://example.com/redirect"); - assertThat(providerDetails.getAuthorizationUri()) - .isEqualTo("https://example.com/auth"); + assertThat(adapted.getRedirectUriTemplate()).isEqualTo("https://example.com/redirect"); + assertThat(providerDetails.getAuthorizationUri()).isEqualTo("https://example.com/auth"); assertThat(providerDetails.getTokenUri()).isEqualTo("https://example.com/token"); assertThat(providerDetails.getJwkSetUri()).isEqualTo("https://example.com/jwk"); UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint(); @@ -303,8 +273,8 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { return registration; } - private void testOidcConfiguration(OAuth2ClientProperties.Registration registration, - String providerId) throws Exception { + private void testOidcConfiguration(OAuth2ClientProperties.Registration registration, String providerId) + throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -318,29 +288,22 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("okta"); ProviderDetails providerDetails = adapted.getProviderDetails(); - assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(ClientAuthenticationMethod.BASIC); - assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); + assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.BASIC); + assertThat(adapted.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRegistrationId()).isEqualTo("okta"); assertThat(adapted.getClientName()).isEqualTo(issuer); assertThat(adapted.getScopes()).containsOnly("openid"); - assertThat(providerDetails.getAuthorizationUri()) - .isEqualTo("https://example.com/o/oauth2/v2/auth"); - assertThat(providerDetails.getTokenUri()) - .isEqualTo("https://example.com/oauth2/v4/token"); - assertThat(providerDetails.getJwkSetUri()) - .isEqualTo("https://example.com/oauth2/v3/certs"); + assertThat(providerDetails.getAuthorizationUri()).isEqualTo("https://example.com/o/oauth2/v2/auth"); + assertThat(providerDetails.getTokenUri()).isEqualTo("https://example.com/oauth2/v4/token"); + assertThat(providerDetails.getJwkSetUri()).isEqualTo("https://example.com/oauth2/v3/certs"); UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint(); - assertThat(userInfoEndpoint.getUri()) - .isEqualTo("https://example.com/oauth2/v3/userinfo"); - assertThat(userInfoEndpoint.getAuthenticationMethod()).isEqualTo( - org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/oauth2/v3/userinfo"); + assertThat(userInfoEndpoint.getAuthenticationMethod()) + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); } private void setupMockResponse(String issuer) throws JsonProcessingException { - MockResponse mockResponse = new MockResponse() - .setResponseCode(HttpStatus.OK.value()) + MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); @@ -358,11 +321,9 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { response.put("revocation_endpoint", "https://example.com/o/oauth2/revoke"); response.put("scopes_supported", Collections.singletonList("openid")); response.put("subject_types_supported", Collections.singletonList("public")); - response.put("grant_types_supported", - Collections.singletonList("authorization_code")); + response.put("grant_types_supported", Collections.singletonList("authorization_code")); response.put("token_endpoint", "https://example.com/oauth2/v4/token"); - response.put("token_endpoint_auth_methods_supported", - Collections.singletonList("client_secret_basic")); + response.put("token_endpoint_auth_methods_supported", Collections.singletonList("client_secret_basic")); response.put("userinfo_endpoint", "https://example.com/oauth2/v3/userinfo"); return response; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java index cd943cd579b..a86f8e3f765 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java @@ -50,35 +50,32 @@ import static org.assertj.core.api.Assertions.assertThat; public class ReactiveOAuth2ClientAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)); private static final String REGISTRATION_PREFIX = "spring.security.oauth2.client.registration"; @Test public void autoConfigurationShouldBackOffForServletEnvironments() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(ReactiveOAuth2ClientAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @Test public void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ClientRegistrationRepository.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); } @Test public void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { - this.contextRunner.withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", - REGISTRATION_PREFIX + ".foo.provider=github").run((context) -> { + this.contextRunner + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> { ReactiveClientRegistrationRepository repository = context .getBean(ReactiveClientRegistrationRepository.class); - ClientRegistration registration = repository - .findByRegistrationId("foo").block(Duration.ofSeconds(30)); + ClientRegistration registration = repository.findByRegistrationId("foo") + .block(Duration.ofSeconds(30)); assertThat(registration).isNotNull(); assertThat(registration.getClientSecret()).isEqualTo("secret"); }); @@ -86,53 +83,43 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { @Test public void authorizedClientServiceBeanIsConditionalOnClientRegistrationRepository() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveOAuth2AuthorizedClientService.class)); + this.contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2AuthorizedClientService.class)); } @Test public void configurationRegistersAuthorizedClientServiceBean() { - this.contextRunner - .withUserConfiguration(ReactiveClientRepositoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean( - InMemoryReactiveClientRegistrationRepository.class)); + this.contextRunner.withUserConfiguration(ReactiveClientRepositoryConfiguration.class).run( + (context) -> assertThat(context).hasSingleBean(InMemoryReactiveClientRegistrationRepository.class)); } @Test public void authorizedClientServiceBeanIsConditionalOnMissingBean() { - this.contextRunner - .withUserConfiguration( - ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) + this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) .run((context) -> { - assertThat(context) - .hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); + assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); assertThat(context).hasBean("testAuthorizedClientService"); }); } @Test public void authorizedClientRepositoryBeanIsConditionalOnAuthorizedClientService() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); + this.contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); } @Test public void configurationRegistersAuthorizedClientRepositoryBean() { - this.contextRunner - .withUserConfiguration( - ReactiveOAuth2AuthorizedClientServiceConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean( - AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); + this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class) + .run((context) -> assertThat(context) + .hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); } @Test public void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { - this.contextRunner - .withUserConfiguration( - ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) + this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) .run((context) -> { - assertThat(context) - .hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); + assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); assertThat(context).hasBean("testAuthorizedClientRepository"); }); } @@ -156,10 +143,8 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { FilteredClassLoader classLoader = new FilteredClassLoader(classToFilter); this.contextRunner.withClassLoader(classLoader) .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", - REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @Configuration(proxyBeanMethods = false) @@ -168,23 +153,20 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { @Bean public ReactiveClientRegistrationRepository clientRegistrationRepository() { List registrations = new ArrayList<>(); - registrations - .add(getClientRegistration("first", "https://user-info-uri.com")); + registrations.add(getClientRegistration("first", "https://user-info-uri.com")); registrations.add(getClientRegistration("second", "https://other-user-info")); return new InMemoryReactiveClientRegistrationRepository(registrations); } private ClientRegistration getClientRegistration(String id, String userInfoUri) { - ClientRegistration.Builder builder = ClientRegistration - .withRegistrationId(id); - builder.clientName("foo").clientId("foo").clientAuthenticationMethod( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .scope("read").clientSecret("secret") - .redirectUriTemplate("https://redirect-uri.com") - .authorizationUri("https://authorization-uri.com") - .tokenUri("https://token-uri.com").userInfoUri(userInfoUri) - .userNameAttributeName("login"); + ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id); + builder.clientName("foo").clientId("foo") + .clientAuthenticationMethod( + org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read") + .clientSecret("secret").redirectUriTemplate("https://redirect-uri.com") + .authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com") + .userInfoUri(userInfoUri).userNameAttributeName("login"); return builder.build(); } @@ -197,8 +179,7 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { @Bean public ReactiveOAuth2AuthorizedClientService testAuthorizedClientService( ReactiveClientRegistrationRepository clientRegistrationRepository) { - return new InMemoryReactiveOAuth2AuthorizedClientService( - clientRegistrationRepository); + return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); } } @@ -210,8 +191,7 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { @Bean public ServerOAuth2AuthorizedClientRepository testAuthorizedClientRepository( ReactiveOAuth2AuthorizedClientService authorizedClientService) { - return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository( - authorizedClientService); + return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java index 66210e14d39..867a5241f47 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java @@ -37,26 +37,18 @@ public class OAuth2ClientRegistrationRepositoryConfigurationTests { @Test public void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { - this.contextRunner - .withUserConfiguration( - OAuth2ClientRegistrationRepositoryConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(ClientRegistrationRepository.class)); + this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); } @Test public void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { - this.contextRunner - .withUserConfiguration( - OAuth2ClientRegistrationRepositoryConfiguration.class) + this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", - REGISTRATION_PREFIX + ".foo.provider=github") + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") .run((context) -> { - ClientRegistrationRepository repository = context - .getBean(ClientRegistrationRepository.class); - ClientRegistration registration = repository - .findByRegistrationId("foo"); + ClientRegistrationRepository repository = context.getBean(ClientRegistrationRepository.class); + ClientRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration).isNotNull(); assertThat(registration.getClientSecret()).isEqualTo("secret"); }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java index 06198924f05..24c06cfb9bd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java @@ -61,52 +61,40 @@ public class OAuth2WebSecurityConfigurationTests { @Test public void securityConfigurerConfiguresOAuth2Login() { - this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> { - ClientRegistrationRepository expected = context - .getBean(ClientRegistrationRepository.class); - ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils - .getField( - getFilters(context, - OAuth2LoginAuthenticationFilter.class).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), - actual.findByRegistrationId("first"))).isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), - actual.findByRegistrationId("second"))).isTrue(); + this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class).run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); + ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( + getFilters(context, OAuth2LoginAuthenticationFilter.class).get(0), + "clientRegistrationRepository"); + assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) + .isTrue(); + assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) + .isTrue(); }); } @Test public void securityConfigurerConfiguresAuthorizationCode() { - this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> { - ClientRegistrationRepository expected = context - .getBean(ClientRegistrationRepository.class); - ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils - .getField(getFilters(context, - OAuth2AuthorizationCodeGrantFilter.class).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), - actual.findByRegistrationId("first"))).isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), - actual.findByRegistrationId("second"))).isTrue(); + this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class).run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); + ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( + getFilters(context, OAuth2AuthorizationCodeGrantFilter.class).get(0), + "clientRegistrationRepository"); + assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) + .isTrue(); + assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) + .isTrue(); }); } @Test public void securityConfigurerBacksOffWhenClientRegistrationBeanAbsent() { - this.contextRunner.withUserConfiguration(TestConfig.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)) - .isEmpty(); - assertThat( - getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)) - .isEmpty(); + this.contextRunner.withUserConfiguration(TestConfig.class, OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); }); } @@ -115,8 +103,7 @@ public class OAuth2WebSecurityConfigurationTests { this.contextRunner .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(OAuth2AuthorizedClientService.class)); + .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class)); } @Test @@ -124,79 +111,60 @@ public class OAuth2WebSecurityConfigurationTests { this.contextRunner .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(OAuth2AuthorizedClientRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class)); } @Test public void securityConfigurerBacksOffWhenOtherWebSecurityAdapterPresent() { - this.contextRunner.withUserConfiguration(TestWebSecurityConfigurerConfig.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)) - .isEmpty(); - assertThat( - getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)) - .isEmpty(); - assertThat(context).getBean(OAuth2AuthorizedClientService.class) - .isNotNull(); + this.contextRunner + .withUserConfiguration(TestWebSecurityConfigurerConfig.class, OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); }); } @Test public void authorizedClientServiceBeanIsConditionalOnMissingBean() { - this.contextRunner - .withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> { - assertThat(context) - .hasSingleBean(OAuth2AuthorizedClientService.class); + this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, + OAuth2WebSecurityConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class); assertThat(context).hasBean("testAuthorizedClientService"); }); } @Test public void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { - this.contextRunner.withUserConfiguration( - OAuth2AuthorizedClientRepositoryConfiguration.class, + this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(context) - .hasSingleBean(OAuth2AuthorizedClientRepository.class); + assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); assertThat(context).hasBean("testAuthorizedClientRepository"); }); } - private List getFilters(AssertableApplicationContext context, - Class filter) { - FilterChainProxy filterChain = (FilterChainProxy) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + private List getFilters(AssertableApplicationContext context, Class filter) { + FilterChainProxy filterChain = (FilterChainProxy) context.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); List filterChains = filterChain.getFilterChains(); List filters = filterChains.get(0).getFilters(); return filters.stream().filter(filter::isInstance).collect(Collectors.toList()); } private boolean isEqual(ClientRegistration reg1, ClientRegistration reg2) { - boolean result = ObjectUtils.nullSafeEquals(reg1.getClientId(), - reg2.getClientId()); - result = result - && ObjectUtils.nullSafeEquals(reg1.getClientName(), reg2.getClientName()); - result = result && ObjectUtils.nullSafeEquals(reg1.getClientSecret(), - reg2.getClientSecret()); + boolean result = ObjectUtils.nullSafeEquals(reg1.getClientId(), reg2.getClientId()); + result = result && ObjectUtils.nullSafeEquals(reg1.getClientName(), reg2.getClientName()); + result = result && ObjectUtils.nullSafeEquals(reg1.getClientSecret(), reg2.getClientSecret()); result = result && ObjectUtils.nullSafeEquals(reg1.getScopes(), reg2.getScopes()); - result = result && ObjectUtils.nullSafeEquals(reg1.getRedirectUriTemplate(), - reg2.getRedirectUriTemplate()); - result = result && ObjectUtils.nullSafeEquals(reg1.getRegistrationId(), - reg2.getRegistrationId()); - result = result && ObjectUtils.nullSafeEquals(reg1.getAuthorizationGrantType(), - reg2.getAuthorizationGrantType()); - result = result && ObjectUtils.nullSafeEquals( - reg1.getProviderDetails().getAuthorizationUri(), - reg2.getProviderDetails().getAuthorizationUri()); - result = result && ObjectUtils.nullSafeEquals( - reg1.getProviderDetails().getUserInfoEndpoint(), - reg2.getProviderDetails().getUserInfoEndpoint()); + result = result && ObjectUtils.nullSafeEquals(reg1.getRedirectUriTemplate(), reg2.getRedirectUriTemplate()); + result = result && ObjectUtils.nullSafeEquals(reg1.getRegistrationId(), reg2.getRegistrationId()); result = result - && ObjectUtils.nullSafeEquals(reg1.getProviderDetails().getTokenUri(), - reg2.getProviderDetails().getTokenUri()); + && ObjectUtils.nullSafeEquals(reg1.getAuthorizationGrantType(), reg2.getAuthorizationGrantType()); + result = result && ObjectUtils.nullSafeEquals(reg1.getProviderDetails().getAuthorizationUri(), + reg2.getProviderDetails().getAuthorizationUri()); + result = result && ObjectUtils.nullSafeEquals(reg1.getProviderDetails().getUserInfoEndpoint(), + reg2.getProviderDetails().getUserInfoEndpoint()); + result = result && ObjectUtils.nullSafeEquals(reg1.getProviderDetails().getTokenUri(), + reg2.getProviderDetails().getTokenUri()); return result; } @@ -218,23 +186,20 @@ public class OAuth2WebSecurityConfigurationTests { @Bean public ClientRegistrationRepository clientRegistrationRepository() { List registrations = new ArrayList<>(); - registrations - .add(getClientRegistration("first", "https://user-info-uri.com")); + registrations.add(getClientRegistration("first", "https://user-info-uri.com")); registrations.add(getClientRegistration("second", "https://other-user-info")); return new InMemoryClientRegistrationRepository(registrations); } private ClientRegistration getClientRegistration(String id, String userInfoUri) { - ClientRegistration.Builder builder = ClientRegistration - .withRegistrationId(id); - builder.clientName("foo").clientId("foo").clientAuthenticationMethod( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .scope("read").clientSecret("secret") - .redirectUriTemplate("https://redirect-uri.com") - .authorizationUri("https://authorization-uri.com") - .tokenUri("https://token-uri.com").userInfoUri(userInfoUri) - .userNameAttributeName("login"); + ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id); + builder.clientName("foo").clientId("foo") + .clientAuthenticationMethod( + org.springframework.security.oauth2.core.ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read") + .clientSecret("secret").redirectUriTemplate("https://redirect-uri.com") + .authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com") + .userInfoUri(userInfoUri).userNameAttributeName("login"); return builder.build(); } @@ -253,8 +218,7 @@ public class OAuth2WebSecurityConfigurationTests { @Bean public OAuth2AuthorizedClientService testAuthorizedClientService( ClientRegistrationRepository clientRegistrationRepository) { - return new InMemoryOAuth2AuthorizedClientService( - clientRegistrationRepository); + return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); } } @@ -266,8 +230,7 @@ public class OAuth2WebSecurityConfigurationTests { @Bean public OAuth2AuthorizedClientRepository testAuthorizedClientRepository( OAuth2AuthorizedClientService authorizedClientService) { - return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository( - authorizedClientService); + return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java index 6ea97182bc3..a373612f1f1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java @@ -64,8 +64,7 @@ import static org.mockito.Mockito.mock; public class ReactiveOAuth2ResourceServerAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) .withUserConfiguration(TestConfig.class); private MockWebServer server; @@ -79,8 +78,8 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldConfigureResourceServer() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); assertFilterConfiguredWithJwtAuthenticationManager(context); @@ -88,18 +87,14 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() - throws IOException { + public void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws IOException { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort()) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort()).run((context) -> { assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); assertFilterConfiguredWithJwtAuthenticationManager(context); }); @@ -107,8 +102,9 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") .run((context) -> { assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); assertFilterConfiguredWithJwtAuthenticationManager(context); @@ -117,8 +113,9 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") .run((context) -> assertThat(context).hasFailed().getFailure() .hasMessageContaining("class path resource [does-not-exist]") .hasMessageContaining("Public key location does not exist")); @@ -126,10 +123,10 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationWhenSetUriKeyLocationIssuerUriPresentShouldUseSetUri() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") .run((context) -> { assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); assertFilterConfiguredWithJwtAuthenticationManager(context); @@ -139,17 +136,17 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() - throws Exception { + public void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort(), - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort(), + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") .run((context) -> { assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); assertFilterConfiguredWithJwtAuthenticationManager(context); @@ -159,70 +156,63 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationWhenJwkSetUriNullShouldNotFail() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test public void jwtDecoderBeanIsConditionalOnMissingBean() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); } @Test public void jwtDecoderByIssuerUriBeanIsConditionalOnMissingBean() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") .withUserConfiguration(JwtDecoderConfig.class) .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); } @Test public void autoConfigurationShouldBeConditionalOnBearerTokenAuthenticationTokenClass() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader( - new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) + .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test public void autoConfigurationShouldBeConditionalOnReactiveJwtDecoderClass() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .withClassLoader(new FilteredClassLoader(ReactiveJwtDecoder.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test public void autoConfigurationWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(SecurityWebFilterChainConfig.class) - .run((context) -> { + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(SecurityWebFilterChainConfig.class).run((context) -> { assertThat(context).hasSingleBean(SecurityWebFilterChain.class); assertThat(context).hasBean("testSpringSecurityFilterChain"); }); } - private void assertFilterConfiguredWithJwtAuthenticationManager( - AssertableReactiveWebApplicationContext context) { + private void assertFilterConfiguredWithJwtAuthenticationManager(AssertableReactiveWebApplicationContext context) { MatcherSecurityWebFilterChain filterChain = (MatcherSecurityWebFilterChain) context .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); Stream filters = filterChain.getWebFilters().toStream(); AuthenticationWebFilter webFilter = (AuthenticationWebFilter) filters - .filter((f) -> f instanceof AuthenticationWebFilter).findFirst() - .orElse(null); + .filter((f) -> f instanceof AuthenticationWebFilter).findFirst().orElse(null); ReactiveAuthenticationManager authenticationManager = (ReactiveAuthenticationManager) ReflectionTestUtils .getField(webFilter, "authenticationManager"); - assertThat(authenticationManager) - .isInstanceOf(JwtReactiveAuthenticationManager.class); + assertThat(authenticationManager).isInstanceOf(JwtReactiveAuthenticationManager.class); } @@ -234,8 +224,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } private void setupMockResponse(String issuer) throws JsonProcessingException { - MockResponse mockResponse = new MockResponse() - .setResponseCode(HttpStatus.OK.value()) + MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); @@ -253,11 +242,9 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { response.put("revocation_endpoint", "https://example.com/o/oauth2/revoke"); response.put("scopes_supported", Collections.singletonList("openid")); response.put("subject_types_supported", Collections.singletonList("public")); - response.put("grant_types_supported", - Collections.singletonList("authorization_code")); + response.put("grant_types_supported", Collections.singletonList("authorization_code")); response.put("token_endpoint", "https://example.com/oauth2/v4/token"); - response.put("token_endpoint_auth_methods_supported", - Collections.singletonList("client_secret_basic")); + response.put("token_endpoint_auth_methods_supported", Collections.singletonList("client_secret_basic")); response.put("userinfo_endpoint", "https://example.com/oauth2/v3/userinfo"); return response; } @@ -286,11 +273,9 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { static class SecurityWebFilterChainConfig { @Bean - SecurityWebFilterChain testSpringSecurityFilterChain(ServerHttpSecurity http, - ReactiveJwtDecoder decoder) { - http.authorizeExchange().pathMatchers("/message/**").hasRole("ADMIN") - .anyExchange().authenticated().and().oauth2ResourceServer().jwt() - .jwtDecoder(decoder); + SecurityWebFilterChain testSpringSecurityFilterChain(ServerHttpSecurity http, ReactiveJwtDecoder decoder) { + http.authorizeExchange().pathMatchers("/message/**").hasRole("ADMIN").anyExchange().authenticated().and() + .oauth2ResourceServer().jwt().jwtDecoder(decoder); return http.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java index fd7e267efdd..ca1baf23b11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java @@ -60,8 +60,7 @@ import static org.mockito.Mockito.mock; public class OAuth2ResourceServerAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) .withUserConfiguration(TestConfig.class); private MockWebServer server; @@ -75,8 +74,8 @@ public class OAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldConfigureResourceServer() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); @@ -85,39 +84,46 @@ public class OAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldMatchDefaultJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - Object processor = ReflectionTestUtils.getField(jwtDecoder, - "jwtProcessor"); - Object keySelector = ReflectionTestUtils.getField(processor, - "jwsKeySelector"); - assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlg", - JWSAlgorithm.RS256); + Object processor = ReflectionTestUtils.getField(jwtDecoder, "jwtProcessor"); + Object keySelector = ReflectionTestUtils.getField(processor, "jwsKeySelector"); + assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlg", JWSAlgorithm.RS256); }); } @Test public void autoConfigurationShouldConfigureResourceServerWithJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") .run((context) -> { JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - Object processor = ReflectionTestUtils.getField(jwtDecoder, - "jwtProcessor"); - Object keySelector = ReflectionTestUtils.getField(processor, - "jwsKeySelector"); - assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlg", - JWSAlgorithm.RS384); + Object processor = ReflectionTestUtils.getField(jwtDecoder, "jwtProcessor"); + Object keySelector = ReflectionTestUtils.getField(processor, "jwsKeySelector"); + assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlg", JWSAlgorithm.RS384); assertThat(getBearerTokenFilter(context)).isNotNull(); }); } @Test - public void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() - throws Exception { + public void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws Exception { + this.server = new MockWebServer(); + this.server.start(); + String issuer = this.server.url("").toString(); + String cleanIssuerPath = cleanIssuerPath(issuer); + setupMockResponse(cleanIssuerPath); + this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort()).run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); + } + + @Test + public void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -125,24 +131,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { setupMockResponse(cleanIssuerPath); this.contextRunner .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort()) - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); - } - - @Test - public void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() - throws Exception { - this.server = new MockWebServer(); - this.server.start(); - String issuer = this.server.url("").toString(); - String cleanIssuerPath = cleanIssuerPath(issuer); - setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); @@ -151,8 +140,9 @@ public class OAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") .run((context) -> assertThat(context).hasFailed().getFailure() .hasMessageContaining("class path resource [does-not-exist]") .hasMessageContaining("Public key location does not exist")); @@ -160,10 +150,10 @@ public class OAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationWhenSetUriKeyLocationAndIssuerUriPresentShouldUseSetUri() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); @@ -173,17 +163,17 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() - throws Exception { + public void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort(), - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort(), + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); @@ -193,30 +183,30 @@ public class OAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationWhenJwkSetUriNullShouldNotFail() { - this.contextRunner - .run((context) -> assertThat(getBearerTokenFilter(context)).isNull()); + this.contextRunner.run((context) -> assertThat(getBearerTokenFilter(context)).isNull()); } @Test public void jwtDecoderByJwkSetUriIsConditionalOnMissingBean() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test public void jwtDecoderByOidcIssuerUriIsConditionalOnMissingBean() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") .withUserConfiguration(JwtDecoderConfig.class) .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test public void autoConfigurationShouldBeConditionalOnJwtAuthenticationTokenClass() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .withClassLoader(new FilteredClassLoader(JwtAuthenticationToken.class)) .run((context) -> assertThat(getBearerTokenFilter(context)).isNull()); @@ -224,21 +214,18 @@ public class OAuth2ResourceServerAutoConfigurationTests { @Test public void autoConfigurationShouldBeConditionalOnJwtDecoderClass() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .withClassLoader(new FilteredClassLoader(JwtDecoder.class)) .run((context) -> assertThat(getBearerTokenFilter(context)).isNull()); } private Filter getBearerTokenFilter(AssertableWebApplicationContext context) { - FilterChainProxy filterChain = (FilterChainProxy) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + FilterChainProxy filterChain = (FilterChainProxy) context.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); List filterChains = filterChain.getFilterChains(); List filters = filterChains.get(0).getFilters(); - return filters.stream() - .filter((f) -> f instanceof BearerTokenAuthenticationFilter).findFirst() - .orElse(null); + return filters.stream().filter((f) -> f instanceof BearerTokenAuthenticationFilter).findFirst().orElse(null); } private String cleanIssuerPath(String issuer) { @@ -249,8 +236,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } private void setupMockResponse(String issuer) throws JsonProcessingException { - MockResponse mockResponse = new MockResponse() - .setResponseCode(HttpStatus.OK.value()) + MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); @@ -268,11 +254,9 @@ public class OAuth2ResourceServerAutoConfigurationTests { response.put("revocation_endpoint", "https://example.com/o/oauth2/revoke"); response.put("scopes_supported", Collections.singletonList("openid")); response.put("subject_types_supported", Collections.singletonList("public")); - response.put("grant_types_supported", - Collections.singletonList("authorization_code")); + response.put("grant_types_supported", Collections.singletonList("authorization_code")); response.put("token_endpoint", "https://example.com/oauth2/v4/token"); - response.put("token_endpoint_auth_methods_supported", - Collections.singletonList("client_secret_basic")); + response.put("token_endpoint_auth_methods_supported", Collections.singletonList("client_secret_basic")); response.put("userinfo_endpoint", "https://example.com/oauth2/v3/userinfo"); return response; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java index a90dae9db2a..9ba113965c8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java @@ -29,8 +29,7 @@ public class PathRequestTests { @Test public void toStaticResourcesShouldReturnStaticResourceRequest() { - assertThat(PathRequest.toStaticResources()) - .isInstanceOf(StaticResourceRequest.class); + assertThat(PathRequest.toStaticResources()).isInstanceOf(StaticResourceRequest.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java index ba2beaee57f..381948a130b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java @@ -38,22 +38,17 @@ public class ReactiveSecurityAutoConfigurationTests { @Test public void backsOffWhenWebFilterChainProxyBeanPresent() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) .withUserConfiguration(WebFilterChainProxyConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(WebFilterChainProxy.class)); + .run((context) -> assertThat(context).hasSingleBean(WebFilterChainProxy.class)); } @Test public void enablesWebFluxSecurity() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class)) - .run((context) -> assertThat(context).getBean(WebFilterChainProxy.class) - .isNotNull()); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(WebFilterChainProxy.class).isNotNull()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java index 3c6f016c37e..2ff2db5f8af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java @@ -46,57 +46,40 @@ import static org.mockito.Mockito.mock; public class ReactiveUserDetailsServiceAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(ReactiveUserDetailsServiceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class)); @Test public void configuresADefaultUser() { - this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class) - .run((context) -> { - ReactiveUserDetailsService userDetailsService = context - .getBean(ReactiveUserDetailsService.class); - assertThat(userDetailsService.findByUsername("user") - .block(Duration.ofSeconds(30))).isNotNull(); - }); + this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class).run((context) -> { + ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); + assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNotNull(); + }); } @Test public void doesNotConfigureDefaultUserIfUserDetailsServiceAvailable() { - this.contextRunner - .withUserConfiguration(UserConfig.class, TestSecurityConfiguration.class) - .run((context) -> { - ReactiveUserDetailsService userDetailsService = context - .getBean(ReactiveUserDetailsService.class); - assertThat(userDetailsService.findByUsername("user") - .block(Duration.ofSeconds(30))).isNull(); - assertThat(userDetailsService.findByUsername("foo") - .block(Duration.ofSeconds(30))).isNotNull(); - assertThat(userDetailsService.findByUsername("admin") - .block(Duration.ofSeconds(30))).isNotNull(); - }); + this.contextRunner.withUserConfiguration(UserConfig.class, TestSecurityConfiguration.class).run((context) -> { + ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); + assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNull(); + assertThat(userDetailsService.findByUsername("foo").block(Duration.ofSeconds(30))).isNotNull(); + assertThat(userDetailsService.findByUsername("admin").block(Duration.ofSeconds(30))).isNotNull(); + }); } @Test public void doesNotConfigureDefaultUserIfAuthenticationManagerAvailable() { - this.contextRunner - .withUserConfiguration(AuthenticationManagerConfig.class, - TestSecurityConfiguration.class) - .withConfiguration( - AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) - .run((context) -> assertThat(context) - .getBean(ReactiveUserDetailsService.class).isNull()); + this.contextRunner.withUserConfiguration(AuthenticationManagerConfig.class, TestSecurityConfiguration.class) + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(ReactiveUserDetailsService.class).isNull()); } @Test public void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { - this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class) - .run(((context) -> { - MapReactiveUserDetailsService userDetailsService = context - .getBean(MapReactiveUserDetailsService.class); - String password = userDetailsService.findByUsername("user") - .block(Duration.ofSeconds(30)).getPassword(); - assertThat(password).startsWith("{noop}"); - })); + this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class).run(((context) -> { + MapReactiveUserDetailsService userDetailsService = context.getBean(MapReactiveUserDetailsService.class); + String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)).getPassword(); + assertThat(password).startsWith("{noop}"); + })); } @Test @@ -115,15 +98,13 @@ public class ReactiveUserDetailsServiceAutoConfigurationTests { testPasswordEncoding(TestConfigWithPasswordEncoder.class, "secret", "secret"); } - private void testPasswordEncoding(Class configClass, String providedPassword, - String expectedPassword) { + private void testPasswordEncoding(Class configClass, String providedPassword, String expectedPassword) { this.contextRunner.withUserConfiguration(configClass) - .withPropertyValues("spring.security.user.password=" + providedPassword) - .run(((context) -> { + .withPropertyValues("spring.security.user.password=" + providedPassword).run(((context) -> { MapReactiveUserDetailsService userDetailsService = context .getBean(MapReactiveUserDetailsService.class); - String password = userDetailsService.findByUsername("user") - .block(Duration.ofSeconds(30)).getPassword(); + String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)) + .getPassword(); assertThat(password).isEqualTo(expectedPassword); })); } @@ -140,10 +121,8 @@ public class ReactiveUserDetailsServiceAutoConfigurationTests { @Bean public MapReactiveUserDetailsService userDetailsService() { - UserDetails foo = User.withUsername("foo").password("foo").roles("USER") - .build(); - UserDetails admin = User.withUsername("admin").password("admin") - .roles("USER", "ADMIN").build(); + UserDetails foo = User.withUsername("foo").password("foo").roles("USER").build(); + UserDetails admin = User.withUsername("admin").password("admin").roles("USER", "ADMIN").build(); return new MapReactiveUserDetailsService(foo, admin); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java index b2b90d952b2..199d8fb16ac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java @@ -68,24 +68,20 @@ public class StaticResourceRequestTests { @Test public void atLocationShouldMatchLocation() { - ServerWebExchangeMatcher matcher = this.resourceRequest - .at(StaticResourceLocation.CSS); + ServerWebExchangeMatcher matcher = this.resourceRequest.at(StaticResourceLocation.CSS); assertMatcher(matcher).matches("/css/file.css"); assertMatcher(matcher).doesNotMatch("/js/file.js"); } @Test public void atLocationsFromSetWhenSetIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.resourceRequest.at(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) .withMessageContaining("Locations must not be null"); } @Test public void excludeFromSetWhenSetIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.resourceRequest.atCommonLocations().excluding(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) .withMessageContaining("Locations must not be null"); } @@ -101,40 +97,35 @@ public class StaticResourceRequestTests { private final ServerWebExchangeMatcher matcher; - RequestMatcherAssert(StaticApplicationContext context, - ServerWebExchangeMatcher matcher) { + RequestMatcherAssert(StaticApplicationContext context, ServerWebExchangeMatcher matcher) { this.context = context; this.matcher = matcher; } void matches(String path) { - ServerWebExchange exchange = webHandler().createExchange( - MockServerHttpRequest.get(path).build(), + ServerWebExchange exchange = webHandler().createExchange(MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); matches(exchange); } private void matches(ServerWebExchange exchange) { - assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)) - .isMatch()).as("Matches " + getRequestPath(exchange)).isTrue(); + assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) + .as("Matches " + getRequestPath(exchange)).isTrue(); } void doesNotMatch(String path) { - ServerWebExchange exchange = webHandler().createExchange( - MockServerHttpRequest.get(path).build(), + ServerWebExchange exchange = webHandler().createExchange(MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); doesNotMatch(exchange); } private void doesNotMatch(ServerWebExchange exchange) { - assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)) - .isMatch()).as("Does not match " + getRequestPath(exchange)) - .isFalse(); + assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) + .as("Does not match " + getRequestPath(exchange)).isFalse(); } private TestHttpWebHandlerAdapter webHandler() { - TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter( - mock(WebHandler.class)); + TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(mock(WebHandler.class)); adapter.setApplicationContext(this.context); return adapter; } @@ -152,8 +143,7 @@ public class StaticResourceRequestTests { } @Override - protected ServerWebExchange createExchange(ServerHttpRequest request, - ServerHttpResponse response) { + protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { return super.createExchange(request, response); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java index d3ea300fdcd..a3ffae78632 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java @@ -40,8 +40,7 @@ public class PathRequestTests { @Test public void toStaticResourcesShouldReturnStaticResourceRequest() { - assertThat(PathRequest.toStaticResources()) - .isInstanceOf(StaticResourceRequest.class); + assertThat(PathRequest.toStaticResources()).isInstanceOf(StaticResourceRequest.class); } @Test @@ -75,8 +74,7 @@ public class PathRequestTests { } private void matches(HttpServletRequest request) { - assertThat(this.matcher.matches(request)) - .as("Matches " + getRequestPath(request)).isTrue(); + assertThat(this.matcher.matches(request)).as("Matches " + getRequestPath(request)).isTrue(); } public void doesNotMatch(String path) { @@ -84,15 +82,12 @@ public class PathRequestTests { } private void doesNotMatch(HttpServletRequest request) { - assertThat(this.matcher.matches(request)) - .as("Does not match " + getRequestPath(request)).isFalse(); + assertThat(this.matcher.matches(request)).as("Does not match " + getRequestPath(request)).isFalse(); } private MockHttpServletRequest mockRequest(String path) { MockServletContext servletContext = new MockServletContext(); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setPathInfo(path); return request; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java index 5652e4cce98..8b8903fbba9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java @@ -58,80 +58,63 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SecurityAutoConfigurationTests { - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)); + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( + AutoConfigurations.of(SecurityAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test public void testWebConfiguration() { this.contextRunner.run((context) -> { assertThat(context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); - assertThat(context.getBean(FilterChainProxy.class).getFilterChains()) - .hasSize(1); + assertThat(context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(1); }); } @Test public void testDefaultFilterOrderWithSecurityAdapter() { this.contextRunner - .withConfiguration(AutoConfigurations.of(WebSecurity.class, - SecurityFilterAutoConfiguration.class)) - .run((context) -> assertThat(context - .getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo( - OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); + .withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test public void testFilterIsNotRegisteredInNonWeb() { try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext()) { - customContext.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, + customContext.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); customContext.refresh(); - assertThat(customContext.containsBean("securityFilterChainRegistration")) - .isFalse(); + assertThat(customContext.containsBean("securityFilterChainRegistration")).isFalse(); } } @Test public void defaultAuthenticationEventPublisherRegistered() { - this.contextRunner.run((context) -> assertThat( - context.getBean(AuthenticationEventPublisher.class)) - .isInstanceOf(DefaultAuthenticationEventPublisher.class)); + this.contextRunner.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) + .isInstanceOf(DefaultAuthenticationEventPublisher.class)); } @Test public void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() { - this.contextRunner - .withUserConfiguration(AuthenticationEventPublisherConfiguration.class) - .run((context) -> assertThat( - context.getBean(AuthenticationEventPublisher.class)).isInstanceOf( - AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); + this.contextRunner.withUserConfiguration(AuthenticationEventPublisherConfiguration.class) + .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)).isInstanceOf( + AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); } @Test public void testDefaultFilterOrder() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .run((context) -> assertThat(context - .getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo( - OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); + this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test public void testCustomFilterOrder() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .withPropertyValues("spring.security.filter.order:12345").run( - (context) -> assertThat(context - .getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class) + this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .withPropertyValues("spring.security.filter.order:12345") + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) .getOrder()).isEqualTo(12345)); } @@ -142,53 +125,42 @@ public class SecurityAutoConfigurationTests { "spring.datasource.initialization-mode:never") .withUserConfiguration(EntityConfiguration.class) .withConfiguration( - AutoConfigurations.of(HibernateJpaAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)) - .isNotNull()); + AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull()); // This can fail if security @Conditionals force early instantiation of the // HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found) } @Test public void testSecurityEvaluationContextExtensionSupport() { - this.contextRunner.run((context) -> assertThat(context) - .getBean(SecurityEvaluationContextExtension.class).isNotNull()); + this.contextRunner + .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); } @Test public void defaultFilterDispatcherTypes() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean( - "securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); @SuppressWarnings("unchecked") EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils .getField(bean, "dispatcherTypes"); - assertThat(dispatcherTypes).containsOnly(DispatcherType.ASYNC, - DispatcherType.ERROR, DispatcherType.REQUEST); + assertThat(dispatcherTypes).containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, + DispatcherType.REQUEST); }); } @Test public void customFilterDispatcherTypes() { - this.contextRunner - .withPropertyValues( - "spring.security.filter.dispatcher-types:INCLUDE,ERROR") - .withConfiguration( - AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean( - "securityFilterChainRegistration", + this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:INCLUDE,ERROR") + .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); @SuppressWarnings("unchecked") EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils .getField(bean, "dispatcherTypes"); - assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE, - DispatcherType.ERROR); + assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); }); } @@ -214,8 +186,7 @@ public class SecurityAutoConfigurationTests { } @Override - public void publishAuthenticationFailure(AuthenticationException exception, - Authentication authentication) { + public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java index fc1d936367b..4cb70055246 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java @@ -55,32 +55,26 @@ import org.springframework.web.bind.annotation.RestController; public class SecurityFilterAutoConfigurationEarlyInitializationTests { @Test - public void testSecurityFilterDoesNotCauseEarlyInitialization( - CapturedOutput capturedOutput) { + public void testSecurityFilterDoesNotCauseEarlyInitialization(CapturedOutput capturedOutput) { try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) { TestPropertyValues.of("server.port:0").applyTo(context); context.register(Config.class); context.refresh(); int port = context.getWebServer().getPort(); - String password = capturedOutput.toString() - .split("Using generated security password: ")[1].split("\n")[0] - .trim(); - new TestRestTemplate("user", password) - .getForEntity("http://localhost:" + port, Object.class); + String password = capturedOutput.toString().split("Using generated security password: ")[1].split("\n")[0] + .trim(); + new TestRestTemplate("user", password).getForEntity("http://localhost:" + port, Object.class); // If early initialization occurred a ConverterNotFoundException is thrown } } @Configuration(proxyBeanMethods = false) - @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, - ConverterBean.class }) - @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, SecurityAutoConfiguration.class, - UserDetailsServiceAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, ConverterBean.class }) + @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + SecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class, + SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class Config { @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java index 64c36f0cf32..69615849188 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java @@ -51,13 +51,10 @@ public class SecurityFilterAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, - ConverterBean.class }) - @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebSecurity.class, - SecurityFilterAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, ConverterBean.class }) + @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebSecurity.class, + SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class Config { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java index 6a31f84b13a..644e5bbdb48 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java @@ -36,83 +36,62 @@ import static org.assertj.core.api.Assertions.assertThat; public class SecurityRequestMatcherProviderAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(SecurityRequestMatcherProviderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)); @Test public void configurationConditionalOnWebApplication() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(SecurityRequestMatcherProviderAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)) .withUserConfiguration(TestMvcConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(RequestMatcherProvider.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); } @Test public void configurationConditionalOnRequestMatcherClass() { this.contextRunner - .withClassLoader(new FilteredClassLoader( - "org.springframework.security.web.util.matcher.RequestMatcher")) - .run((context) -> assertThat(context) - .doesNotHaveBean(RequestMatcherProvider.class)); + .withClassLoader( + new FilteredClassLoader("org.springframework.security.web.util.matcher.RequestMatcher")) + .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); } @Test public void registersMvcRequestMatcherProviderIfMvcPresent() { - this.contextRunner.withUserConfiguration(TestMvcConfiguration.class) - .run((context) -> assertThat(context) - .getBean(RequestMatcherProvider.class) - .isInstanceOf(MvcRequestMatcherProvider.class)); + this.contextRunner.withUserConfiguration(TestMvcConfiguration.class).run((context) -> assertThat(context) + .getBean(RequestMatcherProvider.class).isInstanceOf(MvcRequestMatcherProvider.class)); } @Test public void registersRequestMatcherForJerseyProviderIfJerseyPresentAndMvcAbsent() { - this.contextRunner - .withClassLoader(new FilteredClassLoader( - "org.springframework.web.servlet.DispatcherServlet")) - .withUserConfiguration(TestJerseyConfiguration.class) - .run((context) -> assertThat(context) - .getBean(RequestMatcherProvider.class) - .isInstanceOf(JerseyRequestMatcherProvider.class)); + this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .withUserConfiguration(TestJerseyConfiguration.class).run((context) -> assertThat(context) + .getBean(RequestMatcherProvider.class).isInstanceOf(JerseyRequestMatcherProvider.class)); } @Test public void mvcRequestMatcherProviderConditionalOnDispatcherServletClass() { - this.contextRunner - .withClassLoader(new FilteredClassLoader( - "org.springframework.web.servlet.DispatcherServlet")) - .run((context) -> assertThat(context) - .doesNotHaveBean(MvcRequestMatcherProvider.class)); + this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .run((context) -> assertThat(context).doesNotHaveBean(MvcRequestMatcherProvider.class)); } @Test public void jerseyRequestMatcherProviderConditionalOnResourceConfigClass() { - this.contextRunner - .withClassLoader(new FilteredClassLoader( - "org.glassfish.jersey.server.ResourceConfig")) - .run((context) -> assertThat(context) - .doesNotHaveBean(JerseyRequestMatcherProvider.class)); + this.contextRunner.withClassLoader(new FilteredClassLoader("org.glassfish.jersey.server.ResourceConfig")) + .run((context) -> assertThat(context).doesNotHaveBean(JerseyRequestMatcherProvider.class)); } @Test public void mvcRequestMatcherProviderConditionalOnHandlerMappingIntrospectorBean() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(SecurityRequestMatcherProviderAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(MvcRequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(MvcRequestMatcherProvider.class)); } @Test public void jerseyRequestMatcherProviderConditionalOnJerseyApplicationPathBean() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations - .of(SecurityRequestMatcherProviderAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader( - "org.springframework.web.servlet.DispatcherServlet")) - .run((context) -> assertThat(context) - .doesNotHaveBean(JerseyRequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .run((context) -> assertThat(context).doesNotHaveBean(JerseyRequestMatcherProvider.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java index aeaaddb1ccc..350a8a3b99b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java @@ -55,8 +55,7 @@ public class StaticResourceRequestTests { @Test public void atCommonLocationsWithExcludeShouldNotMatchExcluded() { - RequestMatcher matcher = this.resourceRequest.atCommonLocations() - .excluding(StaticResourceLocation.CSS); + RequestMatcher matcher = this.resourceRequest.atCommonLocations().excluding(StaticResourceLocation.CSS); assertMatcher(matcher).doesNotMatch("/css/file.css"); assertMatcher(matcher).matches("/js/file.js"); } @@ -77,16 +76,13 @@ public class StaticResourceRequestTests { @Test public void atLocationsFromSetWhenSetIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.resourceRequest.at(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) .withMessageContaining("Locations must not be null"); } @Test public void excludeFromSetWhenSetIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.resourceRequest.atCommonLocations().excluding(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) .withMessageContaining("Locations must not be null"); } @@ -124,8 +120,7 @@ public class StaticResourceRequestTests { } private void matches(HttpServletRequest request) { - assertThat(this.matcher.matches(request)) - .as("Matches " + getRequestPath(request)).isTrue(); + assertThat(this.matcher.matches(request)).as("Matches " + getRequestPath(request)).isTrue(); } public void doesNotMatch(String path) { @@ -137,8 +132,7 @@ public class StaticResourceRequestTests { } private void doesNotMatch(HttpServletRequest request) { - assertThat(this.matcher.matches(request)) - .as("Does not match " + getRequestPath(request)).isFalse(); + assertThat(this.matcher.matches(request)).as("Does not match " + getRequestPath(request)).isFalse(); } private MockHttpServletRequest mockRequest(String path) { @@ -147,9 +141,7 @@ public class StaticResourceRequestTests { private MockHttpServletRequest mockRequest(String servletPath, String path) { MockServletContext servletContext = new MockServletContext(); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); if (servletPath != null) { request.setServletPath(servletPath); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java index 8b00a059351..6614102bd2e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java @@ -56,77 +56,56 @@ import static org.mockito.Mockito.mock; public class UserDetailsServiceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestSecurityConfiguration.class).withConfiguration( - AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); + .withUserConfiguration(TestSecurityConfiguration.class) + .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); @Test public void testDefaultUsernamePassword(CapturedOutput capturedOutput) { this.contextRunner.run((context) -> { UserDetailsService manager = context.getBean(UserDetailsService.class); - assertThat(capturedOutput.toString()) - .contains("Using generated security password:"); + assertThat(capturedOutput.toString()).contains("Using generated security password:"); assertThat(manager.loadUserByUsername("user")).isNotNull(); }); } @Test - public void defaultUserNotCreatedIfAuthenticationManagerBeanPresent( - CapturedOutput capturedOutput) { - this.contextRunner - .withUserConfiguration(TestAuthenticationManagerConfiguration.class) - .run((context) -> { - AuthenticationManager manager = context - .getBean(AuthenticationManager.class); - assertThat(manager).isEqualTo(context.getBean( - TestAuthenticationManagerConfiguration.class).authenticationManager); - assertThat(capturedOutput.toString()) - .doesNotContain("Using generated security password: "); - TestingAuthenticationToken token = new TestingAuthenticationToken( - "foo", "bar"); - assertThat(manager.authenticate(token)).isNotNull(); - }); + public void defaultUserNotCreatedIfAuthenticationManagerBeanPresent(CapturedOutput capturedOutput) { + this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> { + AuthenticationManager manager = context.getBean(AuthenticationManager.class); + assertThat(manager) + .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); + assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); + TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); + assertThat(manager.authenticate(token)).isNotNull(); + }); } @Test - public void defaultUserNotCreatedIfUserDetailsServiceBeanPresent( - CapturedOutput capturedOutput) { - this.contextRunner - .withUserConfiguration(TestUserDetailsServiceConfiguration.class) - .run((context) -> { - UserDetailsService userDetailsService = context - .getBean(UserDetailsService.class); - assertThat(capturedOutput.toString()) - .doesNotContain("Using generated security password: "); - assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull(); - }); + public void defaultUserNotCreatedIfUserDetailsServiceBeanPresent(CapturedOutput capturedOutput) { + this.contextRunner.withUserConfiguration(TestUserDetailsServiceConfiguration.class).run((context) -> { + UserDetailsService userDetailsService = context.getBean(UserDetailsService.class); + assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); + assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull(); + }); } @Test - public void defaultUserNotCreatedIfAuthenticationProviderBeanPresent( - CapturedOutput capturedOutput) { - this.contextRunner - .withUserConfiguration(TestAuthenticationProviderConfiguration.class) - .run((context) -> { - AuthenticationProvider provider = context - .getBean(AuthenticationProvider.class); - assertThat(capturedOutput.toString()) - .doesNotContain("Using generated security password: "); - TestingAuthenticationToken token = new TestingAuthenticationToken( - "foo", "bar"); - assertThat(provider.authenticate(token)).isNotNull(); - }); + public void defaultUserNotCreatedIfAuthenticationProviderBeanPresent(CapturedOutput capturedOutput) { + this.contextRunner.withUserConfiguration(TestAuthenticationProviderConfiguration.class).run((context) -> { + AuthenticationProvider provider = context.getBean(AuthenticationProvider.class); + assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); + TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); + assertThat(provider.authenticate(token)).isNotNull(); + }); } @Test public void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { - this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class) - .run(((context) -> { - InMemoryUserDetailsManager userDetailsService = context - .getBean(InMemoryUserDetailsManager.class); - String password = userDetailsService.loadUserByUsername("user") - .getPassword(); - assertThat(password).startsWith("{noop}"); - })); + this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class).run(((context) -> { + InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); + String password = userDetailsService.loadUserByUsername("user").getPassword(); + assertThat(password).startsWith("{noop}"); + })); } @Test @@ -147,30 +126,22 @@ public class UserDetailsServiceAutoConfigurationTests { @Test public void userDetailsServiceWhenClientRegistrationRepositoryBeanPresent() { - this.contextRunner - .withUserConfiguration(TestConfigWithClientRegistrationRepository.class) - .run(((context) -> assertThat(context) - .doesNotHaveBean(InMemoryUserDetailsManager.class))); + this.contextRunner.withUserConfiguration(TestConfigWithClientRegistrationRepository.class) + .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); } @Test - public void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed( - CapturedOutput capturedOutput) { - this.contextRunner - .withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) + public void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(CapturedOutput capturedOutput) { + this.contextRunner.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) .run(((context) -> assertThat(capturedOutput.toString()) .doesNotContain("Using generated security password: "))); } - private void testPasswordEncoding(Class configClass, String providedPassword, - String expectedPassword) { + private void testPasswordEncoding(Class configClass, String providedPassword, String expectedPassword) { this.contextRunner.withUserConfiguration(configClass) - .withPropertyValues("spring.security.user.password=" + providedPassword) - .run(((context) -> { - InMemoryUserDetailsManager userDetailsService = context - .getBean(InMemoryUserDetailsManager.class); - String password = userDetailsService.loadUserByUsername("user") - .getPassword(); + .withPropertyValues("spring.security.user.password=" + providedPassword).run(((context) -> { + InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); + String password = userDetailsService.loadUserByUsername("user").getPassword(); assertThat(password).isEqualTo(expectedPassword); })); } @@ -183,8 +154,7 @@ public class UserDetailsServiceAutoConfigurationTests { @Bean public AuthenticationManager myAuthenticationManager() { AuthenticationProvider authenticationProvider = new TestingAuthenticationProvider(); - this.authenticationManager = new ProviderManager( - Collections.singletonList(authenticationProvider)); + this.authenticationManager = new ProviderManager(Collections.singletonList(authenticationProvider)); return this.authenticationManager; } @@ -195,8 +165,7 @@ public class UserDetailsServiceAutoConfigurationTests { @Bean public InMemoryUserDetailsManager myUserDetailsManager() { - return new InMemoryUserDetailsManager( - User.withUsername("foo").password("bar").roles("USER").build()); + return new InMemoryUserDetailsManager(User.withUsername("foo").password("bar").roles("USER").build()); } } @@ -248,11 +217,9 @@ public class UserDetailsServiceAutoConfigurationTests { public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() { return new WebSecurityConfigurerAdapter() { @Override - protected void configure(AuthenticationManagerBuilder auth) - throws Exception { - auth.inMemoryAuthentication().withUser("hero").password("{noop}hero") - .roles("HERO", "USER").and().withUser("user") - .password("{noop}user").roles("USER"); + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("hero").password("{noop}hero").roles("HERO", "USER").and() + .withUser("user").password("{noop}user").roles("USER"); } }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java index e7d52112b90..7642e8d89c6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java @@ -64,20 +64,17 @@ public class SendGridAutoConfigurationTests { @Test public void autoConfigurationNotFiredWhenBeanAlreadyCreated() { - loadContext(ManualSendGridConfiguration.class, - "spring.sendgrid.api-key:SG.SECRET-API-KEY"); + loadContext(ManualSendGridConfiguration.class, "spring.sendgrid.api-key:SG.SECRET-API-KEY"); SendGrid sendGrid = this.context.getBean(SendGrid.class); assertThat(sendGrid).extracting("apiKey").containsExactly("SG.CUSTOM_API_KEY"); } @Test public void expectedSendGridBeanWithProxyCreated() { - loadContext("spring.sendgrid.api-key:SG.SECRET-API-KEY", - "spring.sendgrid.proxy.host:localhost", + loadContext("spring.sendgrid.api-key:SG.SECRET-API-KEY", "spring.sendgrid.proxy.host:localhost", "spring.sendgrid.proxy.port:5678"); SendGrid sendGrid = this.context.getBean(SendGrid.class); - assertThat(sendGrid).extracting("client").extracting("httpClient") - .extracting("routePlanner") + assertThat(sendGrid).extracting("client").extracting("httpClient").extracting("routePlanner") .hasOnlyElementsOfType(DefaultProxyRoutePlanner.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java index 5319f8b8c83..47fceaf1a69 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public abstract class AbstractSessionAutoConfigurationTests { - protected > T validateSessionRepository( - AssertableWebApplicationContext context, Class type) { + protected > T validateSessionRepository(AssertableWebApplicationContext context, + Class type) { assertThat(context).hasSingleBean(SessionRepositoryFilter.class); assertThat(context).hasSingleBean(SessionRepository.class); SessionRepository repository = context.getBean(SessionRepository.class); @@ -51,8 +51,7 @@ public abstract class AbstractSessionAutoConfigurationTests { AssertableReactiveWebApplicationContext context, Class type) { assertThat(context).hasSingleBean(WebSessionManager.class); assertThat(context).hasSingleBean(ReactiveSessionRepository.class); - ReactiveSessionRepository repository = context - .getBean(ReactiveSessionRepository.class); + ReactiveSessionRepository repository = context.getBean(ReactiveSessionRepository.class); assertThat(repository).as("Wrong session repository type").isInstanceOf(type); return type.cast(repository); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java index d22c0cef8bf..561bce13c69 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java @@ -40,18 +40,16 @@ public class NonUniqueSessionRepositoryFailureAnalyzerTests { @Test public void failureAnalysisWithMultipleCandidates() { - FailureAnalysis analysis = analyzeFailure(createFailure( - JdbcOperationsSessionRepository.class, HazelcastSessionRepository.class)); + FailureAnalysis analysis = analyzeFailure( + createFailure(JdbcOperationsSessionRepository.class, HazelcastSessionRepository.class)); assertThat(analysis).isNotNull(); - assertThat(analysis.getDescription()).contains( - JdbcOperationsSessionRepository.class.getName(), + assertThat(analysis.getDescription()).contains(JdbcOperationsSessionRepository.class.getName(), HazelcastSessionRepository.class.getName()); assertThat(analysis.getAction()).contains("spring.session.store-type"); } @SafeVarargs - private final Exception createFailure( - Class>... candidates) { + private final Exception createFailure(Class>... candidates) { return new NonUniqueSessionRepositoryException(Arrays.asList(candidates)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java index ee8c8383a31..65ba6a2d874 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ReactiveSessionAutoConfigurationMongoTests - extends AbstractSessionAutoConfigurationTests { +public class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @@ -47,45 +46,36 @@ public class ReactiveSessionAutoConfigurationMongoTests @Test public void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=mongodb") - .withConfiguration(AutoConfigurations.of( - EmbeddedMongoAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class)) + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) .run(validateSpringSessionUsesMongo("sessions")); } @Test public void defaultConfigWithUniqueStoreImplementation() { - this.contextRunner - .withClassLoader(new FilteredClassLoader( - ReactiveRedisOperationsSessionRepository.class)) - .withConfiguration(AutoConfigurations.of( - EmbeddedMongoAutoConfiguration.class, + this.contextRunner.withClassLoader(new FilteredClassLoader(ReactiveRedisOperationsSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class)) + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) .run(validateSpringSessionUsesMongo("sessions")); } @Test public void mongoSessionStoreWithCustomizations() { this.contextRunner - .withConfiguration(AutoConfigurations.of( - EmbeddedMongoAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=mongodb", - "spring.session.mongodb.collection-name=foo") + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=mongodb", "spring.session.mongodb.collection-name=foo") .run(validateSpringSessionUsesMongo("foo")); } private ContextConsumer validateSpringSessionUsesMongo( String collectionName) { return (context) -> { - ReactiveMongoOperationsSessionRepository repository = validateSessionRepository( - context, ReactiveMongoOperationsSessionRepository.class); + ReactiveMongoOperationsSessionRepository repository = validateSessionRepository(context, + ReactiveMongoOperationsSessionRepository.class); assertThat(repository.getCollectionName()).isEqualTo(collectionName); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java index 8a046d68d40..0332c417096 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Vedran Pavic */ -public class ReactiveSessionAutoConfigurationRedisTests - extends AbstractSessionAutoConfigurationTests { +public class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { protected final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @@ -47,42 +46,36 @@ public class ReactiveSessionAutoConfigurationRedisTests @Test public void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=redis") - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveAutoConfiguration.class)) - .run(validateSpringSessionUsesRedis("spring:session:", - RedisFlushMode.ON_SAVE)); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .run(validateSpringSessionUsesRedis("spring:session:", RedisFlushMode.ON_SAVE)); } @Test public void defaultConfigWithUniqueStoreImplementation() { - this.contextRunner - .withClassLoader(new FilteredClassLoader( - ReactiveMongoOperationsSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveAutoConfiguration.class)) - .run(validateSpringSessionUsesRedis("spring:session:", - RedisFlushMode.ON_SAVE)); + this.contextRunner.withClassLoader(new FilteredClassLoader(ReactiveMongoOperationsSessionRepository.class)) + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .run(validateSpringSessionUsesRedis("spring:session:", RedisFlushMode.ON_SAVE)); } @Test public void redisSessionStoreWithCustomizations() { this.contextRunner - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=redis", - "spring.session.redis.namespace=foo", + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate") .run(validateSpringSessionUsesRedis("foo:", RedisFlushMode.IMMEDIATE)); } - private ContextConsumer validateSpringSessionUsesRedis( - String namespace, RedisFlushMode flushMode) { + private ContextConsumer validateSpringSessionUsesRedis(String namespace, + RedisFlushMode flushMode) { return (context) -> { - ReactiveRedisOperationsSessionRepository repository = validateSessionRepository( - context, ReactiveRedisOperationsSessionRepository.class); + ReactiveRedisOperationsSessionRepository repository = validateSessionRepository(context, + ReactiveRedisOperationsSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("namespace", namespace); - assertThat(repository).hasFieldOrPropertyWithValue("redisFlushMode", - flushMode); + assertThat(repository).hasFieldOrPropertyWithValue("redisFlushMode", flushMode); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java index ffe59cac0dc..47d6d4dbcca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java @@ -43,8 +43,7 @@ import static org.mockito.Mockito.verify; * * @author Vedran Pavic */ -public class SessionAutoConfigurationHazelcastTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) @@ -52,17 +51,14 @@ public class SessionAutoConfigurationHazelcastTests @Test public void defaultConfig() { - this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast") - .run(this::validateDefaultConfig); + this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast").run(this::validateDefaultConfig); } @Test public void defaultConfigWithUniqueStoreImplementation() { this.contextRunner - .withClassLoader( - new FilteredClassLoader(JdbcOperationsSessionRepository.class, - RedisOperationsSessionRepository.class, - MongoOperationsSessionRepository.class)) + .withClassLoader(new FilteredClassLoader(JdbcOperationsSessionRepository.class, + RedisOperationsSessionRepository.class, MongoOperationsSessionRepository.class)) .run(this::validateDefaultConfig); } @@ -74,27 +70,22 @@ public class SessionAutoConfigurationHazelcastTests @Test public void customMapName() { - this.contextRunner - .withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.map-name=foo:bar:biz") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", + "spring.session.hazelcast.map-name=foo:bar:biz").run((context) -> { validateSessionRepository(context, HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); verify(hazelcastInstance, times(1)).getMap("foo:bar:biz"); }); } @Test public void customFlushMode() { - this.contextRunner - .withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.flush-mode=immediate") - .run((context) -> { - HazelcastSessionRepository repository = validateSessionRepository( - context, HazelcastSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue( - "hazelcastFlushMode", HazelcastFlushMode.IMMEDIATE); + this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", + "spring.session.hazelcast.flush-mode=immediate").run((context) -> { + HazelcastSessionRepository repository = validateSessionRepository(context, + HazelcastSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("hazelcastFlushMode", + HazelcastFlushMode.IMMEDIATE); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java index b82ca7deaab..ad2c73f6734 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java @@ -37,27 +37,23 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class SessionAutoConfigurationIntegrationTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationIntegrationTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - SessionAutoConfiguration.class)) + DataSourceTransactionManagerAutoConfiguration.class, SessionAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test public void severalCandidatesWithNoSessionStore() { - this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf( - NonUniqueSessionRepositoryException.class); - assertThat(context).getFailure().hasMessageContaining( - "Multiple session repository candidates are available"); - assertThat(context).getFailure().hasMessageContaining( - "set the 'spring.session.store-type' property accordingly"); - }); + this.contextRunner.withUserConfiguration(HazelcastConfiguration.class).run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasCauseInstanceOf(NonUniqueSessionRepositoryException.class); + assertThat(context).getFailure() + .hasMessageContaining("Multiple session repository candidates are available"); + assertThat(context).getFailure() + .hasMessageContaining("set the 'spring.session.store-type' property accordingly"); + }); } @Test @@ -65,12 +61,10 @@ public class SessionAutoConfigurationIntegrationTests this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) .withPropertyValues("spring.session.store-type=redis").run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf( - SessionRepositoryUnavailableException.class); - assertThat(context).getFailure().hasMessageContaining( - "No session repository could be auto-configured"); + assertThat(context).getFailure().hasCauseInstanceOf(SessionRepositoryUnavailableException.class); assertThat(context).getFailure() - .hasMessageContaining("session store type is 'redis'"); + .hasMessageContaining("No session repository could be auto-configured"); + assertThat(context).getFailure().hasMessageContaining("session store type is 'redis'"); }); } @@ -78,8 +72,7 @@ public class SessionAutoConfigurationIntegrationTests public void severalCandidatesWithValidSessionStore() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) .withPropertyValues("spring.session.store-type=jdbc") - .run((context) -> validateSessionRepository(context, - JdbcOperationsSessionRepository.class)); + .run((context) -> validateSessionRepository(context, JdbcOperationsSessionRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java index 98775aaaeec..542c6428881 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java @@ -44,27 +44,24 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Vedran Pavic * @author Stephane Nicoll */ -public class SessionAutoConfigurationJdbcTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, SessionAutoConfiguration.class)) + DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, + SessionAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test public void defaultConfig() { - this.contextRunner.withPropertyValues("spring.session.store-type=jdbc") - .run(this::validateDefaultConfig); + this.contextRunner.withPropertyValues("spring.session.store-type=jdbc").run(this::validateDefaultConfig); } @Test public void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(HazelcastSessionRepository.class, - MongoOperationsSessionRepository.class, - RedisOperationsSessionRepository.class)) + MongoOperationsSessionRepository.class, RedisOperationsSessionRepository.class)) .run(this::validateDefaultConfig); } @@ -74,72 +71,61 @@ public class SessionAutoConfigurationJdbcTests assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.EMBEDDED); - assertThat(context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION")).isEmpty(); + assertThat(context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); SpringBootJdbcHttpSessionConfiguration configuration = context .getBean(SpringBootJdbcHttpSessionConfiguration.class); - assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", - "0 * * * * *"); + assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", "0 * * * * *"); } @Test public void filterOrderCanBeCustomized() { - this.contextRunner.withPropertyValues("spring.session.store-type=jdbc", - "spring.session.servlet.filter-order=123").run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); + this.contextRunner + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.servlet.filter-order=123") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getOrder()).isEqualTo(123); }); } @Test public void disableDataSourceInitializer() { - this.contextRunner.withPropertyValues("spring.session.store-type=jdbc", - "spring.session.jdbc.initialize-schema=never").run((context) -> { - JdbcOperationsSessionRepository repository = validateSessionRepository( - context, JdbcOperationsSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("tableName", - "SPRING_SESSION"); - assertThat(context.getBean(JdbcSessionProperties.class) - .getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.NEVER); - assertThatExceptionOfType(BadSqlGrammarException.class) - .isThrownBy(() -> context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION")); + this.contextRunner + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") + .run((context) -> { + JdbcOperationsSessionRepository repository = validateSessionRepository(context, + JdbcOperationsSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); + assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.NEVER); + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( + () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); }); } @Test public void customTableName() { - this.contextRunner.withPropertyValues("spring.session.store-type=jdbc", - "spring.session.jdbc.table-name=FOO_BAR", - "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql") + this.contextRunner + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR", + "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql") .run((context) -> { - JdbcOperationsSessionRepository repository = validateSessionRepository( - context, JdbcOperationsSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("tableName", - "FOO_BAR"); - assertThat(context.getBean(JdbcSessionProperties.class) - .getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.EMBEDDED); - assertThat(context.getBean(JdbcOperations.class) - .queryForList("select * from FOO_BAR")).isEmpty(); + JdbcOperationsSessionRepository repository = validateSessionRepository(context, + JdbcOperationsSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("tableName", "FOO_BAR"); + assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.EMBEDDED); + assertThat(context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); }); } @Test public void customCleanupCron() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", - "spring.session.jdbc.cleanup-cron=0 0 12 * * *") + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.cleanup-cron=0 0 12 * * *") .run((context) -> { - assertThat( - context.getBean(JdbcSessionProperties.class).getCleanupCron()) - .isEqualTo("0 0 12 * * *"); + assertThat(context.getBean(JdbcSessionProperties.class).getCleanupCron()).isEqualTo("0 0 12 * * *"); SpringBootJdbcHttpSessionConfiguration configuration = context .getBean(SpringBootJdbcHttpSessionConfiguration.class); - assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", - "0 0 12 * * *"); + assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", "0 0 12 * * *"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java index 88e68dd88a8..8a7dc3b4094 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class SessionAutoConfigurationMongoTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @@ -47,8 +46,7 @@ public class SessionAutoConfigurationMongoTests @Test public void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=mongodb") - .withConfiguration(AutoConfigurations.of( - EmbeddedMongoAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)) .run(validateSpringSessionUsesMongo("sessions")); } @@ -57,10 +55,8 @@ public class SessionAutoConfigurationMongoTests public void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(HazelcastSessionRepository.class, - JdbcOperationsSessionRepository.class, - RedisOperationsSessionRepository.class)) - .withConfiguration(AutoConfigurations.of( - EmbeddedMongoAutoConfiguration.class, + JdbcOperationsSessionRepository.class, RedisOperationsSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)) .run(validateSpringSessionUsesMongo("sessions")); } @@ -68,21 +64,17 @@ public class SessionAutoConfigurationMongoTests @Test public void mongoSessionStoreWithCustomizations() { this.contextRunner - .withConfiguration(AutoConfigurations.of( - EmbeddedMongoAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=mongodb", - "spring.session.mongodb.collection-name=foo") + .withPropertyValues("spring.session.store-type=mongodb", "spring.session.mongodb.collection-name=foo") .run(validateSpringSessionUsesMongo("foo")); } - private ContextConsumer validateSpringSessionUsesMongo( - String collectionName) { + private ContextConsumer validateSpringSessionUsesMongo(String collectionName) { return (context) -> { - MongoOperationsSessionRepository repository = validateSessionRepository( - context, MongoOperationsSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("collectionName", - collectionName); + MongoOperationsSessionRepository repository = validateSessionRepository(context, + MongoOperationsSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("collectionName", collectionName); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java index 2f5fa5dcf31..7d3e9fa838a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java @@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vedran Pavic */ @Testcontainers -public class SessionAutoConfigurationRedisTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { @Container public static RedisContainer redis = new RedisContainer(); @@ -55,52 +54,41 @@ public class SessionAutoConfigurationRedisTests @Test public void defaultConfig() { this.contextRunner - .withPropertyValues("spring.session.store-type=redis", - "spring.redis.port=" + redis.getMappedPort()) + .withPropertyValues("spring.session.store-type=redis", "spring.redis.port=" + redis.getMappedPort()) .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", - RedisFlushMode.ON_SAVE, "0 * * * * *")); + .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", RedisFlushMode.ON_SAVE, + "0 * * * * *")); } @Test public void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(HazelcastSessionRepository.class, - JdbcOperationsSessionRepository.class, - MongoOperationsSessionRepository.class)) + JdbcOperationsSessionRepository.class, MongoOperationsSessionRepository.class)) .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.redis.port=" + redis.getMappedPort()) - .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", - RedisFlushMode.ON_SAVE, "0 * * * * *")); + .withPropertyValues("spring.redis.port=" + redis.getMappedPort()).run(validateSpringSessionUsesRedis( + "spring:session:event:0:created:", RedisFlushMode.ON_SAVE, "0 * * * * *")); } @Test public void redisSessionStoreWithCustomizations() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=redis", - "spring.session.redis.namespace=foo", - "spring.session.redis.flush-mode=immediate", - "spring.session.redis.cleanup-cron=0 0 12 * * *", + this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", + "spring.session.redis.flush-mode=immediate", "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.redis.port=" + redis.getMappedPort()) - .run(validateSpringSessionUsesRedis("foo:event:0:created:", - RedisFlushMode.IMMEDIATE, "0 0 12 * * *")); + .run(validateSpringSessionUsesRedis("foo:event:0:created:", RedisFlushMode.IMMEDIATE, "0 0 12 * * *")); } private ContextConsumer validateSpringSessionUsesRedis( - String sessionCreatedChannelPrefix, RedisFlushMode flushMode, - String cleanupCron) { + String sessionCreatedChannelPrefix, RedisFlushMode flushMode, String cleanupCron) { return (context) -> { - RedisOperationsSessionRepository repository = validateSessionRepository( - context, RedisOperationsSessionRepository.class); - assertThat(repository.getSessionCreatedChannelPrefix()) - .isEqualTo(sessionCreatedChannelPrefix); - assertThat(repository).hasFieldOrPropertyWithValue("redisFlushMode", - flushMode); + RedisOperationsSessionRepository repository = validateSessionRepository(context, + RedisOperationsSessionRepository.class); + assertThat(repository.getSessionCreatedChannelPrefix()).isEqualTo(sessionCreatedChannelPrefix); + assertThat(repository).hasFieldOrPropertyWithValue("redisFlushMode", flushMode); SpringBootRedisHttpSessionConfiguration configuration = context .getBean(SpringBootRedisHttpSessionConfiguration.class); - assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", - cleanupCron); + assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", cleanupCron); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java index 795fc746fee..290d3922b15 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java @@ -62,91 +62,71 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat public void contextFailsIfMultipleStoresAreAvailable() { this.contextRunner.run((context) -> { assertThat(context).hasFailed(); + assertThat(context).getFailure().hasCauseInstanceOf(NonUniqueSessionRepositoryException.class); assertThat(context).getFailure() - .hasCauseInstanceOf(NonUniqueSessionRepositoryException.class); - assertThat(context).getFailure().hasMessageContaining( - "Multiple session repository candidates are available"); + .hasMessageContaining("Multiple session repository candidates are available"); }); } @Test public void contextFailsIfStoreTypeNotAvailable() { - this.contextRunner.withPropertyValues("spring.session.store-type=jdbc") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf( - SessionRepositoryUnavailableException.class); - assertThat(context).getFailure().hasMessageContaining( - "No session repository could be auto-configured"); - assertThat(context).getFailure() - .hasMessageContaining("session store type is 'jdbc'"); - }); + this.contextRunner.withPropertyValues("spring.session.store-type=jdbc").run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasCauseInstanceOf(SessionRepositoryUnavailableException.class); + assertThat(context).getFailure().hasMessageContaining("No session repository could be auto-configured"); + assertThat(context).getFailure().hasMessageContaining("session store type is 'jdbc'"); + }); } @Test public void autoConfigurationDisabledIfStoreTypeSetToNone() { this.contextRunner.withPropertyValues("spring.session.store-type=none") - .run((context) -> assertThat(context) - .doesNotHaveBean(SessionRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SessionRepository.class)); } @Test public void backOffIfSessionRepositoryIsPresent() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("spring.session.store-type=redis").run((context) -> { - MapSessionRepository repository = validateSessionRepository(context, - MapSessionRepository.class); - assertThat(context).getBean("mySessionRepository") - .isSameAs(repository); + MapSessionRepository repository = validateSessionRepository(context, MapSessionRepository.class); + assertThat(context).getBean("mySessionRepository").isSameAs(repository); }); } @Test public void autoConfigWhenSpringSessionTimeoutIsSetShouldUseThat() { this.contextRunner - .withUserConfiguration(ServerPropertiesConfiguration.class, - SessionRepositoryConfiguration.class) - .withPropertyValues("server.servlet.session.timeout=1", - "spring.session.timeout=3") - .run((context) -> assertThat( - context.getBean(SessionProperties.class).getTimeout()) - .isEqualTo(Duration.ofSeconds(3))); + .withUserConfiguration(ServerPropertiesConfiguration.class, SessionRepositoryConfiguration.class) + .withPropertyValues("server.servlet.session.timeout=1", "spring.session.timeout=3") + .run((context) -> assertThat(context.getBean(SessionProperties.class).getTimeout()) + .isEqualTo(Duration.ofSeconds(3))); } @Test public void autoConfigWhenSpringSessionTimeoutIsNotSetShouldUseServerSessionTimeout() { this.contextRunner - .withUserConfiguration(ServerPropertiesConfiguration.class, - SessionRepositoryConfiguration.class) + .withUserConfiguration(ServerPropertiesConfiguration.class, SessionRepositoryConfiguration.class) .withPropertyValues("server.servlet.session.timeout=3") - .run((context) -> assertThat( - context.getBean(SessionProperties.class).getTimeout()) - .isEqualTo(Duration.ofSeconds(3))); + .run((context) -> assertThat(context.getBean(SessionProperties.class).getTimeout()) + .isEqualTo(Duration.ofSeconds(3))); } @SuppressWarnings("unchecked") @Test public void filterIsRegisteredWithAsyncErrorAndRequestDispatcherTypes() { - this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); - assertThat(registration.getFilter()) - .isSameAs(context.getBean(SessionRepositoryFilter.class)); - assertThat((EnumSet) ReflectionTestUtils - .getField(registration, "dispatcherTypes")).containsOnly( - DispatcherType.ASYNC, DispatcherType.ERROR, - DispatcherType.REQUEST); - }); + this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class).run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration.getFilter()).isSameAs(context.getBean(SessionRepositoryFilter.class)); + assertThat((EnumSet) ReflectionTestUtils.getField(registration, "dispatcherTypes")) + .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); + }); } @Test public void filterOrderCanBeCustomizedWithCustomStore() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-order=123") - .run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); + .withPropertyValues("spring.session.servlet.filter-order=123").run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getOrder()).isEqualTo(123); }); } @@ -155,14 +135,10 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Test public void filterDispatcherTypesCanBeCustomized() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues( - "spring.session.servlet.filter-dispatcher-types=error, request") - .run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); - assertThat((EnumSet) ReflectionTestUtils - .getField(registration, "dispatcherTypes")).containsOnly( - DispatcherType.ERROR, DispatcherType.REQUEST); + .withPropertyValues("spring.session.servlet.filter-dispatcher-types=error, request").run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat((EnumSet) ReflectionTestUtils.getField(registration, "dispatcherTypes")) + .containsOnly(DispatcherType.ERROR, DispatcherType.REQUEST); }); } @@ -170,26 +146,17 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat public void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("server.servlet.session.cookie.name=sid", - "server.servlet.session.cookie.domain=spring", - "server.servlet.session.cookie.path=/test", - "server.servlet.session.cookie.httpOnly=false", - "server.servlet.session.cookie.secure=false", + "server.servlet.session.cookie.domain=spring", "server.servlet.session.cookie.path=/test", + "server.servlet.session.cookie.httpOnly=false", "server.servlet.session.cookie.secure=false", "server.servlet.session.cookie.maxAge=10s") .run((context) -> { - DefaultCookieSerializer cookieSerializer = context - .getBean(DefaultCookieSerializer.class); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieName", - "sid"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("domainName", - "spring"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookiePath", - "/test"); - assertThat(cookieSerializer) - .hasFieldOrPropertyWithValue("useHttpOnlyCookie", false); - assertThat(cookieSerializer) - .hasFieldOrPropertyWithValue("useSecureCookie", false); - assertThat(cookieSerializer) - .hasFieldOrPropertyWithValue("cookieMaxAge", 10); + DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieName", "sid"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("domainName", "spring"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookiePath", "/test"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useHttpOnlyCookie", false); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useSecureCookie", false); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieMaxAge", 10); }); } @@ -197,65 +164,48 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat public void autoConfiguredCookieSerializerIsUsedBySessionRepositoryFilter() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("server.port=0").run((context) -> { - SessionRepositoryFilter filter = context - .getBean(SessionRepositoryFilter.class); + SessionRepositoryFilter filter = context.getBean(SessionRepositoryFilter.class); CookieHttpSessionIdResolver sessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils .getField(filter, "httpSessionIdResolver"); DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils .getField(sessionIdResolver, "cookieSerializer"); - assertThat(cookieSerializer) - .isSameAs(context.getBean(DefaultCookieSerializer.class)); + assertThat(cookieSerializer).isSameAs(context.getBean(DefaultCookieSerializer.class)); }); } @Test public void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresACookieSerializer() { - this.contextRunner - .withUserConfiguration(UserProvidedCookieSerializerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(DefaultCookieSerializer.class); - assertThat(context).hasBean("myCookieSerializer"); - }); + this.contextRunner.withUserConfiguration(UserProvidedCookieSerializerConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(DefaultCookieSerializer.class); + assertThat(context).hasBean("myCookieSerializer"); + }); } @Test public void cookiesSerializerIsAutoConfiguredWhenUserConfiguresCookieHttpSessionIdResolver() { - this.contextRunner - .withUserConfiguration( - UserProvidedCookieHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat( - context.getBeansOfType(DefaultCookieSerializer.class)) - .isNotEmpty()); + this.contextRunner.withUserConfiguration(UserProvidedCookieHttpSessionStrategyConfiguration.class) + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isNotEmpty()); } @Test public void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresHeaderHttpSessionIdResolver() { - this.contextRunner - .withUserConfiguration( - UserProvidedHeaderHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat( - context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); + this.contextRunner.withUserConfiguration(UserProvidedHeaderHttpSessionStrategyConfiguration.class) + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test public void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresCustomHttpSessionIdResolver() { - this.contextRunner - .withUserConfiguration( - UserProvidedCustomHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat( - context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); + this.contextRunner.withUserConfiguration(UserProvidedCustomHttpSessionStrategyConfiguration.class) + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test public void autoConfiguredCookieSerializerIsConfiguredWithRememberMeRequestAttribute() { - this.contextRunner.withBean(SpringSessionRememberMeServicesConfiguration.class) - .run((context) -> { - DefaultCookieSerializer cookieSerializer = context - .getBean(DefaultCookieSerializer.class); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue( - "rememberMeRequestAttribute", - SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); - }); + this.contextRunner.withBean(SpringSessionRememberMeServicesConfiguration.class).run((context) -> { + DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("rememberMeRequestAttribute", + SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); + }); } @Configuration(proxyBeanMethods = false) @@ -276,8 +226,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration(proxyBeanMethods = false) @EnableSpringHttpSession - static class UserProvidedCookieSerializerConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedCookieSerializerConfiguration extends SessionRepositoryConfiguration { @Bean public DefaultCookieSerializer myCookieSerializer() { @@ -288,8 +237,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration(proxyBeanMethods = false) @EnableSpringHttpSession - static class UserProvidedCookieHttpSessionStrategyConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedCookieHttpSessionStrategyConfiguration extends SessionRepositoryConfiguration { @Bean public CookieHttpSessionIdResolver httpSessionStrategy() { @@ -300,8 +248,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration(proxyBeanMethods = false) @EnableSpringHttpSession - static class UserProvidedHeaderHttpSessionStrategyConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedHeaderHttpSessionStrategyConfiguration extends SessionRepositoryConfiguration { @Bean public HeaderHttpSessionIdResolver httpSessionStrategy() { @@ -312,8 +259,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration(proxyBeanMethods = false) @EnableSpringHttpSession - static class UserProvidedCustomHttpSessionStrategyConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedCustomHttpSessionStrategyConfiguration extends SessionRepositoryConfiguration { @Bean public HttpSessionIdResolver httpSessionStrategy() { @@ -324,8 +270,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration(proxyBeanMethods = false) @EnableSpringHttpSession - static class SpringSessionRememberMeServicesConfiguration - extends SessionRepositoryConfiguration { + static class SpringSessionRememberMeServicesConfiguration extends SessionRepositoryConfiguration { @Bean public SpringSessionRememberMeServices rememberMeServices() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java index 931f077e819..dac00cb2de0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java @@ -35,21 +35,17 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions("spring-security-*") -public class SessionAutoConfigurationWithoutSecurityTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationWithoutSecurityTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test public void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { - this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .run((context) -> { - DefaultCookieSerializer cookieSerializer = context - .getBean(DefaultCookieSerializer.class); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue( - "rememberMeRequestAttribute", null); - }); + this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class).run((context) -> { + DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("rememberMeRequestAttribute", null); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java index d91f6801d0c..20f8f8928bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java @@ -57,57 +57,44 @@ import static org.mockito.Mockito.verify; public class TaskExecutionAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); @Test public void taskExecutorBuilderShouldApplyCustomSettings() { - this.contextRunner - .withPropertyValues("spring.task.execution.pool.queue-capacity=10", - "spring.task.execution.pool.core-size=2", - "spring.task.execution.pool.max-size=4", - "spring.task.execution.pool.allow-core-thread-timeout=true", - "spring.task.execution.pool.keep-alive=5s", - "spring.task.execution.shutdown.await-termination=true", - "spring.task.execution.shutdown.await-termination-period=30s", - "spring.task.execution.thread-name-prefix=mytest-") - .run(assertTaskExecutor((taskExecutor) -> { - assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity", - 10); + this.contextRunner.withPropertyValues("spring.task.execution.pool.queue-capacity=10", + "spring.task.execution.pool.core-size=2", "spring.task.execution.pool.max-size=4", + "spring.task.execution.pool.allow-core-thread-timeout=true", "spring.task.execution.pool.keep-alive=5s", + "spring.task.execution.shutdown.await-termination=true", + "spring.task.execution.shutdown.await-termination-period=30s", + "spring.task.execution.thread-name-prefix=mytest-").run(assertTaskExecutor((taskExecutor) -> { + assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity", 10); assertThat(taskExecutor.getCorePoolSize()).isEqualTo(2); assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(4); - assertThat(taskExecutor) - .hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true); assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(5); - assertThat(taskExecutor).hasFieldOrPropertyWithValue( - "waitForTasksToCompleteOnShutdown", true); - assertThat(taskExecutor) - .hasFieldOrPropertyWithValue("awaitTerminationSeconds", 30); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationSeconds", 30); assertThat(taskExecutor.getThreadNamePrefix()).isEqualTo("mytest-"); })); } @Test public void taskExecutorBuilderWhenHasCustomBuilderShouldUseCustomBuilder() { - this.contextRunner.withUserConfiguration(CustomTaskExecutorBuilderConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(TaskExecutorBuilder.class); - assertThat(context.getBean(TaskExecutorBuilder.class)) - .isSameAs(context.getBean( - CustomTaskExecutorBuilderConfig.class).taskExecutorBuilder); - }); + this.contextRunner.withUserConfiguration(CustomTaskExecutorBuilderConfig.class).run((context) -> { + assertThat(context).hasSingleBean(TaskExecutorBuilder.class); + assertThat(context.getBean(TaskExecutorBuilder.class)) + .isSameAs(context.getBean(CustomTaskExecutorBuilderConfig.class).taskExecutorBuilder); + }); } @Test public void taskExecutorBuilderShouldUseTaskDecorator() { - this.contextRunner.withUserConfiguration(TaskDecoratorConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(TaskExecutorBuilder.class); - ThreadPoolTaskExecutor executor = context - .getBean(TaskExecutorBuilder.class).build(); - assertThat(ReflectionTestUtils.getField(executor, "taskDecorator")) - .isSameAs(context.getBean(TaskDecorator.class)); - }); + this.contextRunner.withUserConfiguration(TaskDecoratorConfig.class).run((context) -> { + assertThat(context).hasSingleBean(TaskExecutorBuilder.class); + ThreadPoolTaskExecutor executor = context.getBean(TaskExecutorBuilder.class).build(); + assertThat(ReflectionTestUtils.getField(executor, "taskDecorator")) + .isSameAs(context.getBean(TaskDecorator.class)); + }); } @Test @@ -116,40 +103,32 @@ public class TaskExecutionAutoConfigurationTests { assertThat(capturedOutput).doesNotContain("Initializing ExecutorService"); assertThat(context).hasSingleBean(Executor.class); assertThat(context).hasBean("applicationTaskExecutor"); - assertThat(context).getBean("applicationTaskExecutor") - .isInstanceOf(ThreadPoolTaskExecutor.class); + assertThat(context).getBean("applicationTaskExecutor").isInstanceOf(ThreadPoolTaskExecutor.class); assertThat(capturedOutput).contains("Initializing ExecutorService"); }); } @Test public void taskExecutorWhenHasCustomTaskExecutorShouldBackOff() { - this.contextRunner.withUserConfiguration(CustomTaskExecutorConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(Executor.class); - assertThat(context.getBean(Executor.class)) - .isSameAs(context.getBean("customTaskExecutor")); - }); + this.contextRunner.withUserConfiguration(CustomTaskExecutorConfig.class).run((context) -> { + assertThat(context).hasSingleBean(Executor.class); + assertThat(context.getBean(Executor.class)).isSameAs(context.getBean("customTaskExecutor")); + }); } @Test public void taskExecutorBuilderShouldApplyCustomizer() { - this.contextRunner.withUserConfiguration(TaskExecutorCustomizerConfig.class) - .run((context) -> { - TaskExecutorCustomizer customizer = context - .getBean(TaskExecutorCustomizer.class); - ThreadPoolTaskExecutor executor = context - .getBean(TaskExecutorBuilder.class).build(); - verify(customizer).customize(executor); - }); + this.contextRunner.withUserConfiguration(TaskExecutorCustomizerConfig.class).run((context) -> { + TaskExecutorCustomizer customizer = context.getBean(TaskExecutorCustomizer.class); + ThreadPoolTaskExecutor executor = context.getBean(TaskExecutorBuilder.class).build(); + verify(customizer).customize(executor); + }); } @Test public void enableAsyncUsesAutoConfiguredOneByDefault() { - this.contextRunner - .withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") - .withUserConfiguration(AsyncConfiguration.class, TestBean.class) - .run((context) -> { + this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") + .withUserConfiguration(AsyncConfiguration.class, TestBean.class).run((context) -> { assertThat(context).hasSingleBean(TaskExecutor.class); TestBean bean = context.getBean(TestBean.class); String text = bean.echo("something").get(); @@ -159,12 +138,9 @@ public class TaskExecutionAutoConfigurationTests { @Test public void enableAsyncUsesAutoConfiguredOneByDefaultEvenThoughSchedulingIsConfigured() { - this.contextRunner - .withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") - .withConfiguration( - AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(AsyncConfiguration.class, - SchedulingConfiguration.class, TestBean.class) + this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .withUserConfiguration(AsyncConfiguration.class, SchedulingConfiguration.class, TestBean.class) .run((context) -> { TestBean bean = context.getBean(TestBean.class); String text = bean.echo("something").get(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java index 0c418eeb35d..143193ea2e7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java @@ -48,20 +48,18 @@ import static org.assertj.core.api.Assertions.assertThat; public class TaskSchedulingAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class).withConfiguration( - AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); @Test public void noSchedulingDoesNotExposeTaskScheduler() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(TaskScheduler.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(TaskScheduler.class)); } @Test public void enableSchedulingWithNoTaskExecutorAutoConfiguresOne() { this.contextRunner - .withPropertyValues( - "spring.task.scheduling.shutdown.await-termination=true", + .withPropertyValues("spring.task.scheduling.shutdown.await-termination=true", "spring.task.scheduling.shutdown.await-termination-period=30s", "spring.task.scheduling.thread-name-prefix=scheduling-test-") .withUserConfiguration(SchedulingConfiguration.class).run((context) -> { @@ -69,38 +67,30 @@ public class TaskSchedulingAutoConfigurationTests { TaskExecutor taskExecutor = context.getBean(TaskExecutor.class); TestBean bean = context.getBean(TestBean.class); assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(taskExecutor).hasFieldOrPropertyWithValue( - "waitForTasksToCompleteOnShutdown", true); - assertThat(taskExecutor) - .hasFieldOrPropertyWithValue("awaitTerminationSeconds", 30); - assertThat(bean.threadNames) - .allMatch((name) -> name.contains("scheduling-test-")); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationSeconds", 30); + assertThat(bean.threadNames).allMatch((name) -> name.contains("scheduling-test-")); }); } @Test public void enableSchedulingWithNoTaskExecutorAppliesCustomizers() { - this.contextRunner - .withPropertyValues( - "spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withUserConfiguration(SchedulingConfiguration.class, - TaskSchedulerCustomizerConfiguration.class) + this.contextRunner.withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") + .withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerCustomizerConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(TaskExecutor.class); TestBean bean = context.getBean(TestBean.class); assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames) - .allMatch((name) -> name.contains("customized-scheduler-")); + assertThat(bean.threadNames).allMatch((name) -> name.contains("customized-scheduler-")); }); } @Test public void enableSchedulingWithExistingTaskSchedulerBacksOff() { - this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, - TaskSchedulerConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerConfiguration.class) + .run((context) -> { assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context.getBean(TaskScheduler.class)) - .isInstanceOf(TestTaskScheduler.class); + assertThat(context.getBean(TaskScheduler.class)).isInstanceOf(TestTaskScheduler.class); TestBean bean = context.getBean(TestBean.class); assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(bean.threadNames).containsExactly("test-1"); @@ -109,21 +99,21 @@ public class TaskSchedulingAutoConfigurationTests { @Test public void enableSchedulingWithExistingScheduledExecutorServiceBacksOff() { - this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, - ScheduledExecutorServiceConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(SchedulingConfiguration.class, ScheduledExecutorServiceConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean(TaskScheduler.class); assertThat(context).hasSingleBean(ScheduledExecutorService.class); TestBean bean = context.getBean(TestBean.class); assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames) - .allMatch((name) -> name.contains("pool-")); + assertThat(bean.threadNames).allMatch((name) -> name.contains("pool-")); }); } @Test public void enableSchedulingWithConfigurerBacksOff() { - this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, - SchedulingConfigurerConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, SchedulingConfigurerConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean(TaskScheduler.class); TestBean bean = context.getBean(TestBean.class); assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); @@ -162,8 +152,7 @@ public class TaskSchedulingAutoConfigurationTests { @Bean public TaskSchedulerCustomizer testTaskSchedulerCustomizer() { - return ((taskScheduler) -> taskScheduler - .setThreadNamePrefix("customized-scheduler-")); + return ((taskScheduler) -> taskScheduler.setThreadNamePrefix("customized-scheduler-")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java index deb228f9ba3..c747f10fdd1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java @@ -59,14 +59,13 @@ public class TemplateAvailabilityProvidersTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - this.providers = new TemplateAvailabilityProviders( - Collections.singleton(this.provider)); + this.providers = new TemplateAvailabilityProviders(Collections.singleton(this.provider)); } @Test public void createWhenApplicationContextIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new TemplateAvailabilityProviders((ApplicationContext) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)) .withMessageContaining("ClassLoader must not be null"); } @@ -74,31 +73,27 @@ public class TemplateAvailabilityProvidersTests { public void createWhenUsingApplicationContextShouldLoadProviders() { ApplicationContext applicationContext = mock(ApplicationContext.class); given(applicationContext.getClassLoader()).willReturn(this.classLoader); - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - applicationContext); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(applicationContext); assertThat(providers.getProviders()).isNotEmpty(); verify(applicationContext).getClassLoader(); } @Test public void createWhenClassLoaderIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null)) .withMessageContaining("ClassLoader must not be null"); } @Test public void createWhenUsingClassLoaderShouldLoadProviders() { - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - this.classLoader); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(this.classLoader); assertThat(providers.getProviders()).isNotEmpty(); } @Test public void createWhenProvidersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TemplateAvailabilityProviders( - (Collection) null)) + .isThrownBy(() -> new TemplateAvailabilityProviders((Collection) null)) .withMessageContaining("Providers must not be null"); } @@ -111,95 +106,84 @@ public class TemplateAvailabilityProvidersTests { @Test public void getProviderWhenApplicationContextIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, null)) .withMessageContaining("ApplicationContext must not be null"); } @Test public void getProviderWhenViewIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(null, this.environment, - this.classLoader, this.resourceLoader)) + .isThrownBy( + () -> this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader)) .withMessageContaining("View must not be null"); } @Test public void getProviderWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, null, - this.classLoader, this.resourceLoader)) + .isThrownBy(() -> this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader)) .withMessageContaining("Environment must not be null"); } @Test public void getProviderWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, - null, this.resourceLoader)) + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)) .withMessageContaining("ClassLoader must not be null"); } @Test public void getProviderWhenResourceLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, - this.classLoader, null)) + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.classLoader, null)) .withMessageContaining("ResourceLoader must not be null"); } @Test public void getProviderWhenNoneMatchShouldReturnNull() { - TemplateAvailabilityProvider found = this.providers.getProvider(this.view, - this.environment, this.classLoader, this.resourceLoader); + TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, + this.resourceLoader); assertThat(found).isNull(); - verify(this.provider).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); + verify(this.provider).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test public void getProviderWhenMatchShouldReturnProvider() { - given(this.provider.isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader)).willReturn(true); - TemplateAvailabilityProvider found = this.providers.getProvider(this.view, - this.environment, this.classLoader, this.resourceLoader); + given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) + .willReturn(true); + TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, + this.resourceLoader); assertThat(found).isSameAs(this.provider); } @Test public void getProviderShouldCacheMatchResult() { - given(this.provider.isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader)).willReturn(true); - this.providers.getProvider(this.view, this.environment, this.classLoader, + given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) + .willReturn(true); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); - this.providers.getProvider(this.view, this.environment, this.classLoader, - this.resourceLoader); - verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); } @Test public void getProviderShouldCacheNoMatchResult() { - this.providers.getProvider(this.view, this.environment, this.classLoader, + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); - this.providers.getProvider(this.view, this.environment, this.classLoader, - this.resourceLoader); - verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); } @Test public void getProviderWhenCacheDisabledShouldNotUseCache() { - given(this.provider.isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader)).willReturn(true); + given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) + .willReturn(true); this.environment.setProperty("spring.template.provider.cache", "false"); - this.providers.getProvider(this.view, this.environment, this.classLoader, + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + verify(this.provider, times(2)).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); - this.providers.getProvider(this.view, this.environment, this.classLoader, - this.resourceLoader); - verify(this.provider, times(2)).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java index e0da1d406f5..2535be704b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java @@ -33,8 +33,7 @@ public class ViewResolverPropertiesTests { @Test public void defaultContentType() { - assertThat(new ViewResolverProperties().getContentType()) - .hasToString("text/html;charset=UTF-8"); + assertThat(new ViewResolverProperties().getContentType()).hasToString("text/html;charset=UTF-8"); } @Test @@ -64,8 +63,7 @@ public class ViewResolverPropertiesTests { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain;foo=bar")); properties.setCharset(StandardCharsets.UTF_16); - assertThat(properties.getContentType()) - .hasToString("text/plain;charset=UTF-16;foo=bar"); + assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-16;foo=bar"); } private static class ViewResolverProperties extends AbstractViewResolverProperties { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java index 8c9b484069e..c51f1e0da61 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java @@ -68,148 +68,114 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void createFromConfigClass() { - this.contextRunner.withPropertyValues("spring.thymeleaf.suffix:.html") - .run((context) -> { - TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("foo", "bar")); - String result = engine.process("template", attrs).trim(); - assertThat(result).isEqualTo("bar"); - }); + this.contextRunner.withPropertyValues("spring.thymeleaf.suffix:.html").run((context) -> { + TemplateEngine engine = context.getBean(TemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); + String result = engine.process("template", attrs).trim(); + assertThat(result).isEqualTo("bar"); + }); } @Test public void overrideCharacterEncoding() { - this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16") - .run((context) -> { - ITemplateResolver resolver = context.getBean(ITemplateResolver.class); - assertThat(resolver) - .isInstanceOf(SpringResourceTemplateResolver.class); - assertThat(((SpringResourceTemplateResolver) resolver) - .getCharacterEncoding()).isEqualTo("UTF-16"); - ThymeleafReactiveViewResolver views = context - .getBean(ThymeleafReactiveViewResolver.class); - assertThat(views.getDefaultCharset().name()).isEqualTo("UTF-16"); - }); + this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16").run((context) -> { + ITemplateResolver resolver = context.getBean(ITemplateResolver.class); + assertThat(resolver).isInstanceOf(SpringResourceTemplateResolver.class); + assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()).isEqualTo("UTF-16"); + ThymeleafReactiveViewResolver views = context.getBean(ThymeleafReactiveViewResolver.class); + assertThat(views.getDefaultCharset().name()).isEqualTo("UTF-16"); + }); } @Test public void overrideMediaTypes() { - this.contextRunner - .withPropertyValues( - "spring.thymeleaf.reactive.media-types:text/html,text/plain") - .run((context) -> assertThat( - context.getBean(ThymeleafReactiveViewResolver.class) - .getSupportedMediaTypes()).contains(MediaType.TEXT_HTML, - MediaType.TEXT_PLAIN)); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.media-types:text/html,text/plain").run( + (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) + .contains(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN)); } @Test public void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") - .run((context) -> assertThat( - context.getBean(ITemplateResolver.class).getOrder()) - .isEqualTo(Integer.valueOf(25))); + .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) + .isEqualTo(Integer.valueOf(25))); } @Test public void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") - .run((context) -> assertThat(context - .getBean(ThymeleafReactiveViewResolver.class).getViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test public void overrideMaxChunkSize() { - this.contextRunner - .withPropertyValues("spring.thymeleaf.reactive.maxChunkSize:8KB") + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.maxChunkSize:8KB") .run((context) -> assertThat( - context.getBean(ThymeleafReactiveViewResolver.class) - .getResponseMaxChunkSizeBytes()) - .isEqualTo(Integer.valueOf(8192))); + context.getBean(ThymeleafReactiveViewResolver.class).getResponseMaxChunkSizeBytes()) + .isEqualTo(Integer.valueOf(8192))); } @Test public void overrideFullModeViewNames() { - this.contextRunner - .withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar") - .run((context) -> assertThat( - context.getBean(ThymeleafReactiveViewResolver.class) - .getFullModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar").run( + (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getFullModeViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test public void overrideChunkedModeViewNames() { - this.contextRunner - .withPropertyValues( - "spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar") - .run((context) -> assertThat( - context.getBean(ThymeleafReactiveViewResolver.class) - .getChunkedModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar").run( + (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getChunkedModeViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test public void overrideEnableSpringElCompiler() { - this.contextRunner - .withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") - .run((context) -> assertThat( - context.getBean(SpringWebFluxTemplateEngine.class) - .getEnableSpringELCompiler()).isTrue()); + this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true").run( + (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) + .isTrue()); } @Test public void enableSpringElCompilerIsDisabledByDefault() { this.contextRunner.run( - (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class) - .getEnableSpringELCompiler()).isFalse()); + (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) + .isFalse()); } @Test public void overrideRenderHiddenMarkersBeforeCheckboxes() { - this.contextRunner - .withPropertyValues( - "spring.thymeleaf.render-hidden-markers-before-checkboxes:true") + this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") .run((context) -> assertThat( - context.getBean(SpringWebFluxTemplateEngine.class) - .getRenderHiddenMarkersBeforeCheckboxes()).isTrue()); + context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isTrue()); } @Test public void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class) - .getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); + this.contextRunner.run((context) -> assertThat( + context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); } @Test public void templateLocationDoesNotExist(CapturedOutput capturedOutput) { - this.contextRunner - .withPropertyValues( - "spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> assertThat(capturedOutput) - .contains("Cannot find template location")); + this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") + .run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); } @Test public void templateLocationEmpty(CapturedOutput capturedOutput) { - new File(this.buildOutput.getTestResourcesLocation(), - "empty-templates/empty-directory").mkdirs(); - this.contextRunner.withPropertyValues( - "spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(capturedOutput) - .doesNotContain("Cannot find template location")); + new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); + this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); } @Test public void useDataDialect() { this.contextRunner.run((context) -> { - ISpringWebFluxTemplateEngine engine = context - .getBean(ISpringWebFluxTemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("foo", "bar")); + ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("data-dialect", attrs).trim(); assertThat(result).isEqualTo(""); }); @@ -218,8 +184,7 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void useJava8TimeDialect() { this.contextRunner.run((context) -> { - ISpringWebFluxTemplateEngine engine = context - .getBean(ISpringWebFluxTemplateEngine.class); + ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); Context attrs = new Context(Locale.UK); String result = engine.process("java8time-dialect", attrs).trim(); assertThat(result).isEqualTo("2015-11-24"); @@ -229,28 +194,21 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void useSecurityDialect() { this.contextRunner.run((context) -> { - ISpringWebFluxTemplateEngine engine = context - .getBean(ISpringWebFluxTemplateEngine.class); - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/test").build()); - exchange.getAttributes().put( - SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME, - new SecurityContextImpl( - new TestingAuthenticationToken("alice", "admin"))); + ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); + exchange.getAttributes().put(SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME, + new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); IContext attrs = new SpringWebFluxContext(exchange); String result = engine.process("security-dialect", attrs); - assertThat(result).isEqualTo("
    alice
    " - + System.lineSeparator()); + assertThat(result).isEqualTo("
    alice
    " + System.lineSeparator()); }); } @Test public void renderTemplate() { this.contextRunner.run((context) -> { - ISpringWebFluxTemplateEngine engine = context - .getBean(ISpringWebFluxTemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("foo", "bar")); + ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("home", attrs).trim(); assertThat(result).isEqualTo("bar"); }); @@ -259,8 +217,8 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) - .run((context) -> assertThat(ReflectionTestUtils.getField( - context.getBean(LayoutDialect.class), "sortingStrategy")) + .run((context) -> assertThat( + ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) .isInstanceOf(GroupingRespectLayoutTitleStrategy.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java index 0771dd4e664..5fc1551d061 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java @@ -84,20 +84,17 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void autoConfigurationBackOffWithoutThymeleafSpring() { - this.contextRunner - .withClassLoader(new FilteredClassLoader("org.thymeleaf.spring5")) - .run((context) -> assertThat(context) - .doesNotHaveBean(TemplateEngine.class)); + this.contextRunner.withClassLoader(new FilteredClassLoader("org.thymeleaf.spring5")) + .run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class)); } @Test public void createFromConfigClass() { - this.contextRunner.withPropertyValues("spring.thymeleaf.mode:HTML", - "spring.thymeleaf.suffix:").run((context) -> { + this.contextRunner.withPropertyValues("spring.thymeleaf.mode:HTML", "spring.thymeleaf.suffix:") + .run((context) -> { assertThat(context).hasSingleBean(TemplateEngine.class); TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("foo", "bar")); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("template.html", attrs).trim(); assertThat(result).isEqualTo("bar"); }); @@ -105,112 +102,92 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void overrideCharacterEncoding() { - this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16") - .run((context) -> { - ITemplateResolver resolver = context.getBean(ITemplateResolver.class); - assertThat(resolver) - .isInstanceOf(SpringResourceTemplateResolver.class); - assertThat(((SpringResourceTemplateResolver) resolver) - .getCharacterEncoding()).isEqualTo("UTF-16"); - ThymeleafViewResolver views = context - .getBean(ThymeleafViewResolver.class); - assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16"); - assertThat(views.getContentType()) - .isEqualTo("text/html;charset=UTF-16"); - }); + this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16").run((context) -> { + ITemplateResolver resolver = context.getBean(ITemplateResolver.class); + assertThat(resolver).isInstanceOf(SpringResourceTemplateResolver.class); + assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()).isEqualTo("UTF-16"); + ThymeleafViewResolver views = context.getBean(ThymeleafViewResolver.class); + assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16"); + assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16"); + }); } @Test public void overrideDisableProducePartialOutputWhileProcessing() { - this.contextRunner.withPropertyValues( - "spring.thymeleaf.servlet.produce-partial-output-while-processing:false") - .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class) - .getProducePartialOutputWhileProcessing()).isFalse()); + this.contextRunner.withPropertyValues("spring.thymeleaf.servlet.produce-partial-output-while-processing:false") + .run((context) -> assertThat( + context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) + .isFalse()); } @Test public void disableProducePartialOutputWhileProcessingIsEnabledByDefault() { - this.contextRunner - .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class) - .getProducePartialOutputWhileProcessing()).isTrue()); + this.contextRunner.run((context) -> assertThat( + context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()).isTrue()); } @Test public void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") - .run((context) -> assertThat( - context.getBean(ITemplateResolver.class).getOrder()) - .isEqualTo(Integer.valueOf(25))); + .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) + .isEqualTo(Integer.valueOf(25))); } @Test public void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") - .run((context) -> assertThat( - context.getBean(ThymeleafViewResolver.class).getViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test public void overrideEnableSpringElCompiler() { - this.contextRunner - .withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class) - .getEnableSpringELCompiler()).isTrue()); + this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") + .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) + .isTrue()); } @Test public void enableSpringElCompilerIsDisabledByDefault() { - this.contextRunner.run((context) -> assertThat( - context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) + this.contextRunner + .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) .isFalse()); } @Test public void overrideRenderHiddenMarkersBeforeCheckboxes() { - this.contextRunner - .withPropertyValues( - "spring.thymeleaf.render-hidden-markers-before-checkboxes:true") - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class) - .getRenderHiddenMarkersBeforeCheckboxes()).isTrue()); + this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") + .run((context) -> assertThat( + context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isTrue()); } @Test public void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { - this.contextRunner - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class) - .getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); + this.contextRunner.run((context) -> assertThat( + context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); } @Test public void templateLocationDoesNotExist() { - this.contextRunner - .withPropertyValues( - "spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> this.output - .expect(containsString("Cannot find template location"))); + this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") + .run((context) -> this.output.expect(containsString("Cannot find template location"))); } @Test public void templateLocationEmpty() { - new File(this.buildOutput.getTestResourcesLocation(), - "empty-templates/empty-directory").mkdirs(); - this.contextRunner.withPropertyValues( - "spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> this.output - .expect(not(containsString("Cannot find template location")))); + new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); + this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") + .run((context) -> this.output.expect(not(containsString("Cannot find template location")))); } @Test public void createLayoutFromConfigClass() { this.contextRunner.run((context) -> { - ThymeleafView view = (ThymeleafView) context - .getBean(ThymeleafViewResolver.class) - .resolveViewName("view", Locale.UK); + ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class).resolveViewName("view", + Locale.UK); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); - request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, - context); + request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); view.render(Collections.singletonMap("foo", "bar"), request, response); String result = response.getContentAsString(); assertThat(result).contains("Content"); @@ -223,8 +200,7 @@ public class ThymeleafServletAutoConfigurationTests { public void useDataDialect() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("foo", "bar")); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("data-dialect", attrs).trim(); assertThat(result).isEqualTo(""); }); @@ -244,14 +220,13 @@ public class ThymeleafServletAutoConfigurationTests { public void useSecurityDialect() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); - WebContext attrs = new WebContext(new MockHttpServletRequest(), - new MockHttpServletResponse(), new MockServletContext()); + WebContext attrs = new WebContext(new MockHttpServletRequest(), new MockHttpServletResponse(), + new MockServletContext()); try { - SecurityContextHolder.setContext(new SecurityContextImpl( - new TestingAuthenticationToken("alice", "admin"))); + SecurityContextHolder + .setContext(new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); String result = engine.process("security-dialect", attrs); - assertThat(result).isEqualTo("
    alice
    " - + System.lineSeparator()); + assertThat(result).isEqualTo("
    alice
    " + System.lineSeparator()); } finally { SecurityContextHolder.clearContext(); @@ -263,8 +238,7 @@ public class ThymeleafServletAutoConfigurationTests { public void renderTemplate() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("foo", "bar")); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("home", attrs).trim(); assertThat(result).isEqualTo("bar"); }); @@ -272,14 +246,11 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void renderNonWebAppTemplate() { - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ThymeleafAutoConfiguration.class)) + new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)) .run((context) -> { assertThat(context).doesNotHaveBean(ViewResolver.class); TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("greeting", "Hello World")); + Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); String result = engine.process("message", attrs); assertThat(result).contains("Hello World"); }); @@ -287,40 +258,30 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void registerResourceHandlingFilterDisabledByDefault() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(FilterRegistrationBean.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)); } @Test public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { - this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true") - .run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); - assertThat(registration.getFilter()) - .isInstanceOf(ResourceUrlEncodingFilter.class); - assertThat(registration).hasFieldOrPropertyWithValue( - "dispatcherTypes", - EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); - }); + this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration.getFilter()).isInstanceOf(ResourceUrlEncodingFilter.class); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); + }); } @Test @SuppressWarnings("rawtypes") public void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 - this.contextRunner - .withUserConfiguration(FilterRegistrationOtherConfiguration.class) - .withPropertyValues("spring.resources.chain.enabled:true") - .run((context) -> { - Map beans = context - .getBeansOfType(FilterRegistrationBean.class); + this.contextRunner.withUserConfiguration(FilterRegistrationOtherConfiguration.class) + .withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { + Map beans = context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(2); - FilterRegistrationBean registration = beans.values().stream().filter( - (r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) - .findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue( - "dispatcherTypes", + FilterRegistrationBean registration = beans.values().stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); }); } @@ -329,39 +290,32 @@ public class ThymeleafServletAutoConfigurationTests { @SuppressWarnings("rawtypes") public void registerResourceHandlingFilterWithResourceRegistrationBean() { // gh-14926 - this.contextRunner - .withUserConfiguration(FilterRegistrationResourceConfiguration.class) - .withPropertyValues("spring.resources.chain.enabled:true") - .run((context) -> { - Map beans = context - .getBeansOfType(FilterRegistrationBean.class); + this.contextRunner.withUserConfiguration(FilterRegistrationResourceConfiguration.class) + .withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { + Map beans = context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(1); - FilterRegistrationBean registration = beans.values().stream().filter( - (r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) - .findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue( - "dispatcherTypes", EnumSet.of(DispatcherType.INCLUDE)); + FilterRegistrationBean registration = beans.values().stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.INCLUDE)); }); } @Test public void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) - .run((context) -> assertThat(ReflectionTestUtils.getField( - context.getBean(LayoutDialect.class), "sortingStrategy")) + .run((context) -> assertThat( + ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) .isInstanceOf(GroupingRespectLayoutTitleStrategy.class)); } @Test public void cachingCanBeDisabled() { - this.contextRunner.withPropertyValues("spring.thymeleaf.cache:false") - .run((context) -> { - assertThat(context.getBean(ThymeleafViewResolver.class).isCache()) - .isFalse(); - SpringResourceTemplateResolver templateResolver = context - .getBean(SpringResourceTemplateResolver.class); - assertThat(templateResolver.isCacheable()).isFalse(); - }); + this.contextRunner.withPropertyValues("spring.thymeleaf.cache:false").run((context) -> { + assertThat(context.getBean(ThymeleafViewResolver.class).isCache()).isFalse(); + SpringResourceTemplateResolver templateResolver = context.getBean(SpringResourceTemplateResolver.class); + assertThat(templateResolver.isCacheable()).isFalse(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java index da6be91eb66..af7c1706fcb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java @@ -40,29 +40,28 @@ public class ThymeleafTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertThat(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isFalse(); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomPrefix() { - this.environment.setProperty("spring.thymeleaf.prefix", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.thymeleaf.prefix", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf"); - assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java index 3c0ff0090b8..9969859b2ee 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java @@ -68,15 +68,11 @@ public class TransactionAutoConfigurationTests { @Test public void singleTransactionManager() { - load(new Class[] { DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class }, + load(new Class[] { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class }, "spring.datasource.initialization-mode:never"); - PlatformTransactionManager transactionManager = this.context - .getBean(PlatformTransactionManager.class); - TransactionTemplate transactionTemplate = this.context - .getBean(TransactionTemplate.class); - assertThat(transactionTemplate.getTransactionManager()) - .isSameAs(transactionManager); + PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.class); + TransactionTemplate transactionTemplate = this.context.getBean(TransactionTemplate.class); + assertThat(transactionTemplate.getTransactionManager()).isSameAs(transactionManager); } @Test @@ -88,8 +84,7 @@ public class TransactionAutoConfigurationTests { @Test public void customTransactionManager() { load(CustomTransactionManagerConfiguration.class); - Map beans = this.context - .getBeansOfType(TransactionTemplate.class); + Map beans = this.context.getBeansOfType(TransactionTemplate.class); assertThat(beans).hasSize(1); assertThat(beans.containsKey("transactionTemplateFoo")).isTrue(); } @@ -97,50 +92,39 @@ public class TransactionAutoConfigurationTests { @Test public void platformTransactionManagerCustomizers() { load(SeveralTransactionManagersConfiguration.class); - TransactionManagerCustomizers customizers = this.context - .getBean(TransactionManagerCustomizers.class); - List field = (List) ReflectionTestUtils.getField(customizers, - "customizers"); + TransactionManagerCustomizers customizers = this.context.getBean(TransactionManagerCustomizers.class); + List field = (List) ReflectionTestUtils.getField(customizers, "customizers"); assertThat(field).hasSize(1).first().isInstanceOf(TransactionProperties.class); } @Test public void transactionNotManagedWithNoTransactionManager() { load(BaseConfiguration.class); - assertThat(this.context.getBean(TransactionalService.class).isTransactionActive()) - .isFalse(); + assertThat(this.context.getBean(TransactionalService.class).isTransactionActive()).isFalse(); } @Test public void transactionManagerUsesCglibByDefault() { load(TransactionManagersConfiguration.class); - assertThat(this.context.getBean(AnotherServiceImpl.class).isTransactionActive()) - .isTrue(); - assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)) - .hasSize(1); + assertThat(this.context.getBean(AnotherServiceImpl.class).isTransactionActive()).isTrue(); + assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(1); } @Test public void transactionManagerCanBeConfiguredToJdkProxy() { - load(TransactionManagersConfiguration.class, - "spring.aop.proxy-target-class=false"); - assertThat(this.context.getBean(AnotherService.class).isTransactionActive()) - .isTrue(); + load(TransactionManagersConfiguration.class, "spring.aop.proxy-target-class=false"); + assertThat(this.context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(this.context.getBeansOfType(AnotherServiceImpl.class)).hasSize(0); - assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)) - .hasSize(0); + assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(0); } @Test public void customEnableTransactionManagementTakesPrecedence() { - load(new Class[] { CustomTransactionManagementConfiguration.class, - TransactionManagersConfiguration.class }, + load(new Class[] { CustomTransactionManagementConfiguration.class, TransactionManagersConfiguration.class }, "spring.aop.proxy-target-class=true"); - assertThat(this.context.getBean(AnotherService.class).isTransactionActive()) - .isTrue(); + assertThat(this.context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(this.context.getBeansOfType(AnotherServiceImpl.class)).hasSize(0); - assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)) - .hasSize(0); + assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(0); } private void load(Class config, String... environment) { @@ -180,8 +164,7 @@ public class TransactionAutoConfigurationTests { static class CustomTransactionManagerConfiguration { @Bean - public TransactionTemplate transactionTemplateFoo( - PlatformTransactionManager transactionManager) { + public TransactionTemplate transactionTemplateFoo(PlatformTransactionManager transactionManager) { return new TransactionTemplate(transactionManager); } @@ -218,9 +201,8 @@ public class TransactionAutoConfigurationTests { @Bean public DataSource dataSource() { - return DataSourceBuilder.create() - .driverClassName("org.hsqldb.jdbc.JDBCDriver") - .url("jdbc:hsqldb:mem:tx").username("sa").build(); + return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:tx") + .username("sa").build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java index 1d7e2c1a7b3..75e407df9cc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java @@ -36,8 +36,7 @@ public class TransactionManagerCustomizersTests { @Test public void customizeWithNullCustomizersShouldDoNothing() { - new TransactionManagerCustomizers(null) - .customize(mock(PlatformTransactionManager.class)); + new TransactionManagerCustomizers(null).customize(mock(PlatformTransactionManager.class)); } @Test @@ -45,8 +44,7 @@ public class TransactionManagerCustomizersTests { List> list = new ArrayList<>(); list.add(new TestCustomizer<>()); list.add(new TestJtaCustomizer()); - TransactionManagerCustomizers customizers = new TransactionManagerCustomizers( - list); + TransactionManagerCustomizers customizers = new TransactionManagerCustomizers(list); customizers.customize(mock(PlatformTransactionManager.class)); customizers.customize(mock(JtaTransactionManager.class)); assertThat(list.get(0).getCount()).isEqualTo(2); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index 86af540d8c6..8fc29762798 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -84,8 +84,8 @@ public class JtaAutoConfigurationTests { @Test public void customPlatformTransactionManager() { - this.context = new AnnotationConfigApplicationContext( - CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.class, + JtaAutoConfiguration.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(JtaTransactionManager.class)); } @@ -98,14 +98,12 @@ public class JtaAutoConfigurationTests { this.context.refresh(); assertThat(this.context.getBeansOfType(JtaTransactionManager.class)).isEmpty(); assertThat(this.context.getBeansOfType(XADataSourceWrapper.class)).isEmpty(); - assertThat(this.context.getBeansOfType(XAConnectionFactoryWrapper.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(XAConnectionFactoryWrapper.class)).isEmpty(); } @Test public void atomikosSanityCheck() { - this.context = new AnnotationConfigApplicationContext(JtaProperties.class, - AtomikosJtaConfiguration.class); + this.context = new AnnotationConfigApplicationContext(JtaProperties.class, AtomikosJtaConfiguration.class); this.context.getBean(AtomikosProperties.class); this.context.getBean(UserTransactionService.class); this.context.getBean(UserTransactionManager.class); @@ -118,8 +116,7 @@ public class JtaAutoConfigurationTests { @Test public void bitronixSanityCheck() { - this.context = new AnnotationConfigApplicationContext(JtaProperties.class, - BitronixJtaConfiguration.class); + this.context = new AnnotationConfigApplicationContext(JtaProperties.class, BitronixJtaConfiguration.class); this.context.getBean(bitronix.tm.Configuration.class); this.context.getBean(TransactionManager.class); this.context.getBean(XADataSourceWrapper.class); @@ -130,32 +127,26 @@ public class JtaAutoConfigurationTests { @Test public void defaultBitronixServerId() throws UnknownHostException { - this.context = new AnnotationConfigApplicationContext( - BitronixJtaConfiguration.class); - String serverId = this.context.getBean(bitronix.tm.Configuration.class) - .getServerId(); + this.context = new AnnotationConfigApplicationContext(BitronixJtaConfiguration.class); + String serverId = this.context.getBean(bitronix.tm.Configuration.class).getServerId(); assertThat(serverId).isEqualTo(InetAddress.getLocalHost().getHostAddress()); } @Test public void customBitronixServerId() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.jta.transactionManagerId:custom") - .applyTo(this.context); + TestPropertyValues.of("spring.jta.transactionManagerId:custom").applyTo(this.context); this.context.register(BitronixJtaConfiguration.class); this.context.refresh(); - String serverId = this.context.getBean(bitronix.tm.Configuration.class) - .getServerId(); + String serverId = this.context.getBean(bitronix.tm.Configuration.class).getServerId(); assertThat(serverId).isEqualTo("custom"); } @Test - public void defaultAtomikosTransactionManagerName(@TempDir Path dir) - throws IOException { + public void defaultAtomikosTransactionManagerName(@TempDir Path dir) throws IOException { this.context = new AnnotationConfigApplicationContext(); File logs = new File(dir.toFile(), "jta"); - TestPropertyValues.of("spring.jta.logDir:" + logs.getAbsolutePath()) - .applyTo(this.context); + TestPropertyValues.of("spring.jta.logDir:" + logs.getAbsolutePath()).applyTo(this.context); this.context.register(AtomikosJtaConfiguration.class); this.context.refresh(); @@ -166,14 +157,11 @@ public class JtaAutoConfigurationTests { @Test public void atomikosConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues - .of("spring.jta.atomikos.connectionfactory.minPoolSize:5", - "spring.jta.atomikos.connectionfactory.maxPoolSize:10") - .applyTo(this.context); + TestPropertyValues.of("spring.jta.atomikos.connectionfactory.minPoolSize:5", + "spring.jta.atomikos.connectionfactory.maxPoolSize:10").applyTo(this.context); this.context.register(AtomikosJtaConfiguration.class, PoolConfiguration.class); this.context.refresh(); - AtomikosConnectionFactoryBean connectionFactory = this.context - .getBean(AtomikosConnectionFactoryBean.class); + AtomikosConnectionFactoryBean connectionFactory = this.context.getBean(AtomikosConnectionFactoryBean.class); assertThat(connectionFactory.getMinPoolSize()).isEqualTo(5); assertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10); } @@ -181,14 +169,11 @@ public class JtaAutoConfigurationTests { @Test public void bitronixConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues - .of("spring.jta.bitronix.connectionfactory.minPoolSize:5", - "spring.jta.bitronix.connectionfactory.maxPoolSize:10") - .applyTo(this.context); + TestPropertyValues.of("spring.jta.bitronix.connectionfactory.minPoolSize:5", + "spring.jta.bitronix.connectionfactory.maxPoolSize:10").applyTo(this.context); this.context.register(BitronixJtaConfiguration.class, PoolConfiguration.class); this.context.refresh(); - PoolingConnectionFactoryBean connectionFactory = this.context - .getBean(PoolingConnectionFactoryBean.class); + PoolingConnectionFactoryBean connectionFactory = this.context.getBean(PoolingConnectionFactoryBean.class); assertThat(connectionFactory.getMinPoolSize()).isEqualTo(5); assertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10); } @@ -197,13 +182,11 @@ public class JtaAutoConfigurationTests { public void atomikosDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.jta.atomikos.datasource.minPoolSize:5", - "spring.jta.atomikos.datasource.maxPoolSize:10") + .of("spring.jta.atomikos.datasource.minPoolSize:5", "spring.jta.atomikos.datasource.maxPoolSize:10") .applyTo(this.context); this.context.register(AtomikosJtaConfiguration.class, PoolConfiguration.class); this.context.refresh(); - AtomikosDataSourceBean dataSource = this.context - .getBean(AtomikosDataSourceBean.class); + AtomikosDataSourceBean dataSource = this.context.getBean(AtomikosDataSourceBean.class); assertThat(dataSource.getMinPoolSize()).isEqualTo(5); assertThat(dataSource.getMaxPoolSize()).isEqualTo(10); } @@ -212,13 +195,11 @@ public class JtaAutoConfigurationTests { public void bitronixDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.jta.bitronix.datasource.minPoolSize:5", - "spring.jta.bitronix.datasource.maxPoolSize:10") + .of("spring.jta.bitronix.datasource.minPoolSize:5", "spring.jta.bitronix.datasource.maxPoolSize:10") .applyTo(this.context); this.context.register(BitronixJtaConfiguration.class, PoolConfiguration.class); this.context.refresh(); - PoolingDataSourceBean dataSource = this.context - .getBean(PoolingDataSourceBean.class); + PoolingDataSourceBean dataSource = this.context.getBean(PoolingDataSourceBean.class); assertThat(dataSource.getMinPoolSize()).isEqualTo(5); assertThat(dataSource.getMaxPoolSize()).isEqualTo(10); } @@ -227,14 +208,11 @@ public class JtaAutoConfigurationTests { public void atomikosCustomizeJtaTransactionManagerUsingProperties() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") + .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") .applyTo(this.context); - this.context.register(AtomikosJtaConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(AtomikosJtaConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - JtaTransactionManager transactionManager = this.context - .getBean(JtaTransactionManager.class); + JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @@ -243,14 +221,11 @@ public class JtaAutoConfigurationTests { public void bitronixCustomizeJtaTransactionManagerUsingProperties() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") + .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") .applyTo(this.context); - this.context.register(BitronixJtaConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(BitronixJtaConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - JtaTransactionManager transactionManager = this.context - .getBean(JtaTransactionManager.class); + JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @@ -269,8 +244,7 @@ public class JtaAutoConfigurationTests { public static class PoolConfiguration { @Bean - public ConnectionFactory pooledConnectionFactory( - XAConnectionFactoryWrapper wrapper) throws Exception { + public ConnectionFactory pooledConnectionFactory(XAConnectionFactoryWrapper wrapper) throws Exception { XAConnectionFactory connectionFactory = mock(XAConnectionFactory.class); XAConnection connection = mock(XAConnection.class); XASession session = mock(XASession.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java index 04bebc536d3..0afca31c598 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java @@ -123,8 +123,8 @@ public class ValidationAutoConfigurationTests { String[] springValidatorNames = this.context .getBeanNamesForType(org.springframework.validation.Validator.class); assertThat(jsrValidatorNames).containsExactly("defaultValidator"); - assertThat(springValidatorNames).containsExactly("customValidator", - "anotherCustomValidator", "defaultValidator"); + assertThat(springValidatorNames).containsExactly("customValidator", "anotherCustomValidator", + "defaultValidator"); Validator jsrValidator = this.context.getBean(Validator.class); org.springframework.validation.Validator springValidator = this.context .getBean(org.springframework.validation.Validator.class); @@ -140,14 +140,13 @@ public class ValidationAutoConfigurationTests { String[] springValidatorNames = this.context .getBeanNamesForType(org.springframework.validation.Validator.class); assertThat(jsrValidatorNames).containsExactly("defaultValidator"); - assertThat(springValidatorNames).containsExactly("customValidator", - "anotherCustomValidator", "defaultValidator"); + assertThat(springValidatorNames).containsExactly("customValidator", "anotherCustomValidator", + "defaultValidator"); Validator jsrValidator = this.context.getBean(Validator.class); org.springframework.validation.Validator springValidator = this.context .getBean(org.springframework.validation.Validator.class); assertThat(jsrValidator).isInstanceOf(LocalValidatorFactoryBean.class); - assertThat(springValidator) - .isEqualTo(this.context.getBean("anotherCustomValidator")); + assertThat(springValidator).isEqualTo(this.context.getBean("anotherCustomValidator")); assertThat(isPrimaryBean("defaultValidator")).isFalse(); } @@ -157,53 +156,44 @@ public class ValidationAutoConfigurationTests { assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); SampleService service = this.context.getBean(SampleService.class); service.doSomething("Valid"); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething("KO")); + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> service.doSomething("KO")); } @Test public void validationUsesCglibProxy() { load(DefaultAnotherSampleService.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - DefaultAnotherSampleService service = this.context - .getBean(DefaultAnotherSampleService.class); + DefaultAnotherSampleService service = this.context.getBean(DefaultAnotherSampleService.class); service.doSomething(42); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething(2)); + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> service.doSomething(2)); } @Test public void validationCanBeConfiguredToUseJdkProxy() { - load(AnotherSampleServiceConfiguration.class, - "spring.aop.proxy-target-class=false"); + load(AnotherSampleServiceConfiguration.class, "spring.aop.proxy-target-class=false"); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(this.context.getBeansOfType(DefaultAnotherSampleService.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); AnotherSampleService service = this.context.getBean(AnotherSampleService.class); service.doSomething(42); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething(2)); + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> service.doSomething(2)); } @Test public void userDefinedMethodValidationPostProcessorTakesPrecedence() { load(SampleConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - Object userMethodValidationPostProcessor = this.context - .getBean("testMethodValidationPostProcessor"); + Object userMethodValidationPostProcessor = this.context.getBean("testMethodValidationPostProcessor"); assertThat(this.context.getBean(MethodValidationPostProcessor.class)) .isSameAs(userMethodValidationPostProcessor); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)) - .hasSize(1); - assertThat(this.context.getBean(Validator.class)).isNotSameAs(ReflectionTestUtils - .getField(userMethodValidationPostProcessor, "validator")); + assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); + assertThat(this.context.getBean(Validator.class)) + .isNotSameAs(ReflectionTestUtils.getField(userMethodValidationPostProcessor, "validator")); } @Test public void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() { load(CustomValidatorConfiguration.class); - assertThat(this.context.getBean(TestBeanPostProcessor.class).postProcessed) - .contains("someService"); + assertThat(this.context.getBean(TestBeanPostProcessor.class).postProcessed).contains("someService"); } private boolean isPrimaryBean(String beanName) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java index 2a28550ec86..6bb161ee81c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java @@ -50,11 +50,9 @@ public class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests @Test public void missingElDependencyIsTolerated() { - this.context = new AnnotationConfigApplicationContext( - ValidationAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(ValidationAutoConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java index 269df751c64..f7711adb541 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java @@ -49,11 +49,9 @@ public class ValidationAutoConfigurationWithoutValidatorTests { @Test public void validationIsDisabled() { - this.context = new AnnotationConfigApplicationContext( - ValidationAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(ValidationAutoConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).isEmpty(); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).isEmpty(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java index a74ae176bba..6ac78a28ff8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java @@ -50,45 +50,37 @@ public class ValidatorAdapterTests { @Test public void wrapLocalValidatorFactoryBean() { - this.contextRunner.withUserConfiguration(LocalValidatorFactoryBeanConfig.class) - .run((context) -> { - ValidatorAdapter wrapper = context.getBean(ValidatorAdapter.class); - assertThat(wrapper.supports(SampleData.class)).isTrue(); - MapBindingResult errors = new MapBindingResult( - new HashMap(), "test"); - wrapper.validate(new SampleData(40), errors); - assertThat(errors.getErrorCount()).isEqualTo(1); - }); + this.contextRunner.withUserConfiguration(LocalValidatorFactoryBeanConfig.class).run((context) -> { + ValidatorAdapter wrapper = context.getBean(ValidatorAdapter.class); + assertThat(wrapper.supports(SampleData.class)).isTrue(); + MapBindingResult errors = new MapBindingResult(new HashMap(), "test"); + wrapper.validate(new SampleData(40), errors); + assertThat(errors.getErrorCount()).isEqualTo(1); + }); } @Test public void wrapperInvokesCallbackOnNonManagedBean() { - this.contextRunner.withUserConfiguration(NonManagedBeanConfig.class) - .run((context) -> { - LocalValidatorFactoryBean validator = context - .getBean(NonManagedBeanConfig.class).validator; - verify(validator, times(1)) - .setApplicationContext(any(ApplicationContext.class)); - verify(validator, times(1)).afterPropertiesSet(); - verify(validator, never()).destroy(); - context.close(); - verify(validator, times(1)).destroy(); - }); + this.contextRunner.withUserConfiguration(NonManagedBeanConfig.class).run((context) -> { + LocalValidatorFactoryBean validator = context.getBean(NonManagedBeanConfig.class).validator; + verify(validator, times(1)).setApplicationContext(any(ApplicationContext.class)); + verify(validator, times(1)).afterPropertiesSet(); + verify(validator, never()).destroy(); + context.close(); + verify(validator, times(1)).destroy(); + }); } @Test public void wrapperDoesNotInvokeCallbackOnManagedBean() { - this.contextRunner.withUserConfiguration(ManagedBeanConfig.class) - .run((context) -> { - LocalValidatorFactoryBean validator = context - .getBean(ManagedBeanConfig.class).validator; - verify(validator, never()) - .setApplicationContext(any(ApplicationContext.class)); - verify(validator, never()).afterPropertiesSet(); - verify(validator, never()).destroy(); - context.close(); - verify(validator, never()).destroy(); - }); + this.contextRunner.withUserConfiguration(ManagedBeanConfig.class).run((context) -> { + LocalValidatorFactoryBean validator = context.getBean(ManagedBeanConfig.class).validator; + verify(validator, never()).setApplicationContext(any(ApplicationContext.class)); + verify(validator, never()).afterPropertiesSet(); + verify(validator, never()).destroy(); + context.close(); + verify(validator, never()).destroy(); + }); } @Test @@ -96,10 +88,9 @@ public class ValidatorAdapterTests { ClassPathResource hibernateValidator = new ClassPathResource( "META-INF/services/javax.validation.spi.ValidationProvider"); this.contextRunner - .withClassLoader(new FilteredClassLoader( - FilteredClassLoader.ClassPathResourceFilter - .of(hibernateValidator), - FilteredClassLoader.PackageFilter.of("org.hibernate.validator"))) + .withClassLoader( + new FilteredClassLoader(FilteredClassLoader.ClassPathResourceFilter.of(hibernateValidator), + FilteredClassLoader.PackageFilter.of("org.hibernate.validator"))) .run((context) -> ValidatorAdapter.get(context, null)); } @@ -121,8 +112,7 @@ public class ValidatorAdapterTests { @Configuration(proxyBeanMethods = false) static class NonManagedBeanConfig { - private final LocalValidatorFactoryBean validator = mock( - LocalValidatorFactoryBean.class); + private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.class); @Bean public ValidatorAdapter wrapper() { @@ -134,8 +124,7 @@ public class ValidatorAdapterTests { @Configuration(proxyBeanMethods = false) static class ManagedBeanConfig { - private final LocalValidatorFactoryBean validator = mock( - LocalValidatorFactoryBean.class); + private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.class); @Bean public ValidatorAdapter wrapper() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java index 985e0aac70d..92a0081cd4b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java @@ -41,18 +41,15 @@ public class ResourcePropertiesBindingTests { @Test public void staticLocationsExpandArray() { this.contextRunner - .withPropertyValues( - "spring.resources.static-locations[0]=classpath:/one/", + .withPropertyValues("spring.resources.static-locations[0]=classpath:/one/", "spring.resources.static-locations[1]=classpath:/two", "spring.resources.static-locations[2]=classpath:/three/", "spring.resources.static-locations[3]=classpath:/four", "spring.resources.static-locations[4]=classpath:/five/", "spring.resources.static-locations[5]=classpath:/six") - .run(assertResourceProperties( - (properties) -> assertThat(properties.getStaticLocations()) - .contains("classpath:/one/", "classpath:/two/", - "classpath:/three/", "classpath:/four/", - "classpath:/five/", "classpath:/six/"))); + .run(assertResourceProperties((properties) -> assertThat(properties.getStaticLocations()).contains( + "classpath:/one/", "classpath:/two/", "classpath:/three/", "classpath:/four/", + "classpath:/five/", "classpath:/six/"))); } private ContextConsumer assertResourceProperties( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java index 390f98310fa..2d5c9d358f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java @@ -74,8 +74,7 @@ public class ResourcePropertiesTests { @Test public void emptyCacheControl() { - CacheControl cacheControl = this.properties.getCache().getCachecontrol() - .toHttpCacheControl(); + CacheControl cacheControl = this.properties.getCache().getCachecontrol().toHttpCacheControl(); assertThat(cacheControl).isNull(); } @@ -92,8 +91,8 @@ public class ResourcePropertiesTests { properties.setStaleIfError(Duration.ofSeconds(6)); properties.setStaleWhileRevalidate(Duration.ofSeconds(7)); CacheControl cacheControl = properties.toHttpCacheControl(); - assertThat(cacheControl.getHeaderValue()).isEqualTo( - "max-age=4, must-revalidate, no-transform, public, private, proxy-revalidate," + assertThat(cacheControl.getHeaderValue()) + .isEqualTo("max-age=4, must-revalidate, no-transform, public, private, proxy-revalidate," + " s-maxage=5, stale-if-error=6, stale-while-revalidate=7"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index adb396d6795..deac0ede6f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -82,8 +82,7 @@ public class ServerPropertiesTests { @Test public void testAddressBinding() throws Exception { bind("server.address", "127.0.0.1"); - assertThat(this.properties.getAddress()) - .isEqualTo(InetAddress.getByName("127.0.0.1")); + assertThat(this.properties.getAddress()).isEqualTo(InetAddress.getByName("127.0.0.1")); } @Test @@ -106,8 +105,7 @@ public class ServerPropertiesTests { @Test public void testConnectionTimeout() { bind("server.connection-timeout", "60s"); - assertThat(this.properties.getConnectionTimeout()) - .isEqualTo(Duration.ofMillis(60000)); + assertThat(this.properties.getConnectionTimeout()).isEqualTo(Duration.ofMillis(60000)); } @Test @@ -146,10 +144,8 @@ public class ServerPropertiesTests { assertThat(accesslog.isRequestAttributesEnabled()).isTrue(); assertThat(tomcat.getRemoteIpHeader()).isEqualTo("Remote-Ip"); assertThat(tomcat.getProtocolHeader()).isEqualTo("X-Forwarded-Protocol"); - assertThat(tomcat.getInternalProxies()) - .isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); - assertThat(tomcat.getBackgroundProcessorDelay()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(tomcat.getInternalProxies()).isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); + assertThat(tomcat.getBackgroundProcessorDelay()).isEqualTo(Duration.ofSeconds(10)); } @Test @@ -173,8 +169,7 @@ public class ServerPropertiesTests { @Test public void testContextPathWithTrailingWhitespace() { bind("server.servlet.context-path", "/assets/copy/ "); - assertThat(this.properties.getServlet().getContextPath()) - .isEqualTo("/assets/copy"); + assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets/copy"); } @Test @@ -186,29 +181,25 @@ public class ServerPropertiesTests { @Test public void testContextPathWithLeadingAndTrailingWhitespaceAndContextWithSpace() { bind("server.servlet.context-path", " /assets /copy/ "); - assertThat(this.properties.getServlet().getContextPath()) - .isEqualTo("/assets /copy"); + assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets /copy"); } @Test public void testCustomizeUriEncoding() { bind("server.tomcat.uri-encoding", "US-ASCII"); - assertThat(this.properties.getTomcat().getUriEncoding()) - .isEqualTo(StandardCharsets.US_ASCII); + assertThat(this.properties.getTomcat().getUriEncoding()).isEqualTo(StandardCharsets.US_ASCII); } @Test public void testCustomizeHeaderSize() { bind("server.max-http-header-size", "1MB"); - assertThat(this.properties.getMaxHttpHeaderSize()) - .isEqualTo(DataSize.ofMegabytes(1)); + assertThat(this.properties.getMaxHttpHeaderSize()).isEqualTo(DataSize.ofMegabytes(1)); } @Test public void testCustomizeHeaderSizeUseBytesByDefault() { bind("server.max-http-header-size", "1024"); - assertThat(this.properties.getMaxHttpHeaderSize()) - .isEqualTo(DataSize.ofKilobytes(1)); + assertThat(this.properties.getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(1)); } @Test @@ -240,34 +231,28 @@ public class ServerPropertiesTests { assertThat(jetty.getAccesslog().getFileDateFormat()).isEqualTo("yyyymmdd"); assertThat(jetty.getAccesslog().getRetentionPeriod()).isEqualTo(4); assertThat(jetty.getAccesslog().isAppend()).isTrue(); - assertThat(jetty.getAccesslog().getCustomFormat()) - .isEqualTo("{client}a - %u %t \"%r\" %s %O"); - assertThat(jetty.getAccesslog().getIgnorePaths()).containsExactly("/a/path", - "/b/path"); + assertThat(jetty.getAccesslog().getCustomFormat()).isEqualTo("{client}a - %u %t \"%r\" %s %O"); + assertThat(jetty.getAccesslog().getIgnorePaths()).containsExactly("/a/path", "/b/path"); } @Test public void tomcatAcceptCountMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getAcceptCount()) - .isEqualTo(getDefaultProtocol().getAcceptCount()); + assertThat(this.properties.getTomcat().getAcceptCount()).isEqualTo(getDefaultProtocol().getAcceptCount()); } @Test public void tomcatProcessorCacheMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getProcessorCache()) - .isEqualTo(getDefaultProtocol().getProcessorCache()); + assertThat(this.properties.getTomcat().getProcessorCache()).isEqualTo(getDefaultProtocol().getProcessorCache()); } @Test public void tomcatMaxConnectionsMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getMaxConnections()) - .isEqualTo(getDefaultProtocol().getMaxConnections()); + assertThat(this.properties.getTomcat().getMaxConnections()).isEqualTo(getDefaultProtocol().getMaxConnections()); } @Test public void tomcatMaxThreadsMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getMaxThreads()) - .isEqualTo(getDefaultProtocol().getMaxThreads()); + assertThat(this.properties.getTomcat().getMaxThreads()).isEqualTo(getDefaultProtocol().getMaxThreads()); } @Test @@ -284,8 +269,8 @@ public class ServerPropertiesTests { @Test public void tomcatBackgroundProcessorDelayMatchesEngineDefault() { - assertThat(this.properties.getTomcat().getBackgroundProcessorDelay()).isEqualTo( - Duration.ofSeconds((new StandardEngine().getBackgroundProcessorDelay()))); + assertThat(this.properties.getTomcat().getBackgroundProcessorDelay()) + .isEqualTo(Duration.ofSeconds((new StandardEngine().getBackgroundProcessorDelay()))); } @Test @@ -308,9 +293,8 @@ public class ServerPropertiesTests { @Test public void tomcatAccessLogRequestAttributesEnabledMatchesDefault() { - assertThat( - this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) - .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); + assertThat(this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) + .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); } @Test @@ -322,21 +306,19 @@ public class ServerPropertiesTests { @Test public void jettyMaxHttpPostSizeMatchesDefault() throws Exception { JettyServletWebServerFactory jettyFactory = new JettyServletWebServerFactory(0); - JettyWebServer jetty = (JettyWebServer) jettyFactory.getWebServer( - (ServletContextInitializer) (servletContext) -> servletContext + JettyWebServer jetty = (JettyWebServer) jettyFactory + .getWebServer((ServletContextInitializer) (servletContext) -> servletContext .addServlet("formPost", new HttpServlet() { @Override - protected void doPost(HttpServletRequest req, - HttpServletResponse resp) + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getParameterMap(); } }).addMapping("/form")); jetty.start(); - org.eclipse.jetty.server.Connector connector = jetty.getServer() - .getConnectors()[0]; + org.eclipse.jetty.server.Connector connector = jetty.getServer().getConnectors()[0]; final AtomicReference failure = new AtomicReference<>(); connector.addBean(new HttpChannel.Listener() { @@ -369,17 +351,12 @@ public class ServerPropertiesTests { data.append("a"); } body.add("data", data.toString()); - HttpEntity> entity = new HttpEntity<>(body, - headers); - template.postForEntity( - URI.create("http://localhost:" + jetty.getPort() + "/form"), entity, - Void.class); + HttpEntity> entity = new HttpEntity<>(body, headers); + template.postForEntity(URI.create("http://localhost:" + jetty.getPort() + "/form"), entity, Void.class); assertThat(failure.get()).isNotNull(); String message = failure.get().getCause().getMessage(); - int defaultMaxPostSize = Integer - .valueOf(message.substring(message.lastIndexOf(' ')).trim()); - assertThat(this.properties.getJetty().getMaxHttpPostSize().toBytes()) - .isEqualTo(defaultMaxPostSize); + int defaultMaxPostSize = Integer.valueOf(message.substring(message.lastIndexOf(' ')).trim()); + assertThat(this.properties.getJetty().getMaxHttpPostSize().toBytes()).isEqualTo(defaultMaxPostSize); } finally { jetty.stop(); @@ -397,8 +374,7 @@ public class ServerPropertiesTests { } private AbstractProtocol getDefaultProtocol() throws Exception { - return (AbstractProtocol) Class - .forName(TomcatServletWebServerFactory.DEFAULT_PROTOCOL).newInstance(); + return (AbstractProtocol) Class.forName(TomcatServletWebServerFactory.DEFAULT_PROTOCOL).newInstance(); } private void bind(String name, String value) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java index ddd0ade24ae..b6c6290a9a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java @@ -48,21 +48,17 @@ import static org.mockito.Mockito.verify; public class RestTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(RestTemplateAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); @Test public void restTemplateWhenMessageConvertersDefinedShouldHaveMessageConverters() { - this.contextRunner - .withConfiguration(AutoConfigurations - .of(HttpMessageConvertersAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .withUserConfiguration(RestTemplateConfig.class).run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class); - List> converters = context - .getBean(HttpMessageConverters.class).getConverters(); - assertThat(restTemplate.getMessageConverters()) - .containsExactlyElementsOf(converters); + List> converters = context.getBean(HttpMessageConverters.class) + .getConverters(); + assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); assertThat(restTemplate.getRequestFactory()) .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); }); @@ -70,36 +66,30 @@ public class RestTemplateAutoConfigurationTests { @Test public void restTemplateWhenNoMessageConvertersDefinedShouldHaveDefaultMessageConverters() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters().size()) - .isEqualTo(new RestTemplate().getMessageConverters().size()); - }); + this.contextRunner.withUserConfiguration(RestTemplateConfig.class).run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters().size()) + .isEqualTo(new RestTemplate().getMessageConverters().size()); + }); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { - this.contextRunner - .withConfiguration(AutoConfigurations - .of(HttpMessageConvertersAutoConfiguration.class)) - .withUserConfiguration(CustomHttpMessageConverter.class, - RestTemplateConfig.class) - .run((context) -> { + this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .withUserConfiguration(CustomHttpMessageConverter.class, RestTemplateConfig.class).run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()) - .extracting(HttpMessageConverter::getClass) + assertThat(restTemplate.getMessageConverters()).extracting(HttpMessageConverter::getClass) .contains((Class) CustomHttpMessageConverter.class); }); } @Test public void restTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class, - CustomRestTemplateBuilderConfig.class).run((context) -> { + this.contextRunner.withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderConfig.class) + .run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class); assertThat(restTemplate.getMessageConverters()).hasSize(1); @@ -110,12 +100,11 @@ public class RestTemplateAutoConfigurationTests { @Test public void restTemplateShouldApplyCustomizer() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class, - RestTemplateCustomizerConfig.class).run((context) -> { + this.contextRunner.withUserConfiguration(RestTemplateConfig.class, RestTemplateCustomizerConfig.class) + .run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class); - RestTemplateCustomizer customizer = context - .getBean(RestTemplateCustomizer.class); + RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); verify(customizer).customize(restTemplate); }); } @@ -128,20 +117,15 @@ public class RestTemplateAutoConfigurationTests { @Test public void whenServletWebApplicationRestTemplateBuilderIsConfigured() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(RestTemplateBuilder.class)); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(RestTemplateBuilder.class)); } @Test public void whenReactiveWebApplicationRestTemplateBuilderIsNotConfigured() { new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(RestTemplateBuilder.class)); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(RestTemplateBuilder.class)); } @Configuration(proxyBeanMethods = false) @@ -190,8 +174,7 @@ public class RestTemplateAutoConfigurationTests { @Bean public RestTemplateBuilder restTemplateBuilder() { - return new RestTemplateBuilder() - .messageConverters(new CustomHttpMessageConverter()); + return new RestTemplateBuilder().messageConverters(new CustomHttpMessageConverter()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java index a59f47af57d..b1cdfb3b7f1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java @@ -63,23 +63,20 @@ public class JettyWebServerFactoryCustomizerTests { this.environment = new MockEnvironment(); this.serverProperties = new ServerProperties(); ConfigurationPropertySources.attach(this.environment); - this.customizer = new JettyWebServerFactoryCustomizer(this.environment, - this.serverProperties); + this.customizer = new JettyWebServerFactoryCustomizer(this.environment, this.serverProperties); } @Test public void deduceUseForwardHeaders() { this.environment.setProperty("DYNO", "-"); - ConfigurableJettyWebServerFactory factory = mock( - ConfigurableJettyWebServerFactory.class); + ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(true); } @Test public void defaultUseForwardHeaders() { - ConfigurableJettyWebServerFactory factory = mock( - ConfigurableJettyWebServerFactory.class); + ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(false); } @@ -87,18 +84,13 @@ public class JettyWebServerFactoryCustomizerTests { @Test public void accessLogCanBeCustomized() throws IOException { File logFile = File.createTempFile("jetty_log", ".log"); - bind("server.jetty.accesslog.enabled=true", - "server.jetty.accesslog.format=extended_ncsa", - "server.jetty.accesslog.filename=" - + logFile.getAbsolutePath().replace("\\", "\\\\"), - "server.jetty.accesslog.file-date-format=yyyy-MM-dd", - "server.jetty.accesslog.retention-period=42", - "server.jetty.accesslog.append=true", - "server.jetty.accesslog.ignore-paths=/a/path,/b/path"); + bind("server.jetty.accesslog.enabled=true", "server.jetty.accesslog.format=extended_ncsa", + "server.jetty.accesslog.filename=" + logFile.getAbsolutePath().replace("\\", "\\\\"), + "server.jetty.accesslog.file-date-format=yyyy-MM-dd", "server.jetty.accesslog.retention-period=42", + "server.jetty.accesslog.append=true", "server.jetty.accesslog.ignore-paths=/a/path,/b/path"); JettyWebServer server = customizeAndGetServer(); CustomRequestLog requestLog = getRequestLog(server); - assertThat(requestLog.getFormatString()) - .isEqualTo(CustomRequestLog.EXTENDED_NCSA_FORMAT); + assertThat(requestLog.getFormatString()).isEqualTo(CustomRequestLog.EXTENDED_NCSA_FORMAT); assertThat(requestLog.getIgnorePaths().length).isEqualTo(2); assertThat(requestLog.getIgnorePaths()).containsExactly("/a/path", "/b/path"); RequestLogWriter logWriter = getLogWriter(requestLog); @@ -135,8 +127,7 @@ public class JettyWebServerFactoryCustomizerTests { @Test public void setUseForwardHeaders() { this.serverProperties.setUseForwardHeaders(true); - ConfigurableJettyWebServerFactory factory = mock( - ConfigurableJettyWebServerFactory.class); + ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(true); } @@ -172,8 +163,7 @@ public class JettyWebServerFactoryCustomizerTests { server.stop(); Connector[] connectors = server.getServer().getConnectors(); for (Connector connector : connectors) { - connector.getConnectionFactories().stream() - .filter((factory) -> factory instanceof ConnectionFactory) + connector.getConnectionFactories().stream().filter((factory) -> factory instanceof ConnectionFactory) .forEach((cf) -> { ConnectionFactory factory = (ConnectionFactory) cf; HttpConfiguration configuration = factory.getHttpConfiguration(); @@ -184,8 +174,7 @@ public class JettyWebServerFactoryCustomizerTests { } private void bind(String... inlinedProperties) { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - inlinedProperties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties); new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java index 65604064622..ec7907496bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java @@ -45,8 +45,7 @@ public class NettyWebServerFactoryCustomizerTests { this.environment = new MockEnvironment(); this.serverProperties = new ServerProperties(); ConfigurationPropertySources.attach(this.environment); - this.customizer = new NettyWebServerFactoryCustomizer(this.environment, - this.serverProperties); + this.customizer = new NettyWebServerFactoryCustomizer(this.environment, this.serverProperties); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java index b73a367f1b4..a0f830fa766 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java @@ -66,39 +66,38 @@ public class TomcatWebServerFactoryCustomizerTests { this.environment = new MockEnvironment(); this.serverProperties = new ServerProperties(); ConfigurationPropertySources.attach(this.environment); - this.customizer = new TomcatWebServerFactoryCustomizer(this.environment, - this.serverProperties); + this.customizer = new TomcatWebServerFactoryCustomizer(this.environment, this.serverProperties); } @Test public void defaultsAreConsistent() { - customizeAndRunServer((server) -> assertThat(((AbstractHttp11Protocol) server - .getTomcat().getConnector().getProtocolHandler()).getMaxSwallowSize()) - .isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize() - .toBytes())); + customizeAndRunServer((server) -> assertThat( + ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) + .getMaxSwallowSize()) + .isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize().toBytes())); } @Test public void customAcceptCount() { bind("server.tomcat.accept-count=10"); - customizeAndRunServer((server) -> assertThat(((AbstractProtocol) server - .getTomcat().getConnector().getProtocolHandler()).getAcceptCount()) + customizeAndRunServer((server) -> assertThat( + ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getAcceptCount()) .isEqualTo(10)); } @Test public void customProcessorCache() { bind("server.tomcat.processor-cache=100"); - customizeAndRunServer((server) -> assertThat(((AbstractProtocol) server - .getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) + customizeAndRunServer((server) -> assertThat( + ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) .isEqualTo(100)); } @Test public void unlimitedProcessorCache() { bind("server.tomcat.processor-cache=-1"); - customizeAndRunServer((server) -> assertThat(((AbstractProtocol) server - .getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) + customizeAndRunServer((server) -> assertThat( + ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) .isEqualTo(-1)); } @@ -106,23 +105,20 @@ public class TomcatWebServerFactoryCustomizerTests { public void customBackgroundProcessorDelay() { bind("server.tomcat.background-processor-delay=5"); TomcatWebServer server = customizeAndGetServer(); - assertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()) - .isEqualTo(5); + assertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()).isEqualTo(5); } @Test public void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); - customizeAndRunServer( - (server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()) - .isEqualTo(-1)); + customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); } @Test public void customMaxConnections() { bind("server.tomcat.max-connections=5"); - customizeAndRunServer((server) -> assertThat(((AbstractProtocol) server - .getTomcat().getConnector().getProtocolHandler()).getMaxConnections()) + customizeAndRunServer((server) -> assertThat( + ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getMaxConnections()) .isEqualTo(5)); } @@ -130,49 +126,46 @@ public class TomcatWebServerFactoryCustomizerTests { public void customMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=10000"); customizeAndRunServer( - (server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()) - .isEqualTo(10000)); + (server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(10000)); } @Test public void customMaxHttpHeaderSize() { bind("server.max-http-header-size=1KB"); - customizeAndRunServer((server) -> assertThat(((AbstractHttp11Protocol) server - .getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()) - .isEqualTo(DataSize.ofKilobytes(1).toBytes())); + customizeAndRunServer((server) -> assertThat( + ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) + .getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(1).toBytes())); } @Test public void customMaxHttpHeaderSizeIgnoredIfNegative() { bind("server.max-http-header-size=-1"); - customizeAndRunServer((server) -> assertThat(((AbstractHttp11Protocol) server - .getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()) - .isEqualTo(DataSize.ofKilobytes(8).toBytes())); + customizeAndRunServer((server) -> assertThat( + ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) + .getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes())); } @Test public void customMaxHttpHeaderSizeIgnoredIfZero() { bind("server.max-http-header-size=0"); - customizeAndRunServer((server) -> assertThat(((AbstractHttp11Protocol) server - .getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()) - .isEqualTo(DataSize.ofKilobytes(8).toBytes())); + customizeAndRunServer((server) -> assertThat( + ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) + .getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes())); } @Test public void customMaxSwallowSize() { bind("server.tomcat.max-swallow-size=10MB"); - customizeAndRunServer((server) -> assertThat(((AbstractHttp11Protocol) server - .getTomcat().getConnector().getProtocolHandler()).getMaxSwallowSize()) - .isEqualTo(DataSize.ofMegabytes(10).toBytes())); + customizeAndRunServer((server) -> assertThat( + ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) + .getMaxSwallowSize()).isEqualTo(DataSize.ofMegabytes(10).toBytes())); } @Test public void customRemoteIpValve() { bind("server.tomcat.remote-ip-header=x-my-remote-ip-header", - "server.tomcat.protocol-header=x-my-protocol-header", - "server.tomcat.internal-proxies=192.168.0.1", - "server.tomcat.port-header=x-my-forward-port", - "server.tomcat.protocol-header-https-value=On"); + "server.tomcat.protocol-header=x-my-protocol-header", "server.tomcat.internal-proxies=192.168.0.1", + "server.tomcat.port-header=x-my-forward-port", "server.tomcat.protocol-header-https-value=On"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(factory.getEngineValves()).hasSize(1); Valve valve = factory.getEngineValves().iterator().next(); @@ -214,8 +207,7 @@ public class TomcatWebServerFactoryCustomizerTests { @Test public void defaultRemoteIpValve() { // Since 1.1.7 you need to specify at least the protocol - bind("server.tomcat.protocol-header=X-Forwarded-Proto", - "server.tomcat.remote-ip-header=X-Forwarded-For"); + bind("server.tomcat.protocol-header=X-Forwarded-Proto", "server.tomcat.remote-ip-header=X-Forwarded-For"); testRemoteIpValveConfigured(); } @@ -240,8 +232,7 @@ public class TomcatWebServerFactoryCustomizerTests { + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" // 169.254/16 + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" // 127/8 + "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" // 172.16/12 - + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" - + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + "0:0:0:0:0:0:0:1|::1"; assertThat(remoteIpValve.getInternalProxies()).isEqualTo(expectedInternalProxies); } @@ -249,8 +240,7 @@ public class TomcatWebServerFactoryCustomizerTests { @Test public void defaultBackgroundProcessorDelay() { TomcatWebServer server = customizeAndGetServer(); - assertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()) - .isEqualTo(10); + assertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()).isEqualTo(10); } @Test @@ -282,11 +272,9 @@ public class TomcatWebServerFactoryCustomizerTests { @Test public void accessLogBufferingCanBeDisabled() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.buffered=false"); + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.buffered=false"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .isBuffered()).isFalse(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isBuffered()).isFalse(); } @Test @@ -301,25 +289,23 @@ public class TomcatWebServerFactoryCustomizerTests { public void accessLogFileDateFormatByDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getFileDateFormat()).isEqualTo(".yyyy-MM-dd"); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) + .isEqualTo(".yyyy-MM-dd"); } @Test public void accessLogFileDateFormatCanBeRedefined() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.file-date-format=yyyy-MM-dd.HH"); + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.file-date-format=yyyy-MM-dd.HH"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getFileDateFormat()).isEqualTo("yyyy-MM-dd.HH"); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) + .isEqualTo("yyyy-MM-dd.HH"); } @Test public void accessLogIsBufferedByDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .isBuffered()).isTrue(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isBuffered()).isTrue(); } @Test @@ -332,104 +318,86 @@ public class TomcatWebServerFactoryCustomizerTests { public void accessLogMaxDaysDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getMaxDays()).isEqualTo( - this.serverProperties.getTomcat().getAccesslog().getMaxDays()); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getMaxDays()) + .isEqualTo(this.serverProperties.getTomcat().getAccesslog().getMaxDays()); } @Test public void accessLogConditionCanBeSpecified() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.conditionIf=foo", + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.conditionIf=foo", "server.tomcat.accesslog.conditionUnless=bar"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getConditionIf()).isEqualTo("foo"); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getConditionUnless()).isEqualTo("bar"); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getCondition()).describedAs( - "value of condition should equal conditionUnless - provided for backwards compatibility") - .isEqualTo("bar"); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getConditionIf()).isEqualTo("foo"); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getConditionUnless()) + .isEqualTo("bar"); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getCondition()) + .describedAs("value of condition should equal conditionUnless - provided for backwards compatibility") + .isEqualTo("bar"); } @Test public void accessLogEncodingIsNullWhenNotSpecified() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getEncoding()).isNull(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getEncoding()).isNull(); } @Test public void accessLogEncodingCanBeSpecified() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.encoding=UTF-8"); + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.encoding=UTF-8"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getEncoding()).isEqualTo("UTF-8"); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getEncoding()).isEqualTo("UTF-8"); } @Test public void accessLogWithDefaultLocale() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getLocale()).isEqualTo(Locale.getDefault().toString()); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getLocale()) + .isEqualTo(Locale.getDefault().toString()); } @Test public void accessLogLocaleCanBeSpecified() { - String locale = "en_AU".equals(Locale.getDefault().toString()) ? "en_US" - : "en_AU"; - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.locale=" + locale); + String locale = "en_AU".equals(Locale.getDefault().toString()) ? "en_US" : "en_AU"; + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.locale=" + locale); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getLocale()).isEqualTo(locale); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getLocale()).isEqualTo(locale); } @Test public void accessLogCheckExistsDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .isCheckExists()).isFalse(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isCheckExists()).isFalse(); } @Test public void accessLogCheckExistsSpecified() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.check-exists=true"); + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.check-exists=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .isCheckExists()).isTrue(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isCheckExists()).isTrue(); } @Test public void accessLogMaxDaysCanBeRedefined() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.max-days=20"); + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.max-days=20"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getMaxDays()).isEqualTo(20); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getMaxDays()).isEqualTo(20); } @Test public void accessLogDoesNotUseIpv6CanonicalFormatByDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getIpv6Canonical()).isFalse(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getIpv6Canonical()).isFalse(); } @Test public void accessLogwithIpv6CanonicalSet() { - bind("server.tomcat.accesslog.enabled=true", - "server.tomcat.accesslog.ipv6-canonical=true"); + bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.ipv6-canonical=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); - assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()) - .getIpv6Canonical()).isTrue(); + assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getIpv6Canonical()).isTrue(); } @Test @@ -443,8 +411,7 @@ public class TomcatWebServerFactoryCustomizerTests { } private void bind(String... inlinedProperties) { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - inlinedProperties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties); new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java index b53613e3bd9..87121e32099 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java @@ -65,20 +65,15 @@ public class UndertowWebServerFactoryCustomizerTests { this.environment = new MockEnvironment(); this.serverProperties = new ServerProperties(); ConfigurationPropertySources.attach(this.environment); - this.customizer = new UndertowWebServerFactoryCustomizer(this.environment, - this.serverProperties); + this.customizer = new UndertowWebServerFactoryCustomizer(this.environment, this.serverProperties); } @Test public void customizeUndertowAccessLog() { - bind("server.undertow.accesslog.enabled=true", - "server.undertow.accesslog.pattern=foo", - "server.undertow.accesslog.prefix=test_log", - "server.undertow.accesslog.suffix=txt", - "server.undertow.accesslog.dir=test-logs", - "server.undertow.accesslog.rotate=false"); - ConfigurableUndertowWebServerFactory factory = mock( - ConfigurableUndertowWebServerFactory.class); + bind("server.undertow.accesslog.enabled=true", "server.undertow.accesslog.pattern=foo", + "server.undertow.accesslog.prefix=test_log", "server.undertow.accesslog.suffix=txt", + "server.undertow.accesslog.dir=test-logs", "server.undertow.accesslog.rotate=false"); + ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); verify(factory).setAccessLogEnabled(true); verify(factory).setAccessLogPattern("foo"); @@ -151,8 +146,7 @@ public class UndertowWebServerFactoryCustomizerTests { @Test public void customUrlCharset() { bind("server.undertow.url-charset=UTF-16"); - assertThat(boundServerOption(UndertowOptions.URL_CHARSET)) - .isEqualTo(StandardCharsets.UTF_16.name()); + assertThat(boundServerOption(UndertowOptions.URL_CHARSET)).isEqualTo(StandardCharsets.UTF_16.name()); } @Test @@ -164,16 +158,14 @@ public class UndertowWebServerFactoryCustomizerTests { @Test public void deduceUseForwardHeaders() { this.environment.setProperty("DYNO", "-"); - ConfigurableUndertowWebServerFactory factory = mock( - ConfigurableUndertowWebServerFactory.class); + ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(true); } @Test public void defaultUseForwardHeaders() { - ConfigurableUndertowWebServerFactory factory = mock( - ConfigurableUndertowWebServerFactory.class); + ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(false); } @@ -181,8 +173,7 @@ public class UndertowWebServerFactoryCustomizerTests { @Test public void setUseForwardHeaders() { this.serverProperties.setUseForwardHeaders(true); - ConfigurableUndertowWebServerFactory factory = mock( - ConfigurableUndertowWebServerFactory.class); + ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(true); } @@ -191,29 +182,24 @@ public class UndertowWebServerFactoryCustomizerTests { Builder builder = Undertow.builder(); ConfigurableUndertowWebServerFactory factory = mockFactory(builder); this.customizer.customize(factory); - OptionMap map = ((OptionMap.Builder) ReflectionTestUtils.getField(builder, - "serverOptions")).getMap(); + OptionMap map = ((OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions")).getMap(); return map.get(option); } private ConfigurableUndertowWebServerFactory mockFactory(Builder builder) { - ConfigurableUndertowWebServerFactory factory = mock( - ConfigurableUndertowWebServerFactory.class); + ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); willAnswer((invocation) -> { Object argument = invocation.getArgument(0); Arrays.stream((argument instanceof UndertowBuilderCustomizer) - ? new UndertowBuilderCustomizer[] { - (UndertowBuilderCustomizer) argument } - : (UndertowBuilderCustomizer[]) argument) - .forEach((customizer) -> customizer.customize(builder)); + ? new UndertowBuilderCustomizer[] { (UndertowBuilderCustomizer) argument } + : (UndertowBuilderCustomizer[]) argument).forEach((customizer) -> customizer.customize(builder)); return null; }).given(factory).addBuilderCustomizers(any()); return factory; } private void bind(String... inlinedProperties) { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - inlinedProperties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties); new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java index 8170fa0ca0f..b3c221af009 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java @@ -38,18 +38,15 @@ public class WebConversionServiceTests { Date date = new DateTime(2018, 1, 1, 20, 30).toDate(); assertThat(conversionService.convert(date, String.class)).isEqualTo("01*01*2018"); LocalDate jodaDate = LocalDate.fromDateFields(date); - assertThat(conversionService.convert(jodaDate, String.class)) - .isEqualTo("01*01*2018"); + assertThat(conversionService.convert(jodaDate, String.class)).isEqualTo("01*01*2018"); java.time.LocalDate localDate = java.time.LocalDate.of(2018, 1, 1); - assertThat(conversionService.convert(localDate, String.class)) - .isEqualTo("01*01*2018"); + assertThat(conversionService.convert(localDate, String.class)).isEqualTo("01*01*2018"); } @Test public void convertFromStringToDate() { WebConversionService conversionService = new WebConversionService("yyyy-MM-dd"); - java.time.LocalDate date = conversionService.convert("2018-01-01", - java.time.LocalDate.class); + java.time.LocalDate date = conversionService.convert("2018-01-01", java.time.LocalDate.class); assertThat(date).isEqualTo(java.time.LocalDate.of(2018, 1, 1)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java index fa8c895f145..9948b4d20ad 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java @@ -44,18 +44,15 @@ public class HttpHandlerAutoConfigurationTests { @Test public void shouldNotProcessIfExistingHttpHandler() { - this.contextRunner.withUserConfiguration(CustomHttpHandler.class) - .run((context) -> { - assertThat(context).hasSingleBean(HttpHandler.class); - assertThat(context).getBean(HttpHandler.class) - .isSameAs(context.getBean("customHttpHandler")); - }); + this.contextRunner.withUserConfiguration(CustomHttpHandler.class).run((context) -> { + assertThat(context).hasSingleBean(HttpHandler.class); + assertThat(context).getBean(HttpHandler.class).isSameAs(context.getBean("customHttpHandler")); + }); } @Test public void shouldConfigureHttpHandlerAnnotation() { - this.contextRunner - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java index 8059e8a5b10..dbceabeb12a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java @@ -58,20 +58,15 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)); @Test public void createFromConfigClass() { - this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class, - HttpHandlerConfiguration.class).run((context) -> { - assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)) - .hasSize(1); - assertThat(context.getBeansOfType(WebServerFactoryCustomizer.class)) - .hasSize(2); - assertThat(context - .getBeansOfType(ReactiveWebServerFactoryCustomizer.class)) - .hasSize(1); + this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); + assertThat(context.getBeansOfType(WebServerFactoryCustomizer.class)).hasSize(2); + assertThat(context.getBeansOfType(ReactiveWebServerFactoryCustomizer.class)).hasSize(1); }); } @@ -86,44 +81,38 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { @Test public void multipleHttpHandler() { this.contextRunner - .withUserConfiguration(MockWebServerConfiguration.class, - HttpHandlerConfiguration.class, TooManyHttpHandlers.class) + .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, + TooManyHttpHandlers.class) .run((context) -> assertThat(context.getStartupFailure()) .isInstanceOf(ApplicationContextException.class) - .hasMessageContaining("multiple HttpHandler beans : " - + "httpHandler,additionalHttpHandler")); + .hasMessageContaining("multiple HttpHandler beans : " + "httpHandler,additionalHttpHandler")); } @Test public void customizeReactiveWebServer() { - this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class, - HttpHandlerConfiguration.class, ReactiveWebServerCustomization.class) - .run((context) -> assertThat( - context.getBean(MockReactiveWebServerFactory.class).getPort()) - .isEqualTo(9000)); + this.contextRunner + .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, + ReactiveWebServerCustomization.class) + .run((context) -> assertThat(context.getBean(MockReactiveWebServerFactory.class).getPort()) + .isEqualTo(9000)); } @Test public void defaultWebServerIsTomcat() { // Tomcat should be chosen over Netty if the Tomcat library is present. - this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) - .withPropertyValues("server.port=0") - .run((context) -> assertThat( - context.getBean(ReactiveWebServerFactory.class)) - .isInstanceOf(TomcatReactiveWebServerFactory.class)); + this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class).withPropertyValues("server.port=0") + .run((context) -> assertThat(context.getBean(ReactiveWebServerFactory.class)) + .isInstanceOf(TomcatReactiveWebServerFactory.class)); } @Test public void tomcatConnectorCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration( - TomcatConnectorCustomizerConfiguration.class); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(TomcatConnectorCustomizerConfiguration.class); runner.run((context) -> { - TomcatReactiveWebServerFactory factory = context - .getBean(TomcatReactiveWebServerFactory.class); + TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); assertThat(factory.getTomcatConnectorCustomizers()).hasSize(1); }); } @@ -132,13 +121,10 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { public void tomcatContextCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration( - TomcatContextCustomizerConfiguration.class); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(TomcatContextCustomizerConfiguration.class); runner.run((context) -> { - TomcatReactiveWebServerFactory factory = context - .getBean(TomcatReactiveWebServerFactory.class); + TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); assertThat(factory.getTomcatContextCustomizers()).hasSize(1); }); } @@ -147,94 +133,71 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { public void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration( - TomcatProtocolHandlerCustomizerConfiguration.class); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(TomcatProtocolHandlerCustomizerConfiguration.class); runner.run((context) -> { - TomcatReactiveWebServerFactory factory = context - .getBean(TomcatReactiveWebServerFactory.class); + TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); assertThat(factory.getTomcatProtocolHandlerCustomizers()).hasSize(1); }); } @Test public void jettyServerCustomizerBeanIsAddedToFactory() { - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader( - new FilteredClassLoader(Tomcat.class, HttpServer.class)) - .withUserConfiguration(JettyServerCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .run((context) -> { - JettyReactiveWebServerFactory factory = context - .getBean(JettyReactiveWebServerFactory.class); - assertThat(factory.getServerCustomizers()).hasSize(1); - }); + new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) + .withUserConfiguration(JettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); + assertThat(factory.getServerCustomizers()).hasSize(1); + }); } @Test public void undertowDeploymentInfoCustomizerBeanIsAddedToFactory() { - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, - HttpServer.class, Server.class)) - .withUserConfiguration( - UndertowDeploymentInfoCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .run((context) -> { - UndertowReactiveWebServerFactory factory = context - .getBean(UndertowReactiveWebServerFactory.class); - assertThat(factory.getDeploymentInfoCustomizers()).hasSize(1); - }); + new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) + .withUserConfiguration(UndertowDeploymentInfoCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .run((context) -> { + UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); + assertThat(factory.getDeploymentInfoCustomizers()).hasSize(1); + }); } @Test public void undertowBuilderCustomizerBeanIsAddedToFactory() { - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations - .of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, - HttpServer.class, Server.class)) - .withUserConfiguration( - UndertowBuilderCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .run((context) -> { - UndertowReactiveWebServerFactory factory = context - .getBean(UndertowReactiveWebServerFactory.class); - assertThat(factory.getBuilderCustomizers()).hasSize(1); - }); + new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) + .withUserConfiguration(UndertowBuilderCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); + assertThat(factory.getBuilderCustomizers()).hasSize(1); + }); } @Test public void forwardedHeaderTransformerShouldBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) .withPropertyValues("server.forward-headers-strategy=framework") - .run((context) -> assertThat(context) - .hasSingleBean(ForwardedHeaderTransformer.class)); + .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Test public void forwardedHeaderTransformerWhenStrategyNotFilterShouldNotBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) .withPropertyValues("server.forward-headers-strategy=native") - .run((context) -> assertThat(context) - .doesNotHaveBean(ForwardedHeaderTransformer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ForwardedHeaderTransformer.class)); } @Test public void forwardedHeaderTransformerWhenAlreadyRegisteredShouldBackOff() { this.contextRunner - .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, - HttpHandlerConfiguration.class) + .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, HttpHandlerConfiguration.class) .withPropertyValues("server.forward-headers-strategy=framework") - .run((context) -> assertThat(context) - .hasSingleBean(ForwardedHeaderTransformer.class)); + .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java index 1066b173cdb..af1dc3ab41a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java @@ -47,8 +47,7 @@ public class ReactiveWebServerFactoryCustomizerTests { @Test public void testCustomizeServerPort() { - ConfigurableReactiveWebServerFactory factory = mock( - ConfigurableReactiveWebServerFactory.class); + ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); this.properties.setPort(9000); this.customizer.customize(factory); verify(factory).setPort(9000); @@ -56,8 +55,7 @@ public class ReactiveWebServerFactoryCustomizerTests { @Test public void testCustomizeServerAddress() { - ConfigurableReactiveWebServerFactory factory = mock( - ConfigurableReactiveWebServerFactory.class); + ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); InetAddress address = mock(InetAddress.class); this.properties.setAddress(address); this.customizer.customize(factory); @@ -66,8 +64,7 @@ public class ReactiveWebServerFactoryCustomizerTests { @Test public void testCustomizeServerSsl() { - ConfigurableReactiveWebServerFactory factory = mock( - ConfigurableReactiveWebServerFactory.class); + ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); Ssl ssl = mock(Ssl.class); this.properties.setSsl(ssl); this.customizer.customize(factory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java index 3903108cde9..c4c108ae543 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java @@ -87,13 +87,10 @@ public class WebFluxAutoConfigurationTests { @Test public void shouldNotProcessIfExistingWebReactiveConfiguration() { - this.contextRunner.withUserConfiguration(WebFluxConfigurationSupport.class) - .run((context) -> { - assertThat(context).getBeans(RequestMappingHandlerMapping.class) - .hasSize(1); - assertThat(context).getBeans(RequestMappingHandlerAdapter.class) - .hasSize(1); - }); + this.contextRunner.withUserConfiguration(WebFluxConfigurationSupport.class).run((context) -> { + assertThat(context).getBeans(RequestMappingHandlerMapping.class).hasSize(1); + assertThat(context).getBeans(RequestMappingHandlerAdapter.class).hasSize(1); + }); } @Test @@ -102,53 +99,40 @@ public class WebFluxAutoConfigurationTests { assertThat(context).getBeans(RequestMappingHandlerMapping.class).hasSize(1); assertThat(context).getBeans(RequestMappingHandlerAdapter.class).hasSize(1); assertThat(context).getBeans(RequestedContentTypeResolver.class).hasSize(1); - assertThat(context.getBean("resourceHandlerMapping", HandlerMapping.class)) - .isNotNull(); + assertThat(context.getBean("resourceHandlerMapping", HandlerMapping.class)).isNotNull(); }); } @SuppressWarnings("unchecked") @Test public void shouldRegisterCustomHandlerMethodArgumentResolver() { - this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class) - .run((context) -> { - RequestMappingHandlerAdapter adapter = context - .getBean(RequestMappingHandlerAdapter.class); - List customResolvers = (List) ReflectionTestUtils - .getField(adapter.getArgumentResolverConfigurer(), - "customResolvers"); - assertThat(customResolvers).contains( - context.getBean("firstResolver", - HandlerMethodArgumentResolver.class), - context.getBean("secondResolver", - HandlerMethodArgumentResolver.class)); - }); + this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class).run((context) -> { + RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); + List customResolvers = (List) ReflectionTestUtils + .getField(adapter.getArgumentResolverConfigurer(), "customResolvers"); + assertThat(customResolvers).contains(context.getBean("firstResolver", HandlerMethodArgumentResolver.class), + context.getBean("secondResolver", HandlerMethodArgumentResolver.class)); + }); } @Test public void shouldCustomizeCodecs() { - this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class) - .run((context) -> { - CodecCustomizer codecCustomizer = context - .getBean("firstCodecCustomizer", CodecCustomizer.class); - assertThat(codecCustomizer).isNotNull(); - verify(codecCustomizer).customize(any(ServerCodecConfigurer.class)); - }); + this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class).run((context) -> { + CodecCustomizer codecCustomizer = context.getBean("firstCodecCustomizer", CodecCustomizer.class); + assertThat(codecCustomizer).isNotNull(); + verify(codecCustomizer).customize(any(ServerCodecConfigurer.class)); + }); } @Test public void shouldRegisterResourceHandlerMapping() { this.contextRunner.run((context) -> { - SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", - SimpleUrlHandlerMapping.class); + SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class); assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); - ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap() - .get("/**"); + ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap().get("/**"); assertThat(staticHandler.getLocations()).hasSize(4); - assertThat(hm.getUrlMap().get("/webjars/**")) - .isInstanceOf(ResourceWebHandler.class); - ResourceWebHandler webjarsHandler = (ResourceWebHandler) hm.getUrlMap() - .get("/webjars/**"); + assertThat(hm.getUrlMap().get("/webjars/**")).isInstanceOf(ResourceWebHandler.class); + ResourceWebHandler webjarsHandler = (ResourceWebHandler) hm.getUrlMap().get("/webjars/**"); assertThat(webjarsHandler.getLocations()).hasSize(1); assertThat(webjarsHandler.getLocations().get(0)) .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); @@ -157,17 +141,12 @@ public class WebFluxAutoConfigurationTests { @Test public void shouldMapResourcesToCustomPath() { - this.contextRunner - .withPropertyValues("spring.webflux.static-path-pattern:/static/**") - .run((context) -> { - SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", - SimpleUrlHandlerMapping.class); - assertThat(hm.getUrlMap().get("/static/**")) - .isInstanceOf(ResourceWebHandler.class); - ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap() - .get("/static/**"); - assertThat(staticHandler.getLocations()).hasSize(4); - }); + this.contextRunner.withPropertyValues("spring.webflux.static-path-pattern:/static/**").run((context) -> { + SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class); + assertThat(hm.getUrlMap().get("/static/**")).isInstanceOf(ResourceWebHandler.class); + ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap().get("/static/**"); + assertThat(staticHandler.getLocations()).hasSize(4); + }); } @Test @@ -179,29 +158,21 @@ public class WebFluxAutoConfigurationTests { @Test public void resourceHandlerChainEnabled() { - this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true") - .run((context) -> { - SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", - SimpleUrlHandlerMapping.class); - assertThat(hm.getUrlMap().get("/**")) - .isInstanceOf(ResourceWebHandler.class); - ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap() - .get("/**"); - assertThat(staticHandler.getResourceResolvers()) - .extractingResultOf("getClass") - .containsOnly(CachingResourceResolver.class, - PathResourceResolver.class); - assertThat(staticHandler.getResourceTransformers()) - .extractingResultOf("getClass") - .containsOnly(CachingResourceTransformer.class); - }); + this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { + SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class); + assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); + ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap().get("/**"); + assertThat(staticHandler.getResourceResolvers()).extractingResultOf("getClass") + .containsOnly(CachingResourceResolver.class, PathResourceResolver.class); + assertThat(staticHandler.getResourceTransformers()).extractingResultOf("getClass") + .containsOnly(CachingResourceTransformer.class); + }); } @Test public void shouldRegisterViewResolvers() { this.contextRunner.withUserConfiguration(ViewResolvers.class).run((context) -> { - ViewResolutionResultHandler resultHandler = context - .getBean(ViewResolutionResultHandler.class); + ViewResolutionResultHandler resultHandler = context.getBean(ViewResolutionResultHandler.class); assertThat(resultHandler.getViewResolvers()).containsExactly( context.getBean("aViewResolver", ViewResolver.class), context.getBean("anotherViewResolver", ViewResolver.class)); @@ -211,25 +182,20 @@ public class WebFluxAutoConfigurationTests { @Test public void noDateFormat() { this.contextRunner.run((context) -> { - FormattingConversionService conversionService = context - .getBean(FormattingConversionService.class); + FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); // formatting conversion service should use simple toString() - assertThat(conversionService.convert(date, String.class)) - .isEqualTo(date.toString()); + assertThat(conversionService.convert(date, String.class)).isEqualTo(date.toString()); }); } @Test public void overrideDateFormat() { - this.contextRunner.withPropertyValues("spring.webflux.date-format:dd*MM*yyyy") - .run((context) -> { - FormattingConversionService conversionService = context - .getBean(FormattingConversionService.class); - Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); - assertThat(conversionService.convert(date, String.class)) - .isEqualTo("25*06*1988"); - }); + this.contextRunner.withPropertyValues("spring.webflux.date-format:dd*MM*yyyy").run((context) -> { + FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); + Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); + assertThat(conversionService.convert(date, String.class)).isEqualTo("25*06*1988"); + }); } @Test @@ -237,213 +203,170 @@ public class WebFluxAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); - assertThat(context).getBeanNames(Validator.class) - .containsExactly("webFluxValidator"); + assertThat(context).getBeanNames(Validator.class).containsExactly("webFluxValidator"); }); } @Test public void validatorWhenNoCustomizationShouldUseAutoConfigured() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run((context) -> { assertThat(context).getBeanNames(javax.validation.Validator.class) .containsExactly("defaultValidator"); - assertThat(context).getBeanNames(Validator.class) - .containsExactlyInAnyOrder("defaultValidator", - "webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", - Validator.class); + assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("defaultValidator", + "webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); assertThat(validator).isInstanceOf(ValidatorAdapter.class); Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(defaultValidator); + assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); // Primary Spring validator is the one used by WebFlux behind the // scenes - assertThat(context.getBean(Validator.class)) - .isEqualTo(defaultValidator); + assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); }); } @Test public void validatorWithConfigurerShouldUseSpringValidator() { - this.contextRunner.withUserConfiguration(ValidatorWebFluxConfigurer.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(ValidatorFactory.class); - assertThat(context).doesNotHaveBean(javax.validation.Validator.class); - assertThat(context).getBeanNames(Validator.class) - .containsOnly("webFluxValidator"); - assertThat(context.getBean("webFluxValidator")).isSameAs( - context.getBean(ValidatorWebFluxConfigurer.class).validator); - }); + this.contextRunner.withUserConfiguration(ValidatorWebFluxConfigurer.class).run((context) -> { + assertThat(context).doesNotHaveBean(ValidatorFactory.class); + assertThat(context).doesNotHaveBean(javax.validation.Validator.class); + assertThat(context).getBeanNames(Validator.class).containsOnly("webFluxValidator"); + assertThat(context.getBean("webFluxValidator")) + .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); + }); } @Test public void validatorWithConfigurerDoesNotExposeJsr303() { - this.contextRunner.withUserConfiguration(ValidatorJsr303WebFluxConfigurer.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(ValidatorFactory.class); - assertThat(context).doesNotHaveBean(javax.validation.Validator.class); - assertThat(context).getBeanNames(Validator.class) - .containsOnly("webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", - Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(context.getBean( - ValidatorJsr303WebFluxConfigurer.class).validator); - }); + this.contextRunner.withUserConfiguration(ValidatorJsr303WebFluxConfigurer.class).run((context) -> { + assertThat(context).doesNotHaveBean(ValidatorFactory.class); + assertThat(context).doesNotHaveBean(javax.validation.Validator.class); + assertThat(context).getBeanNames(Validator.class).containsOnly("webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + assertThat(((ValidatorAdapter) validator).getTarget()) + .isSameAs(context.getBean(ValidatorJsr303WebFluxConfigurer.class).validator); + }); } @Test public void validationCustomConfigurerTakesPrecedence() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(ValidatorWebFluxConfigurer.class) - .run((context) -> { + this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withUserConfiguration(ValidatorWebFluxConfigurer.class).run((context) -> { assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); - assertThat(context).getBeans(javax.validation.Validator.class) - .hasSize(1); - assertThat(context).getBeanNames(Validator.class) - .containsExactlyInAnyOrder("defaultValidator", - "webFluxValidator"); - assertThat(context.getBean("webFluxValidator")).isSameAs( - context.getBean(ValidatorWebFluxConfigurer.class).validator); + assertThat(context).getBeans(javax.validation.Validator.class).hasSize(1); + assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("defaultValidator", + "webFluxValidator"); + assertThat(context.getBean("webFluxValidator")) + .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); // Primary Spring validator is the auto-configured one as the WebFlux // one has been // customized via a WebFluxConfigurer - assertThat(context.getBean(Validator.class)) - .isEqualTo(context.getBean("defaultValidator")); + assertThat(context.getBean(Validator.class)).isEqualTo(context.getBean("defaultValidator")); }); } @Test public void validatorWithCustomSpringValidatorIgnored() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .withUserConfiguration(CustomSpringValidator.class).run((context) -> { assertThat(context).getBeanNames(javax.validation.Validator.class) .containsExactly("defaultValidator"); - assertThat(context).getBeanNames(Validator.class) - .containsExactlyInAnyOrder("customValidator", - "defaultValidator", "webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", - Validator.class); + assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("customValidator", + "defaultValidator", "webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); assertThat(validator).isInstanceOf(ValidatorAdapter.class); Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(defaultValidator); + assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); // Primary Spring validator is the one used by WebFlux behind the // scenes - assertThat(context.getBean(Validator.class)) - .isEqualTo(defaultValidator); + assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); }); } @Test public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { - this.contextRunner.withUserConfiguration(CustomJsr303Validator.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(ValidatorFactory.class); - assertThat(context).getBeanNames(javax.validation.Validator.class) - .containsExactly("customValidator"); - assertThat(context).getBeanNames(Validator.class) - .containsExactly("webFluxValidator"); - Validator validator = context.getBean(Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Validator target = ((ValidatorAdapter) validator).getTarget(); - assertThat(target).hasFieldOrPropertyWithValue("targetValidator", - context.getBean("customValidator")); - }); + this.contextRunner.withUserConfiguration(CustomJsr303Validator.class).run((context) -> { + assertThat(context).doesNotHaveBean(ValidatorFactory.class); + assertThat(context).getBeanNames(javax.validation.Validator.class).containsExactly("customValidator"); + assertThat(context).getBeanNames(Validator.class).containsExactly("webFluxValidator"); + Validator validator = context.getBean(Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Validator target = ((ValidatorAdapter) validator).getTarget(); + assertThat(target).hasFieldOrPropertyWithValue("targetValidator", context.getBean("customValidator")); + }); } @Test public void hiddenHttpMethodFilterIsAutoConfigured() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(OrderedHiddenHttpMethodFilter.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(OrderedHiddenHttpMethodFilter.class)); } @Test public void hiddenHttpMethodFilterCanBeOverridden() { - this.contextRunner.withUserConfiguration(CustomHiddenHttpMethodFilter.class) - .run((context) -> { - assertThat(context) - .doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); - assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); - }); + this.contextRunner.withUserConfiguration(CustomHiddenHttpMethodFilter.class).run((context) -> { + assertThat(context).doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); + assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); + }); } @Test public void hiddenHttpMethodFilterCanBeDisabled() { - this.contextRunner - .withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HiddenHttpMethodFilter.class)); + this.contextRunner.withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(HiddenHttpMethodFilter.class)); } @Test public void customRequestMappingHandlerMapping() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerMapping.class) - .run((context) -> assertThat(context) - .getBean(RequestMappingHandlerMapping.class) + .run((context) -> assertThat(context).getBean(RequestMappingHandlerMapping.class) .isInstanceOf(MyRequestMappingHandlerMapping.class)); } @Test public void customRequestMappingHandlerAdapter() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerAdapter.class) - .run((context) -> assertThat(context) - .getBean(RequestMappingHandlerAdapter.class) + .run((context) -> assertThat(context).getBean(RequestMappingHandlerAdapter.class) .isInstanceOf(MyRequestMappingHandlerAdapter.class)); } @Test public void multipleWebFluxRegistrations() { - this.contextRunner.withUserConfiguration(MultipleWebFluxRegistrations.class) - .run((context) -> { - assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .isNotInstanceOf(MyRequestMappingHandlerMapping.class); - assertThat(context.getBean(RequestMappingHandlerAdapter.class)) - .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); - }); + this.contextRunner.withUserConfiguration(MultipleWebFluxRegistrations.class).run((context) -> { + assertThat(context.getBean(RequestMappingHandlerMapping.class)) + .isNotInstanceOf(MyRequestMappingHandlerMapping.class); + assertThat(context.getBean(RequestMappingHandlerAdapter.class)) + .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); + }); } @Test public void cachePeriod() { Assertions.setExtractBareNamePropertyMethods(false); - this.contextRunner.withPropertyValues("spring.resources.cache.period:5") - .run((context) -> { - Map handlerMap = getHandlerMap(context); - assertThat(handlerMap).hasSize(2); - for (Object handler : handlerMap.values()) { - if (handler instanceof ResourceWebHandler) { - assertThat(((ResourceWebHandler) handler).getCacheControl()) - .isEqualToComparingFieldByField( - CacheControl.maxAge(5, TimeUnit.SECONDS)); - } - } - }); + this.contextRunner.withPropertyValues("spring.resources.cache.period:5").run((context) -> { + Map handlerMap = getHandlerMap(context); + assertThat(handlerMap).hasSize(2); + for (Object handler : handlerMap.values()) { + if (handler instanceof ResourceWebHandler) { + assertThat(((ResourceWebHandler) handler).getCacheControl()) + .isEqualToComparingFieldByField(CacheControl.maxAge(5, TimeUnit.SECONDS)); + } + } + }); Assertions.setExtractBareNamePropertyMethods(true); } @Test public void cacheControl() { Assertions.setExtractBareNamePropertyMethods(false); - this.contextRunner - .withPropertyValues("spring.resources.cache.cachecontrol.max-age:5", - "spring.resources.cache.cachecontrol.proxy-revalidate:true") - .run((context) -> { + this.contextRunner.withPropertyValues("spring.resources.cache.cachecontrol.max-age:5", + "spring.resources.cache.cachecontrol.proxy-revalidate:true").run((context) -> { Map handlerMap = getHandlerMap(context); assertThat(handlerMap).hasSize(2); for (Object handler : handlerMap.values()) { if (handler instanceof ResourceWebHandler) { - assertThat(((ResourceWebHandler) handler).getCacheControl()) - .isEqualToComparingFieldByField( - CacheControl.maxAge(5, TimeUnit.SECONDS) - .proxyRevalidate()); + assertThat(((ResourceWebHandler) handler).getCacheControl()).isEqualToComparingFieldByField( + CacheControl.maxAge(5, TimeUnit.SECONDS).proxyRevalidate()); } } }); @@ -451,8 +374,7 @@ public class WebFluxAutoConfigurationTests { } private Map getHandlerMap(ApplicationContext context) { - HandlerMapping mapping = context.getBean("resourceHandlerMapping", - HandlerMapping.class); + HandlerMapping mapping = context.getBean("resourceHandlerMapping", HandlerMapping.class); if (mapping instanceof SimpleUrlHandlerMapping) { return ((SimpleUrlHandlerMapping) mapping).getHandlerMap(); } @@ -591,8 +513,7 @@ public class WebFluxAutoConfigurationTests { } - private static class MyRequestMappingHandlerAdapter - extends RequestMappingHandlerAdapter { + private static class MyRequestMappingHandlerAdapter extends RequestMappingHandlerAdapter { } @@ -620,8 +541,7 @@ public class WebFluxAutoConfigurationTests { } - private static class MyRequestMappingHandlerMapping - extends RequestMappingHandlerMapping { + private static class MyRequestMappingHandlerMapping extends RequestMappingHandlerMapping { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java index e8c8681d39c..0fcc41b80e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java @@ -59,34 +59,27 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @ExtendWith(OutputCaptureExtension.class) public class DefaultErrorWebExceptionHandlerIntegrationTests { - private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", - StandardCharsets.UTF_8); + private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8); private final LogIdFilter logIdFilter = new LogIdFilter(); private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - ReactiveWebServerFactoryAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class, HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, + ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, MustacheAutoConfiguration.class)) - .withPropertyValues("spring.main.web-application-type=reactive", - "server.port=0") + .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") .withUserConfiguration(Application.class); @Test public void jsonError(CapturedOutput capturedOutput) { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() + client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() .jsonPath("status").isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) - .jsonPath("path").isEqualTo(("/")).jsonPath("message") - .isEqualTo("Expected!").jsonPath("exception").doesNotExist() - .jsonPath("trace").doesNotExist().jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/")) + .jsonPath("message").isEqualTo("Expected!").jsonPath("exception").doesNotExist().jsonPath("trace") + .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); assertThat(capturedOutput).contains("500 Server Error for HTTP GET \"/\"") .contains("java.lang.IllegalStateException: Expected!"); }); @@ -96,10 +89,9 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { public void notFound() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/notFound").exchange().expectStatus().isNotFound() - .expectBody().jsonPath("status").isEqualTo("404").jsonPath("error") - .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()).jsonPath("path") - .isEqualTo(("/notFound")).jsonPath("exception").doesNotExist() + client.get().uri("/notFound").exchange().expectStatus().isNotFound().expectBody().jsonPath("status") + .isEqualTo("404").jsonPath("error").isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()) + .jsonPath("path").isEqualTo(("/notFound")).jsonPath("exception").doesNotExist() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @@ -108,10 +100,9 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { public void htmlError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange() - .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) - .expectHeader().contentType(TEXT_HTML_UTF8).expectBody(String.class) - .returnResult().getResponseBody(); + String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) + .expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("status: 500").contains("message: Expected!"); }); } @@ -120,131 +111,105 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { public void bindingResultError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON) - .syncBody("{}").exchange().expectStatus().isBadRequest().expectBody() - .jsonPath("status").isEqualTo("400").jsonPath("error") - .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("path") - .isEqualTo(("/bind")).jsonPath("exception").doesNotExist() - .jsonPath("errors").isArray().jsonPath("message").isNotEmpty() + client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON).syncBody("{}").exchange().expectStatus() + .isBadRequest().expectBody().jsonPath("status").isEqualTo("400").jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("path").isEqualTo(("/bind")) + .jsonPath("exception").doesNotExist().jsonPath("errors").isArray().jsonPath("message").isNotEmpty() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test public void includeStackTraceOnParam() { - this.contextRunner - .withPropertyValues("server.error.include-exception=true", - "server.error.include-stacktrace=on-trace-param") - .run((context) -> { + this.contextRunner.withPropertyValues("server.error.include-exception=true", + "server.error.include-stacktrace=on-trace-param").run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() - .jsonPath("status").isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) - .jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()) - .jsonPath("trace").exists().jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); - }); - } - - @Test - public void alwaysIncludeStackTrace() { - this.contextRunner.withPropertyValues("server.error.include-exception=true", - "server.error.include-stacktrace=always").run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=false").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() - .jsonPath("status").isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) - .jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()) - .jsonPath("trace").exists().jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); - }); - } - - @Test - public void neverIncludeStackTrace() { - this.contextRunner.withPropertyValues("server.error.include-exception=true", - "server.error.include-stacktrace=never").run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() - .jsonPath("status").isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) - .jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()) - .jsonPath("trace").doesNotExist().jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); - }); - } - - @Test - public void statusException() { - this.contextRunner.withPropertyValues("server.error.include-exception=true") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/badRequest").exchange().expectStatus() - .isBadRequest().expectBody().jsonPath("status") - .isEqualTo("400").jsonPath("error") - .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) - .jsonPath("exception") - .isEqualTo(ResponseStatusException.class.getName()) + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") + .isEqualTo("500").jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test - public void defaultErrorView() { + public void alwaysIncludeStackTrace() { this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", - "server.error.include-stacktrace=always") + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") .run((context) -> { WebTestClient client = getWebClient(context); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML) - .exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader() - .contentType(TEXT_HTML_UTF8).expectBody(String.class) - .returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page") - .contains(this.logIdFilter.getLogId()) - .contains("
    Expected!
    ").contains( - "
    java.lang.IllegalStateException"); + client.get().uri("/?trace=false").exchange().expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") + .isEqualTo("500").jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() + .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + }); + } + + @Test + public void neverIncludeStackTrace() { + this.contextRunner + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get().uri("/?trace=true").exchange().expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") + .isEqualTo("500").jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").doesNotExist() + .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + }); + } + + @Test + public void statusException() { + this.contextRunner.withPropertyValues("server.error.include-exception=true").run((context) -> { + WebTestClient client = getWebClient(context); + client.get().uri("/badRequest").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") + .isEqualTo("400").jsonPath("error").isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("exception").isEqualTo(ResponseStatusException.class.getName()).jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); + } + + @Test + public void defaultErrorView() { + this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/", + "server.error.include-stacktrace=always").run((context) -> { + WebTestClient client = getWebClient(context); + String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) + .expectBody(String.class).returnResult().getResponseBody(); + assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) + .contains("
    Expected!
    ") + .contains("
    java.lang.IllegalStateException"); }); } @Test public void escapeHtmlInDefaultErrorView() { - this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/") - .run((context) -> { - WebTestClient client = getWebClient(context); - String body = client.get().uri("/html").accept(MediaType.TEXT_HTML) - .exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader() - .contentType(TEXT_HTML_UTF8).expectBody(String.class) - .returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page") - .contains(this.logIdFilter.getLogId()) - .doesNotContain("")) + new RuntimeException("")) .accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); @@ -93,12 +91,8 @@ public class DefaultErrorViewIntegrationTests { @Test public void testErrorWithSpelEscape() throws Exception { String spel = "${T(" + getClass().getName() + ").injectCall()}"; - MvcResult response = this.mockMvc - .perform( - get("/error") - .requestAttr("javax.servlet.error.exception", - new RuntimeException(spel)) - .accept(MediaType.TEXT_HTML)) + MvcResult response = this.mockMvc.perform(get("/error") + .requestAttr("javax.servlet.error.exception", new RuntimeException(spel)).accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).doesNotContain("injection"); @@ -111,10 +105,9 @@ public class DefaultErrorViewIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java index 6768ab8d9ad..f930a619c95 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java @@ -77,71 +77,63 @@ public class DefaultErrorViewResolverTests { this.resourceProperties = new ResourceProperties(); TemplateAvailabilityProviders templateAvailabilityProviders = new TestTemplateAvailabilityProviders( this.templateAvailabilityProvider); - this.resolver = new DefaultErrorViewResolver(applicationContext, - this.resourceProperties, templateAvailabilityProviders); + this.resolver = new DefaultErrorViewResolver(applicationContext, this.resourceProperties, + templateAvailabilityProviders); } @Test public void createWhenApplicationContextIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new DefaultErrorViewResolver(null, new ResourceProperties())) + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultErrorViewResolver(null, new ResourceProperties())) .withMessageContaining("ApplicationContext must not be null"); } @Test public void createWhenResourcePropertiesIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new DefaultErrorViewResolver(mock(ApplicationContext.class), null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), null)) .withMessageContaining("ResourceProperties must not be null"); } @Test public void resolveWhenNoMatchShouldReturnNull() { - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNull(); } @Test public void resolveWhenExactTemplateMatchShouldReturnTemplate() { - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNotNull(); assertThat(resolved.getViewName()).isEqualTo("error/404"); - verify(this.templateAvailabilityProvider).isTemplateAvailable(eq("error/404"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class)); + verify(this.templateAvailabilityProvider).isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class)); verifyNoMoreInteractions(this.templateAvailabilityProvider); } @Test public void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() { - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.SERVICE_UNAVAILABLE, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.SERVICE_UNAVAILABLE, + this.model); assertThat(resolved.getViewName()).isEqualTo("error/5xx"); } @Test public void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() { - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/4xx"); } @Test public void resolveWhenExactResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/exact"); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("exact/404"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -150,8 +142,7 @@ public class DefaultErrorViewResolverTests { @Test public void resolveWhenSeries4xxResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/4xx"); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("4xx/4xx"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -160,8 +151,8 @@ public class DefaultErrorViewResolverTests { @Test public void resolveWhenSeries5xxResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/5xx"); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.INTERNAL_SERVER_ERROR, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.INTERNAL_SERVER_ERROR, + this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("5xx/5xx"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -170,23 +161,18 @@ public class DefaultErrorViewResolverTests { @Test public void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() { setResourceLocation("/exact"); - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/404"); } @Test - public void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() - throws Exception { + public void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { setResourceLocation("/exact"); - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("exact/404"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -205,8 +191,8 @@ public class DefaultErrorViewResolverTests { private void setResourceLocation(String path) { String packageName = getClass().getPackage().getName(); - this.resourceProperties.setStaticLocations(new String[] { - "classpath:" + packageName.replace('.', '/') + path + "/" }); + this.resourceProperties + .setStaticLocations(new String[] { "classpath:" + packageName.replace('.', '/') + path + "/" }); } private MockHttpServletResponse render(ModelAndView modelAndView) throws Exception { @@ -215,8 +201,7 @@ public class DefaultErrorViewResolverTests { return response; } - private static class TestTemplateAvailabilityProviders - extends TemplateAvailabilityProviders { + private static class TestTemplateAvailabilityProviders extends TemplateAvailabilityProviders { TestTemplateAvailabilityProviders(TemplateAvailabilityProvider provider) { super(Collections.singletonList(provider)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java index 57717b3105e..355f213336f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java @@ -41,28 +41,24 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(OutputCaptureExtension.class) public class ErrorMvcAutoConfigurationTests { - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DispatcherServletAutoConfiguration.class, - ErrorMvcAutoConfiguration.class)); + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( + AutoConfigurations.of(DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class)); @Test public void renderContainsViewWithExceptionDetails() throws Exception { this.contextRunner.run((context) -> { View errorView = context.getBean("error", View.class); ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class); - DispatcherServletWebRequest webRequest = createWebRequest( - new IllegalStateException("Exception message"), false); - errorView.render(errorAttributes.getErrorAttributes(webRequest, true), - webRequest.getRequest(), webRequest.getResponse()); - assertThat(webRequest.getResponse().getContentType()) - .isEqualTo("text/html;charset=UTF-8"); - String responseString = ((MockHttpServletResponse) webRequest.getResponse()) - .getContentAsString(); + DispatcherServletWebRequest webRequest = createWebRequest(new IllegalStateException("Exception message"), + false); + errorView.render(errorAttributes.getErrorAttributes(webRequest, true), webRequest.getRequest(), + webRequest.getResponse()); + assertThat(webRequest.getResponse().getContentType()).isEqualTo("text/html;charset=UTF-8"); + String responseString = ((MockHttpServletResponse) webRequest.getResponse()).getContentAsString(); assertThat(responseString).contains( "

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    ") - .contains("
    Exception message
    ").contains( - "
    java.lang.IllegalStateException"); + .contains("
    Exception message
    ") + .contains("
    java.lang.IllegalStateException"); }); } @@ -71,28 +67,22 @@ public class ErrorMvcAutoConfigurationTests { this.contextRunner.run((context) -> { View errorView = context.getBean("error", View.class); ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class); - DispatcherServletWebRequest webRequest = createWebRequest( - new IllegalStateException("Exception message"), true); - errorView.render(errorAttributes.getErrorAttributes(webRequest, true), - webRequest.getRequest(), webRequest.getResponse()); - assertThat(capturedOutput) - .contains("Cannot render error page for request [/path] " - + "and exception [Exception message] as the response has " - + "already been committed. As a result, the response may " - + "have the wrong status code."); + DispatcherServletWebRequest webRequest = createWebRequest(new IllegalStateException("Exception message"), + true); + errorView.render(errorAttributes.getErrorAttributes(webRequest, true), webRequest.getRequest(), + webRequest.getResponse()); + assertThat(capturedOutput).contains("Cannot render error page for request [/path] " + + "and exception [Exception message] as the response has " + + "already been committed. As a result, the response may " + "have the wrong status code."); }); } - private DispatcherServletWebRequest createWebRequest(Exception ex, - boolean committed) { + private DispatcherServletWebRequest createWebRequest(Exception ex, boolean committed) { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path"); MockHttpServletResponse response = new MockHttpServletResponse(); - DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, - response); - webRequest.setAttribute("javax.servlet.error.exception", ex, - RequestAttributes.SCOPE_REQUEST); - webRequest.setAttribute("javax.servlet.error.request_uri", "/path", - RequestAttributes.SCOPE_REQUEST); + DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, response); + webRequest.setAttribute("javax.servlet.error.exception", ex, RequestAttributes.SCOPE_REQUEST); + webRequest.setAttribute("javax.servlet.error.request_uri", "/path", RequestAttributes.SCOPE_REQUEST); response.setCommitted(committed); response.setOutputStreamAccessAllowed(!committed); response.setWriterAccessAllowed(!committed); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java index 6569d1e1c92..4b176324f11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java @@ -44,8 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.mvc.servlet.path:/spring/") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.mvc.servlet.path:/spring/") @DirtiesContext public class RemappedErrorViewIntegrationTests { @@ -56,24 +55,21 @@ public class RemappedErrorViewIntegrationTests { @Test public void directAccessToErrorPage() { - String content = this.template.getForObject( - "http://localhost:" + this.port + "/spring/error", String.class); + String content = this.template.getForObject("http://localhost:" + this.port + "/spring/error", String.class); assertThat(content).contains("error"); assertThat(content).contains("999"); } @Test public void forwardToErrorPage() { - String content = this.template - .getForObject("http://localhost:" + this.port + "/spring/", String.class); + String content = this.template.getForObject("http://localhost:" + this.port + "/spring/", String.class); assertThat(content).contains("error"); assertThat(content).contains("500"); } @Configuration(proxyBeanMethods = false) @Import({ PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class }) @Controller public static class TestConfiguration implements ErrorPageRegistrar { @@ -90,8 +86,8 @@ public class RemappedErrorViewIntegrationTests { // For manual testing public static void main(String[] args) { - new SpringApplicationBuilder(TestConfiguration.class) - .properties("spring.mvc.servlet.path:spring/*").run(args); + new SpringApplicationBuilder(TestConfiguration.class).properties("spring.mvc.servlet.path:spring/*") + .run(args); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java index 51a39cb20a4..c9135e22fa7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java @@ -49,8 +49,7 @@ public class OnWsdlLocationsConditionTests { @Test public void wsdlLocationsDefinedAsList() { - this.contextRunner - .withPropertyValues("spring.webservices.wsdl-locations[0]=value1") + this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=value1") .run((context) -> assertThat(context).hasBean("foo")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index d501ae9a0a5..242e3c6321c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -46,40 +46,34 @@ public class WebServicesAutoConfigurationTests { @Test public void defaultConfiguration() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ServletRegistrationBean.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ServletRegistrationBean.class)); } @Test public void customPathMustBeginWithASlash() { this.contextRunner.withPropertyValues("spring.webservices.path=invalid") - .run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class).hasMessageContaining( - "Failed to bind properties under 'spring.webservices'")); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to bind properties under 'spring.webservices'")); } @Test public void customPath() { - this.contextRunner.withPropertyValues("spring.webservices.path=/valid").run( - (context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); + this.contextRunner.withPropertyValues("spring.webservices.path=/valid") + .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test public void customPathWithTrailingSlash() { - this.contextRunner.withPropertyValues("spring.webservices.path=/valid/").run( - (context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); + this.contextRunner.withPropertyValues("spring.webservices.path=/valid/") + .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test public void customLoadOnStartup() { - this.contextRunner - .withPropertyValues("spring.webservices.servlet.load-on-startup=1") - .run((context) -> { - ServletRegistrationBean registrationBean = context - .getBean(ServletRegistrationBean.class); - assertThat(ReflectionTestUtils.getField(registrationBean, - "loadOnStartup")).isEqualTo(1); - }); + this.contextRunner.withPropertyValues("spring.webservices.servlet.load-on-startup=1").run((context) -> { + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(ReflectionTestUtils.getField(registrationBean, "loadOnStartup")).isEqualTo(1); + }); } @Test @@ -87,43 +81,31 @@ public class WebServicesAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.webservices.servlet.init.key1=value1", "spring.webservices.servlet.init.key2=value2") - .run((context) -> assertThat( - getServletRegistrationBean(context).getInitParameters()) - .containsEntry("key1", "value1") - .containsEntry("key2", "value2")); + .run((context) -> assertThat(getServletRegistrationBean(context).getInitParameters()) + .containsEntry("key1", "value1").containsEntry("key2", "value2")); } @Test public void withWsdlBeans() { - this.contextRunner - .withPropertyValues("spring.webservices.wsdl-locations=classpath:/wsdl") - .run((context) -> { - assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)) - .containsOnlyKeys("service"); - assertThat(context.getBeansOfType(SimpleXsdSchema.class)) - .containsOnlyKeys("types"); - }); + this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations=classpath:/wsdl").run((context) -> { + assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)).containsOnlyKeys("service"); + assertThat(context.getBeansOfType(SimpleXsdSchema.class)).containsOnlyKeys("types"); + }); } @Test public void withWsdlBeansAsList() { - this.contextRunner - .withPropertyValues( - "spring.webservices.wsdl-locations[0]=classpath:/wsdl") - .run((context) -> { - assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)) - .containsOnlyKeys("service"); - assertThat(context.getBeansOfType(SimpleXsdSchema.class)) - .containsOnlyKeys("types"); - }); + this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=classpath:/wsdl").run((context) -> { + assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)).containsOnlyKeys("service"); + assertThat(context.getBeansOfType(SimpleXsdSchema.class)).containsOnlyKeys("types"); + }); } private Collection getUrlMappings(ApplicationContext context) { return getServletRegistrationBean(context).getUrlMappings(); } - private ServletRegistrationBean getServletRegistrationBean( - ApplicationContext loaded) { + private ServletRegistrationBean getServletRegistrationBean(ApplicationContext loaded) { return loaded.getBean(ServletRegistrationBean.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java index dc51f229b13..5871bb9b297 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java @@ -39,16 +39,14 @@ public class WebServicesPropertiesTests { @Test public void pathMustHaveLengthGreaterThanOne() { this.properties = new WebServicesProperties(); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.properties.setPath("/")) + assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("/")) .withMessageContaining("Path must have length greater than 1"); } @Test public void customPathMustBeginWithASlash() { this.properties = new WebServicesProperties(); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.properties.setPath("custom")) + assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("custom")) .withMessageContaining("Path must start with '/'"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java index 8ba3c4fa086..65b4708d3e5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java @@ -46,8 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class WebServiceTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); @Test public void autoConfiguredBuilderShouldNotHaveMarshallerAndUnmarshaller() { @@ -63,16 +62,14 @@ public class WebServiceTemplateAutoConfigurationTests { this.contextRunner.run(assertWebServiceTemplateBuilder((builder) -> { WebServiceTemplate webServiceTemplate = builder.build(); assertThat(webServiceTemplate.getMessageSenders()).hasSize(1); - WebServiceMessageSender messageSender = webServiceTemplate - .getMessageSenders()[0]; + WebServiceMessageSender messageSender = webServiceTemplate.getMessageSenders()[0]; assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class); })); } @Test public void webServiceTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { - this.contextRunner - .withUserConfiguration(CustomWebServiceTemplateBuilderConfig.class) + this.contextRunner.withUserConfiguration(CustomWebServiceTemplateBuilderConfig.class) .run(assertWebServiceTemplateBuilder((builder) -> { WebServiceTemplate webServiceTemplate = builder.build(); assertThat(webServiceTemplate.getMarshaller()) @@ -108,8 +105,7 @@ public class WebServiceTemplateAutoConfigurationTests { static class DirtyWebServiceTemplateConfig { @Bean - public WebServiceTemplate webServiceTemplateOne( - WebServiceTemplateBuilder builder) { + public WebServiceTemplate webServiceTemplateOne(WebServiceTemplateBuilder builder) { try { return builder.build(); } @@ -119,8 +115,7 @@ public class WebServiceTemplateAutoConfigurationTests { } @Bean - public WebServiceTemplate webServiceTemplateTwo( - WebServiceTemplateBuilder builder) { + public WebServiceTemplate webServiceTemplateTwo(WebServiceTemplateBuilder builder) { try { return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java index bf8932d5b61..ceeb2609897 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java @@ -85,8 +85,7 @@ public class WebSocketMessagingAutoConfigurationTests { @BeforeEach public void setup() { List transports = Arrays.asList( - new WebSocketTransport( - new StandardWebSocketClient(new WsWebSocketContainer())), + new WebSocketTransport(new StandardWebSocketClient(new WsWebSocketContainer())), new RestTemplateXhrTransport(new RestTemplate())); this.sockJsClient = new SockJsClient(transports); } @@ -100,8 +99,7 @@ public class WebSocketMessagingAutoConfigurationTests { @Test public void basicMessagingWithJsonResponse() throws Throwable { Object result = performStompSubscription("/app/json"); - assertThat(new String((byte[]) result)) - .isEqualTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")); + assertThat(new String((byte[]) result)).isEqualTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")); } @Test @@ -118,8 +116,7 @@ public class WebSocketMessagingAutoConfigurationTests { Iterator customizedIterator = customizedConverters.iterator(); Iterator defaultIterator = defaultConverters.iterator(); while (customizedIterator.hasNext()) { - assertThat(customizedIterator.next()) - .isInstanceOf(defaultIterator.next().getClass()); + assertThat(customizedIterator.next()).isInstanceOf(defaultIterator.next().getClass()); } } @@ -135,16 +132,13 @@ public class WebSocketMessagingAutoConfigurationTests { private List getDefaultConverters() { DelegatingWebSocketMessageBrokerConfiguration configuration = new DelegatingWebSocketMessageBrokerConfiguration(); // We shouldn't usually call this method directly since it's on a non-proxy config - CompositeMessageConverter compositeDefaultConverter = ReflectionTestUtils - .invokeMethod(configuration, "brokerMessageConverter"); - return (List) ReflectionTestUtils - .getField(compositeDefaultConverter, "converters"); + CompositeMessageConverter compositeDefaultConverter = ReflectionTestUtils.invokeMethod(configuration, + "brokerMessageConverter"); + return (List) ReflectionTestUtils.getField(compositeDefaultConverter, "converters"); } private Object performStompSubscription(String topic) throws Throwable { - TestPropertyValues - .of("server.port:0", "spring.jackson.serialization.indent-output:true") - .applyTo(this.context); + TestPropertyValues.of("server.port:0", "spring.jackson.serialization.indent-output:true").applyTo(this.context); this.context.register(WebSocketMessagingConfiguration.class); new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); @@ -155,8 +149,7 @@ public class WebSocketMessagingAutoConfigurationTests { StompSessionHandler handler = new StompSessionHandlerAdapter() { @Override - public void afterConnected(StompSession session, - StompHeaders connectedHeaders) { + public void afterConnected(StompSession session, StompHeaders connectedHeaders) { session.subscribe(topic, new StompFrameHandler() { @Override @@ -179,8 +172,8 @@ public class WebSocketMessagingAutoConfigurationTests { } @Override - public void handleException(StompSession session, StompCommand command, - StompHeaders headers, byte[] payload, Throwable exception) { + public void handleException(StompSession session, StompCommand command, StompHeaders headers, + byte[] payload, Throwable exception) { failure.set(exception); latch.countDown(); } @@ -210,12 +203,9 @@ public class WebSocketMessagingAutoConfigurationTests { @EnableWebSocket @EnableConfigurationProperties @EnableWebSocketMessageBroker - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - WebSocketMessagingAutoConfiguration.class, - DispatcherServletAutoConfiguration.class }) - static class WebSocketMessagingConfiguration - implements WebSocketMessageBrokerConfigurer { + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, + WebSocketMessagingAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) + static class WebSocketMessagingConfiguration implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java index 2bcb669863b..19c14af9a91 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java @@ -65,8 +65,7 @@ public class WebSocketServletAutoConfigurationTests { WebSocketServletAutoConfiguration.JettyWebSocketConfiguration.class); } - private void serverContainerIsAvailableFromTheServletContext( - Class... configuration) { + private void serverContainerIsAvailableFromTheServletContext(Class... configuration) { this.context.register(configuration); this.context.refresh(); Object serverContainer = this.context.getServletContext() diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java index d5d720dfd5b..8c86d2867d2 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,7 @@ public final class SpringCli { } private static void addServiceLoaderCommands(CommandRunner runner) { - ServiceLoader factories = ServiceLoader - .load(CommandFactory.class); + ServiceLoader factories = ServiceLoader.load(CommandFactory.class); for (CommandFactory factory : factories) { runner.addCommands(factory.getCommands()); } @@ -81,8 +80,7 @@ public final class SpringCli { private static URL[] getExtensionURLs() { List urls = new ArrayList<>(); - String home = SystemPropertyUtils - .resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); + String home = SystemPropertyUtils.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); File extDirectory = new File(new File(home, "lib"), "ext"); if (extDirectory.isDirectory()) { for (File file : extDirectory.listFiles()) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java index aaa5c96fab9..76bfa1d54b4 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,12 +59,10 @@ public class SpringApplicationLauncher { public Object launch(Class[] sources, String[] args) throws Exception { Map defaultProperties = new HashMap<>(); defaultProperties.put("spring.groovy.template.check-template-location", "false"); - Class applicationClass = this.classLoader - .loadClass(getSpringApplicationClassName()); + Class applicationClass = this.classLoader.loadClass(getSpringApplicationClassName()); Constructor constructor = applicationClass.getConstructor(Class[].class); Object application = constructor.newInstance((Object) sources); - applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application, - defaultProperties); + applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application, defaultProperties); Method method = applicationClass.getMethod("run", String[].class); return method.invoke(application, (Object) args); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java index 8b1041e2098..5911d47c26e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer * @author Phillip Webb * @since 1.3.0 */ -public class SpringApplicationWebApplicationInitializer - extends SpringBootServletInitializer { +public class SpringApplicationWebApplicationInitializer extends SpringBootServletInitializer { /** * The entry containing the source class. @@ -75,8 +74,7 @@ public class SpringApplicationWebApplicationInitializer for (int i = 0; i < this.sources.length; i++) { sourceClasses[i] = classLoader.loadClass(this.sources[i]); } - return builder.sources(sourceClasses) - .properties("spring.groovy.template.check-template-location=false"); + return builder.sources(sourceClasses).properties("spring.groovy.template.check-template-location=false"); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java index fd1b35f20d2..d1b79432901 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ public final class PackagedSpringApplicationLauncher { } private void run(String[] args) throws Exception { - URLClassLoader classLoader = (URLClassLoader) Thread.currentThread() - .getContextClassLoader(); + URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); new SpringApplicationLauncher(classLoader).launch(getSources(classLoader), args); } @@ -61,8 +60,7 @@ public final class PackagedSpringApplicationLauncher { return loadClasses(classLoader, sources.split(",")); } } - throw new IllegalStateException( - "Cannot locate " + SOURCE_ENTRY + " in MANIFEST.MF"); + throw new IllegalStateException("Cannot locate " + SOURCE_ENTRY + " in MANIFEST.MF"); } private boolean isCliPackaged(Manifest manifest) { @@ -71,8 +69,7 @@ public final class PackagedSpringApplicationLauncher { return getClass().getName().equals(startClass); } - private Class[] loadClasses(ClassLoader classLoader, String[] names) - throws ClassNotFoundException { + private Class[] loadClasses(ClassLoader classLoader, String[] names) throws ClassNotFoundException { Class[] classes = new Class[names.length]; for (int i = 0; i < names.length; i++) { classes[i] = classLoader.loadClass(names[i]); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java index 721695a6fdf..bed6e592e85 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -148,8 +148,7 @@ public class CommandRunner implements Iterable { public Command findCommand(String name) { for (Command candidate : this.commands) { String candidateName = candidate.getName(); - if (candidateName.equals(name) || (isOptionCommand(candidate) - && ("--" + candidateName).equals(name))) { + if (candidateName.equals(name) || (isOptionCommand(candidate) && ("--" + candidateName).equals(name))) { return candidate; } } @@ -252,8 +251,7 @@ public class CommandRunner implements Iterable { if (options.contains(CommandException.Option.SHOW_USAGE)) { showUsage(); } - if (debug || couldNotShowMessage - || options.contains(CommandException.Option.STACK_TRACE)) { + if (debug || couldNotShowMessage || options.contains(CommandException.Option.STACK_TRACE)) { printStackTrace(ex); } return 1; @@ -280,19 +278,16 @@ public class CommandRunner implements Iterable { String usageHelp = command.getUsageHelp(); String description = command.getDescription(); Log.info(String.format("%n %1$s %2$-15s%n %3$s", command.getName(), - (usageHelp != null) ? usageHelp : "", - (description != null) ? description : "")); + (usageHelp != null) ? usageHelp : "", (description != null) ? description : "")); } } Log.info(""); Log.info("Common options:"); - Log.info(String.format("%n %1$s %2$-15s%n %3$s", "-d, --debug", - "Verbose mode", + Log.info(String.format("%n %1$s %2$-15s%n %3$s", "-d, --debug", "Verbose mode", "Print additional status information for the command you are running")); Log.info(""); Log.info(""); - Log.info("See '" + this.name - + "help ' for more information on a specific command."); + Log.info("See '" + this.name + "help ' for more information on a specific command."); } protected void printStackTrace(Exception ex) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java index 0551285c0a5..4ecfe8a5380 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public abstract class OptionParsingCommand extends AbstractCommand { private final OptionHandler handler; - protected OptionParsingCommand(String name, String description, - OptionHandler handler) { + protected OptionParsingCommand(String name, String description, OptionHandler handler) { super(name, description); this.handler = handler; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java index 46c44b8550b..cc719ce2321 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,7 @@ import org.springframework.util.Assert; */ abstract class ArchiveCommand extends OptionParsingCommand { - protected ArchiveCommand(String name, String description, - OptionHandler optionHandler) { + protected ArchiveCommand(String name, String description, OptionHandler optionHandler) { super(name, description, optionHandler); } @@ -111,36 +110,28 @@ abstract class ArchiveCommand extends OptionParsingCommand { @Override protected void doOptions() { this.includeOption = option("include", - "Pattern applied to directories on the classpath to find files to " - + "include in the resulting ").withRequiredArg() - .withValuesSeparatedBy(",").defaultsTo(""); - this.excludeOption = option("exclude", - "Pattern applied to directories on the classpath to find files to " - + "exclude from the resulting " + this.type).withRequiredArg() - .withValuesSeparatedBy(",").defaultsTo(""); + "Pattern applied to directories on the classpath to find files to " + "include in the resulting ") + .withRequiredArg().withValuesSeparatedBy(",").defaultsTo(""); + this.excludeOption = option("exclude", "Pattern applied to directories on the classpath to find files to " + + "exclude from the resulting " + this.type).withRequiredArg().withValuesSeparatedBy(",") + .defaultsTo(""); } @Override protected ExitStatus run(OptionSet options) throws Exception { - List nonOptionArguments = new ArrayList( - options.nonOptionArguments()); - Assert.isTrue(nonOptionArguments.size() >= 2, - () -> "The name of the " + "resulting " + this.type - + " and at least one source file must be " + "specified"); + List nonOptionArguments = new ArrayList(options.nonOptionArguments()); + Assert.isTrue(nonOptionArguments.size() >= 2, () -> "The name of the " + "resulting " + this.type + + " and at least one source file must be " + "specified"); File output = new File((String) nonOptionArguments.remove(0)); - Assert.isTrue( - output.getName().toLowerCase(Locale.ENGLISH) - .endsWith("." + this.type), - () -> "The output '" + output + "' is not a " - + this.type.toUpperCase(Locale.ENGLISH) + " file."); + Assert.isTrue(output.getName().toLowerCase(Locale.ENGLISH).endsWith("." + this.type), + () -> "The output '" + output + "' is not a " + this.type.toUpperCase(Locale.ENGLISH) + " file."); deleteIfExists(output); GroovyCompiler compiler = createCompiler(options); List classpath = getClassPathUrls(compiler); - List classpathEntries = findMatchingClasspathEntries( - classpath, options); + List classpathEntries = findMatchingClasspathEntries(classpath, options); String[] sources = new SourceOptions(nonOptionArguments).getSourcesArray(); Class[] compiledClasses = compiler.compile(sources); @@ -154,16 +145,15 @@ abstract class ArchiveCommand extends OptionParsingCommand { private void deleteIfExists(File file) { if (file.exists() && !file.delete()) { - throw new IllegalStateException( - "Failed to delete existing file " + file.getPath()); + throw new IllegalStateException("Failed to delete existing file " + file.getPath()); } } private GroovyCompiler createCompiler(OptionSet options) { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration( - options, this, repositoryConfiguration); + GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this, + repositoryConfiguration); GroovyCompiler groovyCompiler = new GroovyCompiler(configuration); groovyCompiler.getAstTransformations().add(0, new GrabAnnotationTransform()); return groovyCompiler; @@ -173,10 +163,9 @@ abstract class ArchiveCommand extends OptionParsingCommand { return new ArrayList<>(Arrays.asList(compiler.getLoader().getURLs())); } - private List findMatchingClasspathEntries(List classpath, - OptionSet options) throws IOException { - ResourceMatcher matcher = new ResourceMatcher( - options.valuesOf(this.includeOption), + private List findMatchingClasspathEntries(List classpath, OptionSet options) + throws IOException { + ResourceMatcher matcher = new ResourceMatcher(options.valuesOf(this.includeOption), options.valuesOf(this.excludeOption)); List roots = new ArrayList<>(); for (URL classpathEntry : classpath) { @@ -185,9 +174,8 @@ abstract class ArchiveCommand extends OptionParsingCommand { return matcher.find(roots); } - private void writeJar(File file, Class[] compiledClasses, - List classpathEntries, List dependencies) - throws FileNotFoundException, IOException, URISyntaxException { + private void writeJar(File file, Class[] compiledClasses, List classpathEntries, + List dependencies) throws FileNotFoundException, IOException, URISyntaxException { final List libraries; try (JarWriter writer = new JarWriter(file)) { addManifest(writer, compiledClasses); @@ -207,8 +195,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { }); } - private List createLibraries(List dependencies) - throws URISyntaxException { + private List createLibraries(List dependencies) throws URISyntaxException { List libraries = new ArrayList<>(); for (URL dependency : dependencies) { File file = new File(dependency.toURI()); @@ -217,12 +204,10 @@ abstract class ArchiveCommand extends OptionParsingCommand { return libraries; } - private void addManifest(JarWriter writer, Class[] compiledClasses) - throws IOException { + private void addManifest(JarWriter writer, Class[] compiledClasses) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); - manifest.getMainAttributes().putValue( - PackagedSpringApplicationLauncher.SOURCE_ENTRY, + manifest.getMainAttributes().putValue(PackagedSpringApplicationLauncher.SOURCE_ENTRY, commaDelimitedClassNames(compiledClasses)); writer.writeManifest(manifest); } @@ -245,18 +230,16 @@ abstract class ArchiveCommand extends OptionParsingCommand { .getResources("org/springframework/boot/groovy/**"); for (Resource resource : resources) { String url = resource.getURL().toString(); - addResource(writer, resource, - url.substring(url.indexOf("org/springframework/boot/groovy/"))); + addResource(writer, resource, url.substring(url.indexOf("org/springframework/boot/groovy/"))); } } - protected final void addClass(JarWriter writer, Class sourceClass) - throws IOException { + protected final void addClass(JarWriter writer, Class sourceClass) throws IOException { addClass(writer, sourceClass.getClassLoader(), sourceClass.getName()); } - protected final void addClass(JarWriter writer, ClassLoader classLoader, - String sourceClass) throws IOException { + protected final void addClass(JarWriter writer, ClassLoader classLoader, String sourceClass) + throws IOException { if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } @@ -265,14 +248,12 @@ abstract class ArchiveCommand extends OptionParsingCommand { writer.writeEntry(this.layout.getClassesLocation() + name, stream); } - private void addResource(JarWriter writer, Resource resource, String name) - throws IOException { + private void addResource(JarWriter writer, Resource resource, String name) throws IOException { InputStream stream = resource.getInputStream(); writer.writeEntry(name, stream); } - private List addClasspathEntries(JarWriter writer, - List entries) throws IOException { + private List addClasspathEntries(JarWriter writer, List entries) throws IOException { List libraries = new ArrayList<>(); for (MatchedResource entry : entries) { if (entry.isRoot()) { @@ -285,8 +266,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { return libraries; } - protected void writeClasspathEntry(JarWriter writer, MatchedResource entry) - throws IOException { + protected void writeClasspathEntry(JarWriter writer, MatchedResource entry) throws IOException { writer.writeEntry(entry.getName(), new FileInputStream(entry.getFile())); } @@ -326,8 +306,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { for (AnnotatedNode classNode : nodes) { List annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList<>(annotations)) { - if (node.getClassNode().getNameWithoutPackage() - .equals("GrabResolver")) { + if (node.getClassNode().getNameWithoutPackage().equals("GrabResolver")) { node.setMember("initClass", new ConstantExpression(false)); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java index 5b6b0918455..8ac8fa1eee9 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.boot.loader.tools.LibraryScope; public class JarCommand extends ArchiveCommand { public JarCommand() { - super("jar", "Create a self-contained executable jar " - + "file from a Spring Groovy script", new JarOptionHandler()); + super("jar", "Create a self-contained executable jar " + "file from a Spring Groovy script", + new JarOptionHandler()); } private static final class JarOptionHandler extends ArchiveOptionHandler { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java index 2a4e8beb397..e2d3de9951b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,11 +42,11 @@ import org.springframework.util.StringUtils; */ class ResourceMatcher { - private static final String[] DEFAULT_INCLUDES = { "public/**", "resources/**", - "static/**", "templates/**", "META-INF/**", "*" }; + private static final String[] DEFAULT_INCLUDES = { "public/**", "resources/**", "static/**", "templates/**", + "META-INF/**", "*" }; - private static final String[] DEFAULT_EXCLUDES = { ".*", "repository/**", "build/**", - "target/**", "**/*.jar", "**/*.groovy" }; + private static final String[] DEFAULT_EXCLUDES = { ".*", "repository/**", "build/**", "target/**", "**/*.jar", + "**/*.groovy" }; private final AntPathMatcher pathMatcher = new AntPathMatcher(); @@ -187,8 +187,8 @@ class ResourceMatcher { } private MatchedResource(File rootFolder, File file) { - this.name = StringUtils.cleanPath(file.getAbsolutePath() - .substring(rootFolder.getAbsolutePath().length() + 1)); + this.name = StringUtils + .cleanPath(file.getAbsolutePath().substring(rootFolder.getAbsolutePath().length() + 1)); this.file = file; this.root = false; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java index f42bbf24206..4becf43381e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ import org.springframework.boot.loader.tools.LibraryScope; public class WarCommand extends ArchiveCommand { public WarCommand() { - super("war", "Create a self-contained executable war " - + "file from a Spring Groovy script", new WarOptionHandler()); + super("war", "Create a self-contained executable war " + "file from a Spring Groovy script", + new WarOptionHandler()); } private static final class WarOptionHandler extends ArchiveOptionHandler { @@ -49,8 +49,7 @@ public class WarCommand extends ArchiveCommand { @Override protected LibraryScope getLibraryScope(File file) { String fileName = file.getName(); - if (fileName.contains("tomcat-embed") - || fileName.contains("spring-boot-starter-tomcat")) { + if (fileName.contains("tomcat-embed") || fileName.contains("spring-boot-starter-tomcat")) { return LibraryScope.PROVIDED; } return LibraryScope.COMPILE; @@ -58,16 +57,13 @@ public class WarCommand extends ArchiveCommand { @Override protected void addCliClasses(JarWriter writer) throws IOException { - addClass(writer, null, "org.springframework.boot." - + "cli.app.SpringApplicationWebApplicationInitializer"); + addClass(writer, null, "org.springframework.boot." + "cli.app.SpringApplicationWebApplicationInitializer"); super.addCliClasses(writer); } @Override - protected void writeClasspathEntry(JarWriter writer, - ResourceMatcher.MatchedResource entry) throws IOException { - writer.writeEntry(getLayout().getClassesLocation() + entry.getName(), - new FileInputStream(entry.getFile())); + protected void writeClasspathEntry(JarWriter writer, ResourceMatcher.MatchedResource entry) throws IOException { + writer.writeEntry(getLayout().getClassesLocation() + entry.getName(), new FileInputStream(entry.getFile())); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java index c3dc2665024..8e1f438586a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,12 +94,11 @@ public class HelpCommand extends AbstractCommand { String commandName = args[0]; for (Command command : this.commandRunner) { if (command.getName().equals(commandName)) { - Log.info(this.commandRunner.getName() + command.getName() + " - " - + command.getDescription()); + Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription()); Log.info(""); if (command.getUsageHelp() != null) { - Log.info("usage: " + this.commandRunner.getName() + command.getName() - + " " + command.getUsageHelp()); + Log.info("usage: " + this.commandRunner.getName() + command.getName() + " " + + command.getUsageHelp()); Log.info(""); } if (command.getHelp() != null) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java index d96fadfc1a2..ee074c6bcb8 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,7 @@ public class HintCommand extends AbstractCommand { } else if (!arguments.isEmpty() && !starting.isEmpty()) { String command = arguments.remove(0); - showCommandOptionHints(command, Collections.unmodifiableList(arguments), - starting); + showCommandOptionHints(command, Collections.unmodifiableList(arguments), starting); } } catch (Exception ex) { @@ -83,12 +82,10 @@ public class HintCommand extends AbstractCommand { return false; } return command.getName().startsWith(starting) - || (this.commandRunner.isOptionCommand(command) - && ("--" + command.getName()).startsWith(starting)); + || (this.commandRunner.isOptionCommand(command) && ("--" + command.getName()).startsWith(starting)); } - private void showCommandOptionHints(String commandName, - List specifiedArguments, String starting) { + private void showCommandOptionHints(String commandName, List specifiedArguments, String starting) { Command command = this.commandRunner.findCommand(commandName); if (command != null) { for (OptionHelp help : command.getOptionsHelp()) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java index 6d6cfbbce82..6217133d26e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,16 +52,14 @@ public class EncodePasswordCommand extends OptionParsingCommand { static { Map> encoders = new LinkedHashMap<>(); - encoders.put("default", - PasswordEncoderFactories::createDelegatingPasswordEncoder); + encoders.put("default", PasswordEncoderFactories::createDelegatingPasswordEncoder); encoders.put("bcrypt", BCryptPasswordEncoder::new); encoders.put("pbkdf2", Pbkdf2PasswordEncoder::new); ENCODERS = Collections.unmodifiableMap(encoders); } public EncodePasswordCommand() { - super("encodepassword", "Encode a password for use with Spring Security", - new EncodePasswordOptionHandler()); + super("encodepassword", "Encode a password for use with Spring Security", new EncodePasswordOptionHandler()); } @Override @@ -72,10 +70,9 @@ public class EncodePasswordCommand extends OptionParsingCommand { @Override public Collection getExamples() { List examples = new ArrayList<>(); - examples.add(new HelpExample("To encode a password with the default encoder", - "spring encodepassword mypassword")); - examples.add(new HelpExample("To encode a password with pbkdf2", - "spring encodepassword -a pbkdf2 mypassword")); + examples.add( + new HelpExample("To encode a password with the default encoder", "spring encodepassword mypassword")); + examples.add(new HelpExample("To encode a password with pbkdf2", "spring encodepassword -a pbkdf2 mypassword")); return examples; } @@ -85,8 +82,8 @@ public class EncodePasswordCommand extends OptionParsingCommand { @Override protected void options() { - this.algorithm = option(Arrays.asList("algorithm", "a"), - "The algorithm to use").withRequiredArg().defaultsTo("default"); + this.algorithm = option(Arrays.asList("algorithm", "a"), "The algorithm to use").withRequiredArg() + .defaultsTo("default"); } @Override @@ -99,8 +96,8 @@ public class EncodePasswordCommand extends OptionParsingCommand { String password = (String) options.nonOptionArguments().get(0); Supplier encoder = ENCODERS.get(algorithm); if (encoder == null) { - Log.error("Unknown algorithm, valid options are: " + StringUtils - .collectionToCommaDelimitedString(ENCODERS.keySet())); + Log.error("Unknown algorithm, valid options are: " + + StringUtils.collectionToCommaDelimitedString(ENCODERS.keySet())); return ExitStatus.ERROR; } Log.info(encoder.get().encode(password)); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java index 9807beae4e1..504ba0a28f7 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; public class GrabCommand extends OptionParsingCommand { public GrabCommand() { - super("grab", "Download a spring groovy script's dependencies to ./repository", - new GrabOptionHandler()); + super("grab", "Download a spring groovy script's dependencies to ./repository", new GrabOptionHandler()); } private static final class GrabOptionHandler extends CompilerOptionHandler { @@ -50,8 +49,8 @@ public class GrabCommand extends OptionParsingCommand { SourceOptions sourceOptions = new SourceOptions(options); List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration( - options, this, repositoryConfiguration); + GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this, + repositoryConfiguration); if (System.getProperty("grape.root") == null) { System.setProperty("grape.root", "."); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java index e0127909e22..7335dfff69d 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,9 +47,7 @@ public class InitCommand extends OptionParsingCommand { } public InitCommand(InitOptionHandler handler) { - super("init", - "Initialize a new project using Spring " + "Initializr (start.spring.io)", - handler); + super("init", "Initialize a new project using Spring " + "Initializr (start.spring.io)", handler); } @Override @@ -60,11 +58,9 @@ public class InitCommand extends OptionParsingCommand { @Override public Collection getExamples() { List examples = new ArrayList<>(); - examples.add(new HelpExample("To list all the capabilities of the service", - "spring init --list")); + examples.add(new HelpExample("To list all the capabilities of the service", "spring init --list")); examples.add(new HelpExample("To creates a default project", "spring init")); - examples.add(new HelpExample("To create a web my-app.zip", - "spring init -d=web my-app.zip")); + examples.add(new HelpExample("To create a web my-app.zip", "spring init -d=web my-app.zip")); examples.add(new HelpExample("To create a web/data-jpa gradle project unpacked", "spring init -d=web,jpa --build=gradle my-dir")); return examples; @@ -116,16 +112,14 @@ public class InitCommand extends OptionParsingCommand { private OptionSpec force; InitOptionHandler(InitializrService initializrService) { - this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator( - initializrService); + this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator(initializrService); this.projectGenerator = new ProjectGenerator(initializrService); } @Override protected void options() { - this.target = option(Arrays.asList("target"), "URL of the service to use") - .withRequiredArg() + this.target = option(Arrays.asList("target"), "URL of the service to use").withRequiredArg() .defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL); this.listCapabilities = option(Arrays.asList("list"), "List the capabilities of the service. Use it to discover the " @@ -135,48 +129,40 @@ public class InitCommand extends OptionParsingCommand { } private void projectGenerationOptions() { - this.groupId = option(Arrays.asList("groupId", "g"), - "Project coordinates (for example 'org.test')").withRequiredArg(); - this.artifactId = option(Arrays.asList("artifactId", "a"), - "Project coordinates; infer archive name (for example 'test')") - .withRequiredArg(); - this.version = option(Arrays.asList("version", "v"), - "Project version (for example '0.0.1-SNAPSHOT')").withRequiredArg(); - this.name = option(Arrays.asList("name", "n"), - "Project name; infer application name").withRequiredArg(); - this.description = option("description", "Project description") + this.groupId = option(Arrays.asList("groupId", "g"), "Project coordinates (for example 'org.test')") .withRequiredArg(); + this.artifactId = option(Arrays.asList("artifactId", "a"), + "Project coordinates; infer archive name (for example 'test')").withRequiredArg(); + this.version = option(Arrays.asList("version", "v"), "Project version (for example '0.0.1-SNAPSHOT')") + .withRequiredArg(); + this.name = option(Arrays.asList("name", "n"), "Project name; infer application name").withRequiredArg(); + this.description = option("description", "Project description").withRequiredArg(); this.packageName = option("package-name", "Package name").withRequiredArg(); this.type = option(Arrays.asList("type", "t"), "Project type. Not normally needed if you use --build " - + "and/or --format. Check the capabilities of the service " - + "(--list) for more details").withRequiredArg(); - this.packaging = option(Arrays.asList("packaging", "p"), - "Project packaging (for example 'jar')").withRequiredArg(); - this.build = option("build", - "Build system to use (for example 'maven' or 'gradle')") - .withRequiredArg().defaultsTo("maven"); - this.format = option("format", - "Format of the generated content (for example 'build' for a build file, " - + "'project' for a project archive)").withRequiredArg() - .defaultsTo("project"); - this.javaVersion = option(Arrays.asList("java-version", "j"), - "Language level (for example '1.8')").withRequiredArg(); - this.language = option(Arrays.asList("language", "l"), - "Programming language (for example 'java')").withRequiredArg(); + + "and/or --format. Check the capabilities of the service " + "(--list) for more details") + .withRequiredArg(); + this.packaging = option(Arrays.asList("packaging", "p"), "Project packaging (for example 'jar')") + .withRequiredArg(); + this.build = option("build", "Build system to use (for example 'maven' or 'gradle')").withRequiredArg() + .defaultsTo("maven"); + this.format = option("format", "Format of the generated content (for example 'build' for a build file, " + + "'project' for a project archive)").withRequiredArg().defaultsTo("project"); + this.javaVersion = option(Arrays.asList("java-version", "j"), "Language level (for example '1.8')") + .withRequiredArg(); + this.language = option(Arrays.asList("language", "l"), "Programming language (for example 'java')") + .withRequiredArg(); this.bootVersion = option(Arrays.asList("boot-version", "b"), - "Spring Boot version (for example '1.2.0.RELEASE')") - .withRequiredArg(); + "Spring Boot version (for example '1.2.0.RELEASE')").withRequiredArg(); this.dependencies = option(Arrays.asList("dependencies", "d"), - "Comma-separated list of dependency identifiers to include in the " - + "generated project").withRequiredArg(); + "Comma-separated list of dependency identifiers to include in the " + "generated project") + .withRequiredArg(); } private void otherOptions() { this.extract = option(Arrays.asList("extract", "x"), "Extract the project archive. Inferred if a location is specified without an extension"); - this.force = option(Arrays.asList("force", "f"), - "Force overwrite of existing files"); + this.force = option(Arrays.asList("force", "f"), "Force overwrite of existing files"); } @Override @@ -201,8 +187,7 @@ public class InitCommand extends OptionParsingCommand { } private void generateReport(OptionSet options) throws IOException { - Log.info(this.serviceCapabilitiesReport - .generate(options.valueOf(this.target))); + Log.info(this.serviceCapabilitiesReport.generate(options.valueOf(this.target))); } protected void generateProject(OptionSet options) throws IOException { @@ -210,13 +195,10 @@ public class InitCommand extends OptionParsingCommand { this.projectGenerator.generateProject(request, options.has(this.force)); } - protected ProjectGenerationRequest createProjectGenerationRequest( - OptionSet options) { + protected ProjectGenerationRequest createProjectGenerationRequest(OptionSet options) { - List nonOptionArguments = new ArrayList( - options.nonOptionArguments()); - Assert.isTrue(nonOptionArguments.size() <= 1, - "Only the target location may be specified"); + List nonOptionArguments = new ArrayList(options.nonOptionArguments()); + Assert.isTrue(nonOptionArguments.size() <= 1, "Only the target location may be specified"); ProjectGenerationRequest request = new ProjectGenerationRequest(); request.setServiceUrl(options.valueOf(this.target)); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java index e5d8a644b51..1df24f697e1 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,7 @@ class InitializrService { * Accept header to use to retrieve the service capabilities of the service. If the * service does not offer such feature, the json meta-data are retrieved instead. */ - public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain," - + ACCEPT_META_DATA; + public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain," + ACCEPT_META_DATA; /** * Late binding HTTP client. @@ -86,8 +85,7 @@ class InitializrService { * @return an entity defining the project * @throws IOException if generation fails */ - public ProjectGenerationResponse generate(ProjectGenerationRequest request) - throws IOException { + public ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException { Log.info("Using service at " + request.getServiceUrl()); InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl()); URI url = request.generateUrl(metadata); @@ -104,8 +102,7 @@ class InitializrService { * @throws IOException if the service's metadata cannot be loaded */ public InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException { - CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval( - serviceUrl); + CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval(serviceUrl); validateResponse(httpResponse, serviceUrl); return parseJsonMetadata(httpResponse.getEntity()); } @@ -121,10 +118,8 @@ class InitializrService { */ public Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); - request.setHeader( - new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); - CloseableHttpResponse httpResponse = execute(request, serviceUrl, - "retrieve help"); + request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); + CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); @@ -134,34 +129,29 @@ class InitializrService { return parseJsonMetadata(httpEntity); } - private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) - throws IOException { + private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) throws IOException { try { return new InitializrServiceMetadata(getContentAsJson(httpEntity)); } catch (JSONException ex) { - throw new ReportableException( - "Invalid content received from server (" + ex.getMessage() + ")", ex); + throw new ReportableException("Invalid content received from server (" + ex.getMessage() + ")", ex); } } private void validateResponse(CloseableHttpResponse httpResponse, String serviceUrl) { if (httpResponse.getEntity() == null) { - throw new ReportableException( - "No content received from server '" + serviceUrl + "'"); + throw new ReportableException("No content received from server '" + serviceUrl + "'"); } if (httpResponse.getStatusLine().getStatusCode() != 200) { throw createException(serviceUrl, httpResponse); } } - private ProjectGenerationResponse createResponse(CloseableHttpResponse httpResponse, - HttpEntity httpEntity) throws IOException { - ProjectGenerationResponse response = new ProjectGenerationResponse( - ContentType.getOrDefault(httpEntity)); + private ProjectGenerationResponse createResponse(CloseableHttpResponse httpResponse, HttpEntity httpEntity) + throws IOException { + ProjectGenerationResponse response = new ProjectGenerationResponse(ContentType.getOrDefault(httpEntity)); response.setContent(FileCopyUtils.copyToByteArray(httpEntity.getContent())); - String fileName = extractFileName( - httpResponse.getFirstHeader("Content-Disposition")); + String fileName = extractFileName(httpResponse.getFirstHeader("Content-Disposition")); if (fileName != null) { response.setFileName(fileName); } @@ -188,23 +178,19 @@ class InitializrService { return execute(request, url, "retrieve metadata"); } - private CloseableHttpResponse execute(HttpUriRequest request, Object url, - String description) { + private CloseableHttpResponse execute(HttpUriRequest request, Object url, String description) { try { - request.addHeader("User-Agent", "SpringBootCli/" - + getClass().getPackage().getImplementationVersion()); + request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion()); return getHttp().execute(request); } catch (IOException ex) { - throw new ReportableException("Failed to " + description - + " from service at '" + url + "' (" + ex.getMessage() + ")"); + throw new ReportableException( + "Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")"); } } - private ReportableException createException(String url, - CloseableHttpResponse httpResponse) { - String message = "Initializr service call failed using '" + url - + "' - service returned " + private ReportableException createException(String url, CloseableHttpResponse httpResponse) { + String message = "Initializr service call failed using '" + url + "' - service returned " + httpResponse.getStatusLine().getReasonPhrase(); String error = extractMessage(httpResponse.getEntity()); if (StringUtils.hasText(error)) { @@ -232,8 +218,7 @@ class InitializrService { return null; } - private JSONObject getContentAsJson(HttpEntity entity) - throws IOException, JSONException { + private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException { return new JSONObject(getContent(entity)); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java index 34fa673ed12..440606c7243 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,7 @@ class InitializrServiceMetadata { InitializrServiceMetadata(ProjectType defaultProjectType) { this.dependencies = new HashMap<>(); this.projectTypes = new MetadataHolder<>(); - this.projectTypes.getContent().put(defaultProjectType.getId(), - defaultProjectType); + this.projectTypes.getContent().put(defaultProjectType.getId(), defaultProjectType); this.projectTypes.setDefaultItem(defaultProjectType); this.defaults = new HashMap<>(); } @@ -126,8 +125,7 @@ class InitializrServiceMetadata { return this.defaults; } - private Map parseDependencies(JSONObject root) - throws JSONException { + private Map parseDependencies(JSONObject root) throws JSONException { Map result = new HashMap<>(); if (!root.has(DEPENDENCIES_EL)) { return result; @@ -141,16 +139,14 @@ class InitializrServiceMetadata { return result; } - private MetadataHolder parseProjectTypes(JSONObject root) - throws JSONException { + private MetadataHolder parseProjectTypes(JSONObject root) throws JSONException { MetadataHolder result = new MetadataHolder<>(); if (!root.has(TYPE_EL)) { return result; } JSONObject type = root.getJSONObject(TYPE_EL); JSONArray array = type.getJSONArray(VALUES_EL); - String defaultType = (type.has(DEFAULT_ATTRIBUTE) - ? type.getString(DEFAULT_ATTRIBUTE) : null); + String defaultType = (type.has(DEFAULT_ATTRIBUTE) ? type.getString(DEFAULT_ATTRIBUTE) : null); for (int i = 0; i < array.length(); i++) { JSONObject typeJson = array.getJSONObject(i); ProjectType projectType = parseType(typeJson, defaultType); @@ -178,8 +174,7 @@ class InitializrServiceMetadata { return result; } - private void parseGroup(JSONObject group, Map dependencies) - throws JSONException { + private void parseGroup(JSONObject group, Map dependencies) throws JSONException { if (group.has(VALUES_EL)) { JSONArray content = group.getJSONArray(VALUES_EL); for (int i = 0; i < content.length(); i++) { @@ -196,8 +191,7 @@ class InitializrServiceMetadata { return new Dependency(id, name, description); } - private ProjectType parseType(JSONObject object, String defaultId) - throws JSONException { + private ProjectType parseType(JSONObject object, String defaultId) throws JSONException { String id = getStringValue(object, ID_ATTRIBUTE, null); String name = getStringValue(object, NAME_ATTRIBUTE, null); String action = getStringValue(object, ACTION_ATTRIBUTE, null); @@ -210,8 +204,7 @@ class InitializrServiceMetadata { return new ProjectType(id, name, action, defaultType, tags); } - private String getStringValue(JSONObject object, String name, String defaultValue) - throws JSONException { + private String getStringValue(JSONObject object, String name, String defaultValue) throws JSONException { return object.has(name) ? object.getString(name) : defaultValue; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java index e71f1212ca4..35109cf8730 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -317,8 +317,7 @@ class ProjectGenerationRequest { builder.setPath(sb.toString()); if (!this.dependencies.isEmpty()) { - builder.setParameter("dependencies", - StringUtils.collectionToCommaDelimitedString(this.dependencies)); + builder.setParameter("dependencies", StringUtils.collectionToCommaDelimitedString(this.dependencies)); } if (this.groupId != null) { @@ -359,8 +358,7 @@ class ProjectGenerationRequest { return builder.build(); } catch (URISyntaxException ex) { - throw new ReportableException( - "Invalid service URL (" + ex.getMessage() + ")"); + throw new ReportableException("Invalid service URL (" + ex.getMessage() + ")"); } } @@ -368,8 +366,8 @@ class ProjectGenerationRequest { if (this.type != null) { ProjectType result = metadata.getProjectTypes().get(this.type); if (result == null) { - throw new ReportableException(("No project type with id '" + this.type - + "' - check the service capabilities (--list)")); + throw new ReportableException( + ("No project type with id '" + this.type + "' - check the service capabilities (--list)")); } return result; } @@ -385,22 +383,19 @@ class ProjectGenerationRequest { return types.values().iterator().next(); } else if (types.isEmpty()) { - throw new ReportableException("No type found with build '" + this.build - + "' and format '" + this.format + throw new ReportableException("No type found with build '" + this.build + "' and format '" + this.format + "' check the service capabilities (--list)"); } else { - throw new ReportableException("Multiple types found with build '" - + this.build + "' and format '" + this.format - + "' use --type with a more specific value " + types.keySet()); + throw new ReportableException("Multiple types found with build '" + this.build + "' and format '" + + this.format + "' use --type with a more specific value " + types.keySet()); } } else { ProjectType defaultType = metadata.getDefaultType(); if (defaultType == null) { - throw new ReportableException( - ("No project type is set and no default is defined. " - + "Check the service capabilities (--list)")); + throw new ReportableException(("No project type is set and no default is defined. " + + "Check the service capabilities (--list)")); } return defaultType; } @@ -421,10 +416,8 @@ class ProjectGenerationRequest { return null; } - private static void filter(Map projects, String tag, - String tagValue) { - projects.entrySet().removeIf( - (entry) -> !tagValue.equals(entry.getValue().getTags().get(tag))); + private static void filter(Map projects, String tag, String tagValue) { + projects.entrySet().removeIf((entry) -> !tagValue.equals(entry.getValue().getTags().get(tag))); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java index 14a87b74933..ab3a9b364f0 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java @@ -42,11 +42,9 @@ class ProjectGenerator { this.initializrService = initializrService; } - public void generateProject(ProjectGenerationRequest request, boolean force) - throws IOException { + public void generateProject(ProjectGenerationRequest request, boolean force) throws IOException { ProjectGenerationResponse response = this.initializrService.generate(request); - String fileName = (request.getOutput() != null) ? request.getOutput() - : response.getFileName(); + String fileName = (request.getOutput() != null) ? request.getOutput() : response.getFileName(); if (shouldExtract(request, response)) { if (isZipArchive(response)) { extractProject(response, request.getOutput(), force); @@ -59,10 +57,8 @@ class ProjectGenerator { } } if (fileName == null) { - throw new ReportableException( - "Could not save the project, the server did not set a preferred " - + "file name and no location was set. Specify the output location " - + "for the project."); + throw new ReportableException("Could not save the project, the server did not set a preferred " + + "file name and no location was set. Specify the output location " + "for the project."); } writeProject(response, fileName, force); } @@ -73,14 +69,12 @@ class ProjectGenerator { * @param response the generation response * @return if the project should be extracted */ - private boolean shouldExtract(ProjectGenerationRequest request, - ProjectGenerationResponse response) { + private boolean shouldExtract(ProjectGenerationRequest request, ProjectGenerationResponse response) { if (request.isExtract()) { return true; } // explicit name hasn't been provided for an archive and there is no extension - if (isZipArchive(response) && request.getOutput() != null - && !request.getOutput().contains(".")) { + if (isZipArchive(response) && request.getOutput() != null && !request.getOutput().contains(".")) { return true; } return false; @@ -98,15 +92,12 @@ class ProjectGenerator { return false; } - private void extractProject(ProjectGenerationResponse entity, String output, - boolean overwrite) throws IOException { - File outputFolder = (output != null) ? new File(output) - : new File(System.getProperty("user.dir")); + private void extractProject(ProjectGenerationResponse entity, String output, boolean overwrite) throws IOException { + File outputFolder = (output != null) ? new File(output) : new File(System.getProperty("user.dir")); if (!outputFolder.exists()) { outputFolder.mkdirs(); } - try (ZipInputStream zipStream = new ZipInputStream( - new ByteArrayInputStream(entity.getContent()))) { + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(entity.getContent()))) { extractFromStream(zipStream, overwrite, outputFolder); fixExecutableFlag(outputFolder, "mvnw"); fixExecutableFlag(outputFolder, "gradlew"); @@ -114,29 +105,24 @@ class ProjectGenerator { } } - private void extractFromStream(ZipInputStream zipStream, boolean overwrite, - File outputFolder) throws IOException { + private void extractFromStream(ZipInputStream zipStream, boolean overwrite, File outputFolder) throws IOException { ZipEntry entry = zipStream.getNextEntry(); String canonicalOutputPath = outputFolder.getCanonicalPath() + File.separator; while (entry != null) { File file = new File(outputFolder, entry.getName()); String canonicalEntryPath = file.getCanonicalPath(); if (!canonicalEntryPath.startsWith(canonicalOutputPath)) { - throw new ReportableException("Entry '" + entry.getName() - + "' would be written to '" + canonicalEntryPath - + "'. This is outside the output location of '" - + canonicalOutputPath + throw new ReportableException("Entry '" + entry.getName() + "' would be written to '" + + canonicalEntryPath + "'. This is outside the output location of '" + canonicalOutputPath + "'. Verify your target server configuration."); } if (file.exists() && !overwrite) { - throw new ReportableException((file.isDirectory() ? "Directory" : "File") - + " '" + file.getName() + throw new ReportableException((file.isDirectory() ? "Directory" : "File") + " '" + file.getName() + "' already exists. Use --force if you want to overwrite or " + "specify an alternate location."); } if (!entry.isDirectory()) { - FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), - new FileOutputStream(file)); + FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), new FileOutputStream(file)); } else { file.mkdir(); @@ -146,18 +132,16 @@ class ProjectGenerator { } } - private void writeProject(ProjectGenerationResponse entity, String output, - boolean overwrite) throws IOException { + private void writeProject(ProjectGenerationResponse entity, String output, boolean overwrite) throws IOException { File outputFile = new File(output); if (outputFile.exists()) { if (!overwrite) { - throw new ReportableException("File '" + outputFile.getName() - + "' already exists. Use --force if you want to " - + "overwrite or specify an alternate location."); + throw new ReportableException( + "File '" + outputFile.getName() + "' already exists. Use --force if you want to " + + "overwrite or specify an alternate location."); } if (!outputFile.delete()) { - throw new ReportableException( - "Failed to delete existing file " + outputFile.getPath()); + throw new ReportableException("Failed to delete existing file " + outputFile.getPath()); } } FileCopyUtils.copy(entity.getContent(), outputFile); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java index 7ba14e5dd6c..0e3b7e0e30a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ class ProjectType { private final Map tags = new HashMap<>(); - ProjectType(String id, String name, String action, boolean defaultType, - Map tags) { + ProjectType(String id, String name, String action, boolean defaultType, Map tags) { this.id = id; this.name = name; this.action = action; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java index 55df3ada3d5..c96bc3352f1 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java @@ -78,8 +78,7 @@ class ServiceCapabilitiesReportGenerator { return report.toString(); } - private void reportAvailableDependencies(InitializrServiceMetadata metadata, - StringBuilder report) { + private void reportAvailableDependencies(InitializrServiceMetadata metadata, StringBuilder report) { report.append("Available dependencies:").append(NEW_LINE); report.append("-----------------------").append(NEW_LINE); List dependencies = getSortedDependencies(metadata); @@ -98,12 +97,10 @@ class ServiceCapabilitiesReportGenerator { return dependencies; } - private void reportAvailableProjectTypes(InitializrServiceMetadata metadata, - StringBuilder report) { + private void reportAvailableProjectTypes(InitializrServiceMetadata metadata, StringBuilder report) { report.append("Available project types:").append(NEW_LINE); report.append("------------------------").append(NEW_LINE); - SortedSet> entries = new TreeSet<>( - Comparator.comparing(Entry::getKey)); + SortedSet> entries = new TreeSet<>(Comparator.comparing(Entry::getKey)); entries.addAll(metadata.getProjectTypes().entrySet()); for (Entry entry : entries) { ProjectType type = entry.getValue(); @@ -132,16 +129,14 @@ class ServiceCapabilitiesReportGenerator { report.append("]"); } - private void reportDefaults(StringBuilder report, - InitializrServiceMetadata metadata) { + private void reportDefaults(StringBuilder report, InitializrServiceMetadata metadata) { report.append("Defaults:").append(NEW_LINE); report.append("---------").append(NEW_LINE); List defaultsKeys = new ArrayList<>(metadata.getDefaults().keySet()); Collections.sort(defaultsKeys); for (String defaultsKey : defaultsKeys) { String defaultsValue = metadata.getDefaults().get(defaultsKey); - report.append(defaultsKey).append(": ").append(defaultsValue) - .append(NEW_LINE); + report.append(defaultsKey).append(": ").append(defaultsValue).append(NEW_LINE); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java index f4867da0557..7a564683161 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ class GroovyGrabDependencyResolver implements DependencyResolver { } @Override - public List resolve(List artifactIdentifiers) - throws CompilationFailedException, IOException { + public List resolve(List artifactIdentifiers) throws CompilationFailedException, IOException { GroovyCompiler groovyCompiler = new GroovyCompiler(this.configuration); List artifactFiles = new ArrayList<>(); if (!artifactIdentifiers.isEmpty()) { @@ -70,8 +69,7 @@ class GroovyGrabDependencyResolver implements DependencyResolver { private String createSources(List artifactIdentifiers) throws IOException { File file = File.createTempFile("SpringCLIDependency", ".groovy"); file.deleteOnExit(); - try (OutputStreamWriter stream = new OutputStreamWriter( - new FileOutputStream(file), StandardCharsets.UTF_8)) { + try (OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { for (String artifactIdentifier : artifactIdentifiers) { stream.write("@Grab('" + artifactIdentifier + "')"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java index 177070c9a42..c8bc37ab96f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.util.Assert; public class InstallCommand extends OptionParsingCommand { public InstallCommand() { - super("install", "Install dependencies to the lib/ext directory", - new InstallOptionHandler()); + super("install", "Install dependencies to the lib/ext directory", new InstallOptionHandler()); } @Override @@ -52,8 +51,8 @@ public class InstallCommand extends OptionParsingCommand { @SuppressWarnings("unchecked") protected ExitStatus run(OptionSet options) throws Exception { List args = (List) options.nonOptionArguments(); - Assert.notEmpty(args, "Please specify at least one " - + "dependency, in the form group:artifact:version, to install"); + Assert.notEmpty(args, + "Please specify at least one " + "dependency, in the form group:artifact:version, to install"); try { new Installer(options, this).install(args); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java index e8881500fee..53aeef9a4d4 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,10 +45,8 @@ class Installer { private final Properties installCounts; - Installer(OptionSet options, CompilerOptionHandler compilerOptionHandler) - throws IOException { - this(new GroovyGrabDependencyResolver( - createCompilerConfiguration(options, compilerOptionHandler))); + Installer(OptionSet options, CompilerOptionHandler compilerOptionHandler) throws IOException { + this(new GroovyGrabDependencyResolver(createCompilerConfiguration(options, compilerOptionHandler))); } Installer(DependencyResolver resolver) throws IOException { @@ -56,12 +54,11 @@ class Installer { this.installCounts = loadInstallCounts(); } - private static GroovyCompilerConfiguration createCompilerConfiguration( - OptionSet options, CompilerOptionHandler compilerOptionHandler) { + private static GroovyCompilerConfiguration createCompilerConfiguration(OptionSet options, + CompilerOptionHandler compilerOptionHandler) { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler, - repositoryConfiguration) { + return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler, repositoryConfiguration) { @Override public boolean isAutoconfigure() { return false; @@ -94,8 +91,7 @@ class Installer { for (File artifactFile : artifactFiles) { int installCount = getInstallCount(artifactFile); if (installCount == 0) { - FileCopyUtils.copy(artifactFile, - new File(extDirectory, artifactFile.getName())); + FileCopyUtils.copy(artifactFile, new File(extDirectory, artifactFile.getName())); } setInstallCount(artifactFile, installCount + 1); } @@ -144,12 +140,10 @@ class Installer { } private File getDefaultExtDirectory() { - String home = SystemPropertyUtils - .resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); + String home = SystemPropertyUtils.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); File extDirectory = new File(new File(home, "lib"), "ext"); if (!extDirectory.isDirectory() && !extDirectory.mkdirs()) { - throw new IllegalStateException( - "Failed to create ext directory " + extDirectory); + throw new IllegalStateException("Failed to create ext directory " + extDirectory); } return extDirectory; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java index 3c3b40761cd..892bdfba98f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.boot.cli.util.Log; public class UninstallCommand extends OptionParsingCommand { public UninstallCommand() { - super("uninstall", "Uninstall dependencies from the lib/ext directory", - new UninstallOptionHandler()); + super("uninstall", "Uninstall dependencies from the lib/ext directory", new UninstallOptionHandler()); } @Override @@ -62,8 +61,7 @@ public class UninstallCommand extends OptionParsingCommand { try { if (options.has(this.allOption)) { if (!args.isEmpty()) { - throw new IllegalArgumentException( - "Please use --all without specifying any dependencies"); + throw new IllegalArgumentException("Please use --all without specifying any dependencies"); } new Installer(options, this).uninstallAll(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java index 1088373c39e..6ce043a31da 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,15 +39,12 @@ public class CompilerOptionHandler extends OptionHandler { @Override protected final void options() { - this.noGuessImportsOption = option("no-guess-imports", - "Do not attempt to guess imports"); - this.noGuessDependenciesOption = option("no-guess-dependencies", - "Do not attempt to guess dependencies"); - this.autoconfigureOption = option("autoconfigure", - "Add autoconfigure compiler transformations").withOptionalArg() - .ofType(Boolean.class).defaultsTo(true); - this.classpathOption = option(Arrays.asList("classpath", "cp"), - "Additional classpath entries").withRequiredArg(); + this.noGuessImportsOption = option("no-guess-imports", "Do not attempt to guess imports"); + this.noGuessDependenciesOption = option("no-guess-dependencies", "Do not attempt to guess dependencies"); + this.autoconfigureOption = option("autoconfigure", "Add autoconfigure compiler transformations") + .withOptionalArg().ofType(Boolean.class).defaultsTo(true); + this.classpathOption = option(Arrays.asList("classpath", "cp"), "Additional classpath entries") + .withRequiredArg(); doOptions(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java index c5f52184031..4b8ccf32913 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -130,8 +130,8 @@ public class OptionHandler { @Override public String format(Map options) { - Comparator comparator = Comparator.comparing( - (optionDescriptor) -> optionDescriptor.options().iterator().next()); + Comparator comparator = Comparator + .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java index 9ef1f87d225..0b393532398 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,14 +40,11 @@ public class OptionSetGroovyCompilerConfiguration implements GroovyCompilerConfi private final List repositoryConfiguration; - protected OptionSetGroovyCompilerConfiguration(OptionSet optionSet, - CompilerOptionHandler compilerOptionHandler) { - this(optionSet, compilerOptionHandler, - RepositoryConfigurationFactory.createDefaultRepositoryConfiguration()); + protected OptionSetGroovyCompilerConfiguration(OptionSet optionSet, CompilerOptionHandler compilerOptionHandler) { + this(optionSet, compilerOptionHandler, RepositoryConfigurationFactory.createDefaultRepositoryConfiguration()); } - public OptionSetGroovyCompilerConfiguration(OptionSet optionSet, - CompilerOptionHandler compilerOptionHandler, + public OptionSetGroovyCompilerConfiguration(OptionSet optionSet, CompilerOptionHandler compilerOptionHandler, List repositoryConfiguration) { this.options = optionSet; this.optionHandler = compilerOptionHandler; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java index d2218e773b8..9e360e46c07 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,8 +103,7 @@ public class SourceOptions { } } } - this.args = Collections.unmodifiableList( - nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size())); + this.args = Collections.unmodifiableList(nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size())); Assert.isTrue(!sources.isEmpty(), "Please specify at least one file"); this.sources = Collections.unmodifiableList(sources); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java index 40b1398ac57..4ba76ef4a0e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,7 @@ public class RunCommand extends OptionParsingCommand { @Override protected void doOptions() { this.watchOption = option("watch", "Watch the specified file for changes"); - this.verboseOption = option(Arrays.asList("verbose", "v"), - "Verbose logging of dependency resolution"); + this.verboseOption = option(Arrays.asList("verbose", "v"), "Verbose logging of dependency resolution"); this.quietOption = option(Arrays.asList("quiet", "q"), "Quiet logging"); } @@ -100,14 +99,14 @@ public class RunCommand extends OptionParsingCommand { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - repositoryConfiguration.add(0, new RepositoryConfiguration("local", - new File("repository").toURI(), true)); + repositoryConfiguration.add(0, + new RepositoryConfiguration("local", new File("repository").toURI(), true)); SpringApplicationRunnerConfiguration configuration = new SpringApplicationRunnerConfigurationAdapter( options, this, repositoryConfiguration); - this.runner = new SpringApplicationRunner(configuration, - sourceOptions.getSourcesArray(), sourceOptions.getArgsArray()); + this.runner = new SpringApplicationRunner(configuration, sourceOptions.getSourcesArray(), + sourceOptions.getArgsArray()); this.runner.compileAndRun(); return ExitStatus.OK; @@ -118,12 +117,10 @@ public class RunCommand extends OptionParsingCommand { * Simple adapter class to present the {@link OptionSet} as a * {@link SpringApplicationRunnerConfiguration}. */ - private class SpringApplicationRunnerConfigurationAdapter - extends OptionSetGroovyCompilerConfiguration + private class SpringApplicationRunnerConfigurationAdapter extends OptionSetGroovyCompilerConfiguration implements SpringApplicationRunnerConfiguration { - SpringApplicationRunnerConfigurationAdapter(OptionSet options, - CompilerOptionHandler optionHandler, + SpringApplicationRunnerConfigurationAdapter(OptionSet options, CompilerOptionHandler optionHandler, List repositoryConfiguration) { super(options, optionHandler, repositoryConfiguration); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java index 967d6b45c53..e48825cea8d 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,17 +65,14 @@ public class SpringApplicationRunner { * @param sources the files to compile/watch * @param args input arguments */ - SpringApplicationRunner(SpringApplicationRunnerConfiguration configuration, - String[] sources, String... args) { + SpringApplicationRunner(SpringApplicationRunnerConfiguration configuration, String[] sources, String... args) { this.configuration = configuration; this.sources = sources.clone(); this.args = args.clone(); this.compiler = new GroovyCompiler(configuration); int level = configuration.getLogLevel().intValue(); if (level <= Level.FINER.intValue()) { - System.setProperty( - "org.springframework.boot.cli.compiler.grape.ProgressReporter", - "detail"); + System.setProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter", "detail"); System.setProperty("trace", "true"); } else if (level <= Level.FINE.intValue()) { @@ -84,9 +81,7 @@ public class SpringApplicationRunner { else if (level == Level.OFF.intValue()) { System.setProperty("spring.main.banner-mode", "OFF"); System.setProperty("logging.level.ROOT", "OFF"); - System.setProperty( - "org.springframework.boot.cli.compiler.grape.ProgressReporter", - "none"); + System.setProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter", "none"); } } @@ -128,8 +123,7 @@ public class SpringApplicationRunner { private Class[] compile() throws IOException { Class[] compiledSources = this.compiler.compile(this.sources); if (compiledSources.length == 0) { - throw new RuntimeException( - "No classes found in '" + Arrays.toString(this.sources) + "'"); + throw new RuntimeException("No classes found in '" + Arrays.toString(this.sources) + "'"); } return compiledSources; } @@ -169,9 +163,8 @@ public class SpringApplicationRunner { public void run() { synchronized (this.monitor) { try { - this.applicationContext = new SpringApplicationLauncher( - getContextClassLoader()).launch(this.compiledSources, - SpringApplicationRunner.this.args); + this.applicationContext = new SpringApplicationLauncher(getContextClassLoader()) + .launch(this.compiledSources, SpringApplicationRunner.this.args); } catch (Exception ex) { ex.printStackTrace(); @@ -186,8 +179,7 @@ public class SpringApplicationRunner { synchronized (this.monitor) { if (this.applicationContext != null) { try { - Method method = this.applicationContext.getClass() - .getMethod("close"); + Method method = this.applicationContext.getClass().getMethod("close"); method.invoke(this.applicationContext); } catch (NoSuchMethodException ex) { @@ -232,8 +224,7 @@ public class SpringApplicationRunner { private List getSourceFiles() { List sources = new ArrayList<>(); for (String source : SpringApplicationRunner.this.sources) { - List paths = ResourceUtils.getUrls(source, - SpringApplicationRunner.this.compiler.getLoader()); + List paths = ResourceUtils.getUrls(source, SpringApplicationRunner.this.compiler.getLoader()); for (String path : paths) { try { URL url = new URL(path); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java index a8043441fee..f3e8423ea36 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration; * * @author Phillip Webb */ -public interface SpringApplicationRunnerConfiguration - extends GroovyCompilerConfiguration { +public interface SpringApplicationRunnerConfiguration extends GroovyCompilerConfiguration { /** * Returns {@code true} if the source file should be monitored for changes and diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java index 9e703fc7fbf..61e771db2a3 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,8 @@ public class CommandCompleter extends StringsCompleter { private final ConsoleReader console; - public CommandCompleter(ConsoleReader consoleReader, - ArgumentDelimiter argumentDelimiter, Iterable commands) { + public CommandCompleter(ConsoleReader consoleReader, ArgumentDelimiter argumentDelimiter, + Iterable commands) { this.console = consoleReader; List names = new ArrayList<>(); for (Command command : commands) { @@ -59,10 +59,9 @@ public class CommandCompleter extends StringsCompleter { for (OptionHelp optionHelp : command.getOptionsHelp()) { options.addAll(optionHelp.getOptions()); } - AggregateCompleter argumentCompleters = new AggregateCompleter( - new StringsCompleter(options), new FileNameCompleter()); - ArgumentCompleter argumentCompleter = new ArgumentCompleter(argumentDelimiter, - argumentCompleters); + AggregateCompleter argumentCompleters = new AggregateCompleter(new StringsCompleter(options), + new FileNameCompleter()); + ArgumentCompleter argumentCompleter = new ArgumentCompleter(argumentDelimiter, argumentCompleters); argumentCompleter.setStrict(false); this.commandCompleters.put(command.getName(), argumentCompleter); } @@ -99,16 +98,15 @@ public class CommandCompleter extends StringsCompleter { for (OptionHelp optionHelp : command.getOptionsHelp()) { OptionHelpLine optionHelpLine = new OptionHelpLine(optionHelp); optionHelpLines.add(optionHelpLine); - maxOptionsLength = Math.max(maxOptionsLength, - optionHelpLine.getOptions().length()); + maxOptionsLength = Math.max(maxOptionsLength, optionHelpLine.getOptions().length()); } this.console.println(); this.console.println("Usage:"); this.console.println(command.getName() + " " + command.getUsageHelp()); for (OptionHelpLine optionHelpLine : optionHelpLines) { - this.console.println(String.format("\t%" + maxOptionsLength + "s: %s", - optionHelpLine.getOptions(), optionHelpLine.getUsage())); + this.console.println(String.format("\t%" + maxOptionsLength + "s: %s", optionHelpLine.getOptions(), + optionHelpLine.getUsage())); } this.console.drawLine(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java index 29965b3811d..6dbeb8eb502 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ class EscapeAwareWhiteSpaceArgumentDelimiter extends WhitespaceArgumentDelimiter if (closingQuote == -1) { return false; } - int openingQuote = searchBackwards(buffer, closingQuote - 1, - buffer.charAt(closingQuote)); + int openingQuote = searchBackwards(buffer, closingQuote - 1, buffer.charAt(closingQuote)); if (openingQuote == -1) { return true; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java index 96b3f8a7e3e..23dbe161cf8 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,8 +87,7 @@ public class Shell { private Iterable getCommands() { List commands = new ArrayList<>(); - ServiceLoader factories = ServiceLoader.load(CommandFactory.class, - getClass().getClassLoader()); + ServiceLoader factories = ServiceLoader.load(CommandFactory.class, getClass().getClassLoader()); for (CommandFactory factory : factories) { for (Command command : factory.getCommands()) { commands.add(convertToForkCommand(command)); @@ -113,8 +112,8 @@ public class Shell { this.consoleReader.setHistoryEnabled(true); this.consoleReader.setBellEnabled(false); this.consoleReader.setExpandEvents(false); - this.consoleReader.addCompleter(new CommandCompleter(this.consoleReader, - this.argumentDelimiter, this.commandRunner)); + this.consoleReader + .addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner)); this.consoleReader.setCompletionHandler(new CandidateListCompletionHandler()); } @@ -142,8 +141,7 @@ public class Shell { String version = getClass().getPackage().getImplementationVersion(); version = (version != null) ? " (v" + version + ")" : ""; System.out.println(ansi("Spring Boot", Code.BOLD).append(version, Code.FAINT)); - System.out.println(ansi("Hit TAB to complete. Type 'help' and hit " - + "RETURN for help, and 'exit' to quit.")); + System.out.println(ansi("Hit TAB to complete. Type 'help' and hit " + "RETURN for help, and 'exit' to quit.")); } private void runInputLoop() throws Exception { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java index df024442f9a..5f33eca4006 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio private SourceUnit sourceUnit; - protected AnnotatedNodeASTTransformation(Set interestingAnnotationNames, - boolean removeAnnotations) { + protected AnnotatedNodeASTTransformation(Set interestingAnnotationNames, boolean removeAnnotations) { this.interestingAnnotationNames = interestingAnnotationNames; this.removeAnnotations = removeAnnotations; } @@ -67,10 +66,10 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio for (ImportNode importNode : module.getStarImports()) { visitAnnotatedNode(importNode, annotationNodes); } - module.getStaticImports().forEach((name, - importNode) -> visitAnnotatedNode(importNode, annotationNodes)); - module.getStaticStarImports().forEach((name, - importNode) -> visitAnnotatedNode(importNode, annotationNodes)); + module.getStaticImports() + .forEach((name, importNode) -> visitAnnotatedNode(importNode, annotationNodes)); + module.getStaticStarImports() + .forEach((name, importNode) -> visitAnnotatedNode(importNode, annotationNodes)); for (ClassNode classNode : module.getClasses()) { visitAnnotatedNode(classNode, annotationNodes); classNode.visitContents(classVisitor); @@ -86,15 +85,12 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio protected abstract void processAnnotationNodes(List annotationNodes); - private void visitAnnotatedNode(AnnotatedNode annotatedNode, - List annotatedNodes) { + private void visitAnnotatedNode(AnnotatedNode annotatedNode, List annotatedNodes) { if (annotatedNode != null) { - Iterator annotationNodes = annotatedNode.getAnnotations() - .iterator(); + Iterator annotationNodes = annotatedNode.getAnnotations().iterator(); while (annotationNodes.hasNext()) { AnnotationNode annotationNode = annotationNodes.next(); - if (this.interestingAnnotationNames - .contains(annotationNode.getClassNode().getName())) { + if (this.interestingAnnotationNames.contains(annotationNode.getClassNode().getName())) { annotatedNodes.add(annotationNode); if (this.removeAnnotations) { annotationNodes.remove(); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java index c101bbe42ff..a486ac08afe 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,12 +76,10 @@ public abstract class AstUtils { * @return {@code true} if at least one of the annotations is found, otherwise * {@code false} */ - public static boolean hasAtLeastOneAnnotation(AnnotatedNode node, - String... annotations) { + public static boolean hasAtLeastOneAnnotation(AnnotatedNode node, String... annotations) { for (AnnotationNode annotationNode : node.getAnnotations()) { for (String annotation : annotations) { - if (PatternMatchUtils.simpleMatch(annotation, - annotationNode.getClassNode().getName())) { + if (PatternMatchUtils.simpleMatch(annotation, annotationNode.getClassNode().getName())) { return true; } } @@ -147,13 +145,11 @@ public abstract class AstUtils { * @param remove whether or not the extracted closure should be removed * @return a beans Closure if one can be found, null otherwise */ - public static ClosureExpression getClosure(BlockStatement block, String name, - boolean remove) { + public static ClosureExpression getClosure(BlockStatement block, String name, boolean remove) { for (ExpressionStatement statement : getExpressionStatements(block)) { Expression expression = statement.getExpression(); if (expression instanceof MethodCallExpression) { - ClosureExpression closure = getClosure(name, - (MethodCallExpression) expression); + ClosureExpression closure = getClosure(name, (MethodCallExpression) expression); if (closure != null) { if (remove) { block.getStatements().remove(statement); @@ -165,8 +161,7 @@ public abstract class AstUtils { return null; } - private static List getExpressionStatements( - BlockStatement block) { + private static List getExpressionStatements(BlockStatement block) { List statements = new ArrayList<>(); for (Statement statement : block.getStatements()) { if (statement instanceof ExpressionStatement) { @@ -176,13 +171,10 @@ public abstract class AstUtils { return statements; } - private static ClosureExpression getClosure(String name, - MethodCallExpression expression) { + private static ClosureExpression getClosure(String name, MethodCallExpression expression) { Expression method = expression.getMethod(); - if (method instanceof ConstantExpression - && name.equals(((ConstantExpression) method).getValue())) { - return (ClosureExpression) ((ArgumentListExpression) expression - .getArguments()).getExpression(0); + if (method instanceof ConstantExpression && name.equals(((ConstantExpression) method).getValue())) { + return (ClosureExpression) ((ArgumentListExpression) expression.getArguments()).getExpression(0); } return null; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java index 0e31bed7de2..bf918284e88 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public abstract class CompilerAutoConfiguration { * @param dependencies dependency customizer * @throws CompilationFailedException if the dependencies cannot be applied */ - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { } /** @@ -73,9 +72,9 @@ public abstract class CompilerAutoConfiguration { * @param classNode the main class * @throws CompilationFailedException if the customizations cannot be applied */ - public void applyToMainClass(GroovyClassLoader loader, - GroovyCompilerConfiguration configuration, GeneratorContext generatorContext, - SourceUnit source, ClassNode classNode) throws CompilationFailedException { + public void applyToMainClass(GroovyClassLoader loader, GroovyCompilerConfiguration configuration, + GeneratorContext generatorContext, SourceUnit source, ClassNode classNode) + throws CompilationFailedException { } /** diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java index a4f6fc7fbe0..7ccdc6384f7 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,7 @@ public class DependencyCustomizer { } public String getVersion(String artifactId, String defaultVersion) { - String version = this.dependencyResolutionContext.getArtifactCoordinatesResolver() - .getVersion(artifactId); + String version = this.dependencyResolutionContext.getArtifactCoordinatesResolver().getVersion(artifactId); if (version == null) { version = defaultVersion; } @@ -219,22 +218,19 @@ public class DependencyCustomizer { * otherwise {@code false} * @return this {@link DependencyCustomizer} for continued use */ - public DependencyCustomizer add(String module, String classifier, String type, - boolean transitive) { + public DependencyCustomizer add(String module, String classifier, String type, boolean transitive) { if (canAdd()) { ArtifactCoordinatesResolver artifactCoordinatesResolver = this.dependencyResolutionContext .getArtifactCoordinatesResolver(); - this.classNode.addAnnotation( - createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module), - artifactCoordinatesResolver.getArtifactId(module), - artifactCoordinatesResolver.getVersion(module), classifier, - type, transitive)); + this.classNode.addAnnotation(createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module), + artifactCoordinatesResolver.getArtifactId(module), artifactCoordinatesResolver.getVersion(module), + classifier, type, transitive)); } return this; } - private AnnotationNode createGrabAnnotation(String group, String module, - String version, String classifier, String type, boolean transitive) { + private AnnotationNode createGrabAnnotation(String group, String module, String version, String classifier, + String type, boolean transitive) { AnnotationNode annotationNode = new AnnotationNode(new ClassNode(Grab.class)); annotationNode.addMember("group", new ConstantExpression(group)); annotationNode.addMember("module", new ConstantExpression(module)); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java index 061a69a7b2e..8040ebc3bec 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java @@ -65,8 +65,7 @@ import org.springframework.core.annotation.Order; */ @Order(DependencyManagementBomTransformation.ORDER) @SuppressWarnings("deprecation") -public class DependencyManagementBomTransformation - extends AnnotatedNodeASTTransformation { +public class DependencyManagementBomTransformation extends AnnotatedNodeASTTransformation { /** * The order of the transformation. @@ -74,14 +73,12 @@ public class DependencyManagementBomTransformation public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 100; private static final Set DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES = Collections - .unmodifiableSet( - new HashSet<>(Arrays.asList(DependencyManagementBom.class.getName(), - DependencyManagementBom.class.getSimpleName()))); + .unmodifiableSet(new HashSet<>(Arrays.asList(DependencyManagementBom.class.getName(), + DependencyManagementBom.class.getSimpleName()))); private final DependencyResolutionContext resolutionContext; - public DependencyManagementBomTransformation( - DependencyResolutionContext resolutionContext) { + public DependencyManagementBomTransformation(DependencyResolutionContext resolutionContext) { super(DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES, true); this.resolutionContext = resolutionContext; } @@ -108,10 +105,8 @@ public class DependencyManagementBomTransformation private List> createDependencyMaps(Expression valueExpression) { Map dependency = null; - List constantExpressions = getConstantExpressions( - valueExpression); - List> dependencies = new ArrayList<>( - constantExpressions.size()); + List constantExpressions = getConstantExpressions(valueExpression); + List> dependencies = new ArrayList<>(constantExpressions.size()); for (ConstantExpression expression : constantExpressions) { Object value = expression.getValue(); if (value instanceof String) { @@ -140,13 +135,12 @@ public class DependencyManagementBomTransformation && ((ConstantExpression) valueExpression).getValue() instanceof String) { return Arrays.asList((ConstantExpression) valueExpression); } - reportError("@DependencyManagementBom requires an inline constant that is a " - + "string or a string array", valueExpression); + reportError("@DependencyManagementBom requires an inline constant that is a " + "string or a string array", + valueExpression); return Collections.emptyList(); } - private List getConstantExpressions( - ListExpression valueExpression) { + private List getConstantExpressions(ListExpression valueExpression) { List expressions = new ArrayList<>(); for (Expression expression : valueExpression.getExpressions()) { if (expression instanceof ConstantExpression @@ -154,9 +148,7 @@ public class DependencyManagementBomTransformation expressions.add((ConstantExpression) expression); } else { - reportError( - "Each entry in the array must be an " + "inline string constant", - expression); + reportError("Each entry in the array must be an " + "inline string constant", expression); } } return expressions; @@ -164,16 +156,12 @@ public class DependencyManagementBomTransformation private void handleMalformedDependency(Expression expression) { Message message = createSyntaxErrorMessage( - String.format( - "The string must be of the form \"group:module:version\"%n"), - expression); + String.format("The string must be of the form \"group:module:version\"%n"), expression); getSourceUnit().getErrorCollector().addErrorAndContinue(message); } - private void updateDependencyResolutionContext( - List> bomDependencies) { - URI[] uris = Grape.getInstance().resolve(null, - bomDependencies.toArray(new Map[0])); + private void updateDependencyResolutionContext(List> bomDependencies) { + URI[] uris = Grape.getInstance().resolve(null, bomDependencies.toArray(new Map[0])); DefaultModelBuilder modelBuilder = new DefaultModelBuilderFactory().newInstance(); for (URI uri : uris) { try { @@ -182,49 +170,40 @@ public class DependencyManagementBomTransformation request.setModelSource(new UrlModelSource(uri.toURL())); request.setSystemProperties(System.getProperties()); Model model = modelBuilder.build(request).getEffectiveModel(); - this.resolutionContext.addDependencyManagement( - new MavenModelDependencyManagement(model)); + this.resolutionContext.addDependencyManagement(new MavenModelDependencyManagement(model)); } catch (Exception ex) { - throw new IllegalStateException("Failed to build model for '" + uri - + "'. Is it a valid Maven bom?", ex); + throw new IllegalStateException("Failed to build model for '" + uri + "'. Is it a valid Maven bom?", + ex); } } } - private void handleDuplicateDependencyManagementBomAnnotation( - AnnotationNode annotationNode) { + private void handleDuplicateDependencyManagementBomAnnotation(AnnotationNode annotationNode) { Message message = createSyntaxErrorMessage( - "Duplicate @DependencyManagementBom annotation. It must be declared at most once.", - annotationNode); + "Duplicate @DependencyManagementBom annotation. It must be declared at most once.", annotationNode); getSourceUnit().getErrorCollector().addErrorAndContinue(message); } private void reportError(String message, ASTNode node) { - getSourceUnit().getErrorCollector() - .addErrorAndContinue(createSyntaxErrorMessage(message, node)); + getSourceUnit().getErrorCollector().addErrorAndContinue(createSyntaxErrorMessage(message, node)); } private Message createSyntaxErrorMessage(String message, ASTNode node) { - return new SyntaxErrorMessage( - new SyntaxException(message, node.getLineNumber(), node.getColumnNumber(), - node.getLastLineNumber(), node.getLastColumnNumber()), - getSourceUnit()); + return new SyntaxErrorMessage(new SyntaxException(message, node.getLineNumber(), node.getColumnNumber(), + node.getLastLineNumber(), node.getLastColumnNumber()), getSourceUnit()); } private static class GrapeModelResolver implements ModelResolver { @Override public ModelSource resolveModel(Parent parent) throws UnresolvableModelException { - return resolveModel(parent.getGroupId(), parent.getArtifactId(), - parent.getVersion()); + return resolveModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()); } @Override - public ModelSource resolveModel(Dependency dependency) - throws UnresolvableModelException { - return resolveModel(dependency.getGroupId(), dependency.getArtifactId(), - dependency.getVersion()); + public ModelSource resolveModel(Dependency dependency) throws UnresolvableModelException { + return resolveModel(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); } @Override @@ -236,23 +215,19 @@ public class DependencyManagementBomTransformation dependency.put("version", version); dependency.put("type", "pom"); try { - return new UrlModelSource( - Grape.getInstance().resolve(null, dependency)[0].toURL()); + return new UrlModelSource(Grape.getInstance().resolve(null, dependency)[0].toURL()); } catch (MalformedURLException ex) { - throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId, - version); + throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId, version); } } @Override - public void addRepository(Repository repository) - throws InvalidRepositoryException { + public void addRepository(Repository repository) throws InvalidRepositoryException { } @Override - public void addRepository(Repository repository, boolean replace) - throws InvalidRepositoryException { + public void addRepository(Repository repository, boolean replace) throws InvalidRepositoryException { } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java index 57c0ffaae7e..866323c35fd 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,8 +86,7 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { return super.findClass(name); } catch (ClassNotFoundException ex) { - if (this.scope == GroovyCompilerScope.DEFAULT - && name.startsWith(SHARED_PACKAGE)) { + if (this.scope == GroovyCompilerScope.DEFAULT && name.startsWith(SHARED_PACKAGE)) { Class sharedClass = findSharedClass(name); if (sharedClass != null) { return sharedClass; @@ -150,16 +149,14 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { */ protected class ExtendedClassCollector extends ClassCollector { - protected ExtendedClassCollector(InnerLoader loader, CompilationUnit unit, - SourceUnit su) { + protected ExtendedClassCollector(InnerLoader loader, CompilationUnit unit, SourceUnit su) { super(loader, unit, su); } @Override protected Class createClass(byte[] code, ClassNode classNode) { Class createdClass = super.createClass(code, classNode); - ExtendedGroovyClassLoader.this.classResources - .put(classNode.getName().replace('.', '/') + ".class", code); + ExtendedGroovyClassLoader.this.classResources.put(classNode.getName().replace('.', '/') + ".class", code); return createdClass; } @@ -238,8 +235,7 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (!name.startsWith("java.")) { this.groovyOnlyClassLoader.loadClass(name); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java index 523a1b2fd7f..1ef7e457f07 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ import org.springframework.core.Ordered; * @since 1.3.0 */ @GroovyASTTransformation(phase = CompilePhase.CONVERSION) -public abstract class GenericBomAstTransformation - implements SpringBootAstTransformation, Ordered { +public abstract class GenericBomAstTransformation implements SpringBootAstTransformation, Ordered { private static final ClassNode BOM = ClassHelper.make(DependencyManagementBom.class); @@ -80,8 +79,7 @@ public abstract class GenericBomAstTransformation AnnotatedNode annotated = getAnnotatedNode(node); if (annotated != null) { AnnotationNode bom = getAnnotation(annotated); - List expressions = new ArrayList<>( - getConstantExpressions(bom.getMember("value"))); + List expressions = new ArrayList<>(getConstantExpressions(bom.getMember("value"))); expressions.add(new ConstantExpression(module)); bom.setMember("value", new ListExpression(expressions)); } @@ -119,8 +117,7 @@ public abstract class GenericBomAstTransformation return Collections.emptyList(); } - private List getConstantExpressions( - ListExpression valueExpression) { + private List getConstantExpressions(ListExpression valueExpression) { List expressions = new ArrayList<>(); for (Expression expression : valueExpression.getExpressions()) { if (expression instanceof ConstantExpression diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java index 766b762767c..292a043fb9b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,10 +96,8 @@ public class GroovyBeansTransformation implements ASTTransformation { // Implement the interface by adding a public read-only property with the // same name as the method in the interface (getBeans). Make it return the // closure. - this.classNode.addProperty( - new PropertyNode(BEANS, Modifier.PUBLIC | Modifier.FINAL, - ClassHelper.CLOSURE_TYPE.getPlainNodeReference(), - this.classNode, closure, null, null)); + this.classNode.addProperty(new PropertyNode(BEANS, Modifier.PUBLIC | Modifier.FINAL, + ClassHelper.CLOSURE_TYPE.getPlainNodeReference(), this.classNode, closure, null, null)); // Only do this once per class this.xformed = true; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java index 7a5cc87b646..277f9d89f0f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java @@ -92,37 +92,30 @@ public class GroovyCompiler { this.loader = createLoader(configuration); DependencyResolutionContext resolutionContext = new DependencyResolutionContext(); - resolutionContext.addDependencyManagement( - new SpringBootDependenciesDependencyManagement()); + resolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); AetherGrapeEngine grapeEngine = AetherGrapeEngineFactory.create(this.loader, - configuration.getRepositoryConfiguration(), resolutionContext, - configuration.isQuiet()); + configuration.getRepositoryConfiguration(), resolutionContext, configuration.isQuiet()); GrapeEngineInstaller.install(grapeEngine); - this.loader.getConfiguration() - .addCompilationCustomizers(new CompilerAutoConfigureCustomizer()); + this.loader.getConfiguration().addCompilationCustomizers(new CompilerAutoConfigureCustomizer()); if (configuration.isAutoconfigure()) { - this.compilerAutoConfigurations = ServiceLoader - .load(CompilerAutoConfiguration.class); + this.compilerAutoConfigurations = ServiceLoader.load(CompilerAutoConfiguration.class); } else { this.compilerAutoConfigurations = Collections.emptySet(); } this.transformations = new ArrayList<>(); - this.transformations - .add(new DependencyManagementBomTransformation(resolutionContext)); - this.transformations.add(new DependencyAutoConfigurationTransformation( - this.loader, resolutionContext, this.compilerAutoConfigurations)); + this.transformations.add(new DependencyManagementBomTransformation(resolutionContext)); + this.transformations.add(new DependencyAutoConfigurationTransformation(this.loader, resolutionContext, + this.compilerAutoConfigurations)); this.transformations.add(new GroovyBeansTransformation()); if (this.configuration.isGuessDependencies()) { - this.transformations.add( - new ResolveDependencyCoordinatesTransformation(resolutionContext)); + this.transformations.add(new ResolveDependencyCoordinatesTransformation(resolutionContext)); } - for (ASTTransformation transformation : ServiceLoader - .load(SpringBootAstTransformation.class)) { + for (ASTTransformation transformation : ServiceLoader.load(SpringBootAstTransformation.class)) { this.transformations.add(transformation); } this.transformations.sort(AnnotationAwareOrderComparator.INSTANCE); @@ -141,11 +134,9 @@ public class GroovyCompiler { return this.loader; } - private ExtendedGroovyClassLoader createLoader( - GroovyCompilerConfiguration configuration) { + private ExtendedGroovyClassLoader createLoader(GroovyCompilerConfiguration configuration) { - ExtendedGroovyClassLoader loader = new ExtendedGroovyClassLoader( - configuration.getScope()); + ExtendedGroovyClassLoader loader = new ExtendedGroovyClassLoader(configuration.getScope()); for (URL url : getExistingUrls()) { loader.addURL(url); @@ -182,16 +173,14 @@ public class GroovyCompiler { * @throws IOException in case of I/O errors * @throws CompilationFailedException in case of compilation errors */ - public Class[] compile(String... sources) - throws CompilationFailedException, IOException { + public Class[] compile(String... sources) throws CompilationFailedException, IOException { this.loader.clearCache(); List> classes = new ArrayList<>(); CompilerConfiguration configuration = this.loader.getConfiguration(); - CompilationUnit compilationUnit = new CompilationUnit(configuration, null, - this.loader); + CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader); ClassCollector collector = this.loader.createCollector(compilationUnit, null); compilationUnit.setClassgenCallback(collector); @@ -238,8 +227,7 @@ public class GroovyCompiler { return (LinkedList[]) field.get(compilationUnit); } catch (Exception ex) { - throw new IllegalStateException( - "Phase operations not available from compilation unit"); + throw new IllegalStateException("Phase operations not available from compilation unit"); } } @@ -292,12 +280,10 @@ public class GroovyCompiler { } if (classNode.equals(mainClassNode)) { autoConfiguration.applyToMainClass(GroovyCompiler.this.loader, - GroovyCompiler.this.configuration, context, source, - classNode); + GroovyCompiler.this.configuration, context, source, classNode); } - autoConfiguration.apply(GroovyCompiler.this.loader, - GroovyCompiler.this.configuration, context, source, - classNode); + autoConfiguration.apply(GroovyCompiler.this.loader, GroovyCompiler.this.configuration, context, + source, classNode); } } importCustomizer.call(source, context, classNode); @@ -316,8 +302,8 @@ public class GroovyCompiler { if (AstUtils.hasAtLeastOneAnnotation(node, "Enable*AutoConfiguration")) { return null; // No need to enhance this } - if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration", - "Component", "*Service", "Repository", "Enable*")) { + if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration", "Component", "*Service", + "Repository", "Enable*")) { return node; } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java index c0f35bc4a27..871986b553a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,14 +41,14 @@ import org.springframework.util.StringUtils; */ public final class RepositoryConfigurationFactory { - private static final RepositoryConfiguration MAVEN_CENTRAL = new RepositoryConfiguration( - "central", URI.create("https://repo.maven.apache.org/maven2/"), false); + private static final RepositoryConfiguration MAVEN_CENTRAL = new RepositoryConfiguration("central", + URI.create("https://repo.maven.apache.org/maven2/"), false); - private static final RepositoryConfiguration SPRING_MILESTONE = new RepositoryConfiguration( - "spring-milestone", URI.create("https://repo.spring.io/milestone"), false); + private static final RepositoryConfiguration SPRING_MILESTONE = new RepositoryConfiguration("spring-milestone", + URI.create("https://repo.spring.io/milestone"), false); - private static final RepositoryConfiguration SPRING_SNAPSHOT = new RepositoryConfiguration( - "spring-snapshot", URI.create("https://repo.spring.io/snapshot"), true); + private static final RepositoryConfiguration SPRING_SNAPSHOT = new RepositoryConfiguration("spring-snapshot", + URI.create("https://repo.spring.io/snapshot"), true); private RepositoryConfigurationFactory() { } @@ -65,10 +65,8 @@ public final class RepositoryConfigurationFactory { repositoryConfiguration.add(SPRING_MILESTONE); repositoryConfiguration.add(SPRING_SNAPSHOT); } - addDefaultCacheAsRepository(mavenSettings.getLocalRepository(), - repositoryConfiguration); - addActiveProfileRepositories(mavenSettings.getActiveProfiles(), - repositoryConfiguration); + addDefaultCacheAsRepository(mavenSettings.getLocalRepository(), repositoryConfiguration); + addActiveProfileRepositories(mavenSettings.getActiveProfiles(), repositoryConfiguration); return repositoryConfiguration; } @@ -85,16 +83,15 @@ public final class RepositoryConfigurationFactory { List configurations) { for (Profile activeProfile : activeProfiles) { Interpolator interpolator = new RegexBasedInterpolator(); - interpolator.addValueSource( - new PropertiesBasedValueSource(activeProfile.getProperties())); + interpolator.addValueSource(new PropertiesBasedValueSource(activeProfile.getProperties())); for (Repository repository : activeProfile.getRepositories()) { configurations.add(getRepositoryConfiguration(interpolator, repository)); } } } - private static RepositoryConfiguration getRepositoryConfiguration( - Interpolator interpolator, Repository repository) { + private static RepositoryConfiguration getRepositoryConfiguration(Interpolator interpolator, + Repository repository) { String name = interpolate(interpolator, repository.getId()); String url = interpolate(interpolator, repository.getUrl()); boolean snapshotsEnabled = false; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java index 6688636390b..ef20c41a8a5 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java @@ -38,8 +38,7 @@ import org.springframework.core.annotation.Order; * @author Phillip Webb */ @Order(ResolveDependencyCoordinatesTransformation.ORDER) -public class ResolveDependencyCoordinatesTransformation - extends AnnotatedNodeASTTransformation { +public class ResolveDependencyCoordinatesTransformation extends AnnotatedNodeASTTransformation { /** * The order of the transformation. @@ -47,13 +46,11 @@ public class ResolveDependencyCoordinatesTransformation public static final int ORDER = DependencyManagementBomTransformation.ORDER + 300; private static final Set GRAB_ANNOTATION_NAMES = Collections - .unmodifiableSet(new HashSet<>( - Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName()))); + .unmodifiableSet(new HashSet<>(Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName()))); private final DependencyResolutionContext resolutionContext; - public ResolveDependencyCoordinatesTransformation( - DependencyResolutionContext resolutionContext) { + public ResolveDependencyCoordinatesTransformation(DependencyResolutionContext resolutionContext) { super(GRAB_ANNOTATION_NAMES, false); this.resolutionContext = resolutionContext; } @@ -95,12 +92,11 @@ public class ResolveDependencyCoordinatesTransformation module = (String) ((ConstantExpression) expression).getValue(); } if (annotation.getMember("group") == null) { - setMember(annotation, "group", this.resolutionContext - .getArtifactCoordinatesResolver().getGroupId(module)); + setMember(annotation, "group", this.resolutionContext.getArtifactCoordinatesResolver().getGroupId(module)); } if (annotation.getMember("version") == null) { - setMember(annotation, "version", this.resolutionContext - .getArtifactCoordinatesResolver().getVersion(module)); + setMember(annotation, "version", + this.resolutionContext.getArtifactCoordinatesResolver().getVersion(module)); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java index bc1c3340ca0..8c452eb9735 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ class SmartImportCustomizer extends ImportCustomizer { @Override public ImportCustomizer addImport(String alias, String className) { - if (this.source.getAST() - .getImport(ClassHelper.make(className).getNameWithoutPackage()) == null) { + if (this.source.getAST().getImport(ClassHelper.make(className).getNameWithoutPackage()) == null) { super.addImport(alias, className); } return this; @@ -47,8 +46,7 @@ class SmartImportCustomizer extends ImportCustomizer { @Override public ImportCustomizer addImports(String... imports) { for (String alias : imports) { - if (this.source.getAST() - .getImport(ClassHelper.make(alias).getNameWithoutPackage()) == null) { + if (this.source.getAST().getImport(ClassHelper.make(alias).getNameWithoutPackage()) == null) { super.addImports(alias); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java index 21584752cc5..7c14baba4a8 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,15 +38,13 @@ public class CachingCompilerAutoConfiguration extends CompilerAutoConfiguration } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-context-support"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("org.springframework.cache", - "org.springframework.cache.annotation", + imports.addStarImports("org.springframework.cache", "org.springframework.cache.annotation", "org.springframework.cache.concurrent"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java index 698a7671161..f0060141b6f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ public class GroovyTemplatesCompilerAutoConfiguration extends CompilerAutoConfig @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine") - .add("groovy-templates"); + dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates"); } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java index d0cb63f4c4c..86219f8c982 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,20 +32,18 @@ public class JdbcCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneFieldOrMethod(classNode, "JdbcTemplate", - "NamedParameterJdbcTemplate", "DataSource"); + return AstUtils.hasAtLeastOneFieldOrMethod(classNode, "JdbcTemplate", "NamedParameterJdbcTemplate", + "DataSource"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate") - .add("spring-boot-starter-jdbc"); + dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate").add("spring-boot-starter-jdbc"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addStarImports("org.springframework.jdbc.core", - "org.springframework.jdbc.core.namedparam"); + imports.addStarImports("org.springframework.jdbc.core", "org.springframework.jdbc.core.namedparam"); imports.addImports("javax.sql.DataSource"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java index e7f744ce5fb..c0ffeaddc3b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,16 +39,14 @@ public class JmsCompilerAutoConfiguration extends CompilerAutoConfiguration { } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-jms", "javax.jms-api"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("javax.jms", "org.springframework.jms.annotation", - "org.springframework.jms.config", "org.springframework.jms.core", - "org.springframework.jms.listener", + imports.addStarImports("javax.jms", "org.springframework.jms.annotation", "org.springframework.jms.config", + "org.springframework.jms.core", "org.springframework.jms.listener", "org.springframework.jms.listener.adapter"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java index 05062cafcd4..1f5f11ce298 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,20 +39,16 @@ public class RabbitCompilerAutoConfiguration extends CompilerAutoConfiguration { } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-rabbit"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("org.springframework.amqp.rabbit.annotation", - "org.springframework.amqp.rabbit.core", - "org.springframework.amqp.rabbit.config", - "org.springframework.amqp.rabbit.connection", - "org.springframework.amqp.rabbit.listener", - "org.springframework.amqp.rabbit.listener.adapter", + imports.addStarImports("org.springframework.amqp.rabbit.annotation", "org.springframework.amqp.rabbit.core", + "org.springframework.amqp.rabbit.config", "org.springframework.amqp.rabbit.connection", + "org.springframework.amqp.rabbit.listener", "org.springframework.amqp.rabbit.listener.adapter", "org.springframework.amqp.core"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java index d4864241198..36669d72f9e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,10 +38,8 @@ public class SpringBatchCompilerAutoConfiguration extends CompilerAutoConfigurat @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.batch.core.Job") - .add("spring-boot-starter-batch"); - dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate") - .add("spring-jdbc"); + dependencies.ifAnyMissingClasses("org.springframework.batch.core.Job").add("spring-boot-starter-batch"); + dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate").add("spring-jdbc"); } @Override @@ -53,14 +51,10 @@ public class SpringBatchCompilerAutoConfiguration extends CompilerAutoConfigurat "org.springframework.batch.core.configuration.annotation.JobBuilderFactory", "org.springframework.batch.core.configuration.annotation.StepBuilderFactory", "org.springframework.batch.core.configuration.annotation.EnableBatchProcessing", - "org.springframework.batch.core.Step", - "org.springframework.batch.core.StepExecution", - "org.springframework.batch.core.StepContribution", - "org.springframework.batch.core.Job", - "org.springframework.batch.core.JobExecution", - "org.springframework.batch.core.JobParameter", - "org.springframework.batch.core.JobParameters", - "org.springframework.batch.core.launch.JobLauncher", + "org.springframework.batch.core.Step", "org.springframework.batch.core.StepExecution", + "org.springframework.batch.core.StepContribution", "org.springframework.batch.core.Job", + "org.springframework.batch.core.JobExecution", "org.springframework.batch.core.JobParameter", + "org.springframework.batch.core.JobParameters", "org.springframework.batch.core.launch.JobLauncher", "org.springframework.batch.core.converter.JobParametersConverter", "org.springframework.batch.core.converter.DefaultJobParametersConverter"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java index 1c6eae66294..5246bee97f7 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,32 +39,22 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.boot.SpringApplication") - .add("spring-boot-starter"); + dependencies.ifAnyMissingClasses("org.springframework.boot.SpringApplication").add("spring-boot-starter"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addImports("javax.annotation.PostConstruct", - "javax.annotation.PreDestroy", "groovy.util.logging.Log", - "org.springframework.stereotype.Controller", - "org.springframework.stereotype.Service", - "org.springframework.stereotype.Component", - "org.springframework.beans.factory.annotation.Autowired", - "org.springframework.beans.factory.annotation.Value", - "org.springframework.context.annotation.Import", + imports.addImports("javax.annotation.PostConstruct", "javax.annotation.PreDestroy", "groovy.util.logging.Log", + "org.springframework.stereotype.Controller", "org.springframework.stereotype.Service", + "org.springframework.stereotype.Component", "org.springframework.beans.factory.annotation.Autowired", + "org.springframework.beans.factory.annotation.Value", "org.springframework.context.annotation.Import", "org.springframework.context.annotation.ImportResource", - "org.springframework.context.annotation.Profile", - "org.springframework.context.annotation.Scope", + "org.springframework.context.annotation.Profile", "org.springframework.context.annotation.Scope", "org.springframework.context.annotation.Configuration", - "org.springframework.context.annotation.ComponentScan", - "org.springframework.context.annotation.Bean", - "org.springframework.context.ApplicationContext", - "org.springframework.context.MessageSource", - "org.springframework.core.annotation.Order", - "org.springframework.core.io.ResourceLoader", - "org.springframework.boot.ApplicationRunner", - "org.springframework.boot.ApplicationArguments", + "org.springframework.context.annotation.ComponentScan", "org.springframework.context.annotation.Bean", + "org.springframework.context.ApplicationContext", "org.springframework.context.MessageSource", + "org.springframework.core.annotation.Order", "org.springframework.core.io.ResourceLoader", + "org.springframework.boot.ApplicationRunner", "org.springframework.boot.ApplicationArguments", "org.springframework.boot.CommandLineRunner", "org.springframework.boot.context.properties.ConfigurationProperties", "org.springframework.boot.context.properties.EnableConfigurationProperties", @@ -72,21 +62,19 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati "org.springframework.boot.autoconfigure.SpringBootApplication", "org.springframework.boot.context.properties.ConfigurationProperties", "org.springframework.boot.context.properties.EnableConfigurationProperties"); - imports.addStarImports("org.springframework.stereotype", - "org.springframework.scheduling.annotation"); + imports.addStarImports("org.springframework.stereotype", "org.springframework.scheduling.annotation"); } @Override - public void applyToMainClass(GroovyClassLoader loader, - GroovyCompilerConfiguration configuration, GeneratorContext generatorContext, - SourceUnit source, ClassNode classNode) throws CompilationFailedException { + public void applyToMainClass(GroovyClassLoader loader, GroovyCompilerConfiguration configuration, + GeneratorContext generatorContext, SourceUnit source, ClassNode classNode) + throws CompilationFailedException { addEnableAutoConfigurationAnnotation(classNode); } private void addEnableAutoConfigurationAnnotation(ClassNode classNode) { if (!hasEnableAutoConfigureAnnotation(classNode)) { - AnnotationNode annotationNode = new AnnotationNode( - ClassHelper.make("EnableAutoConfiguration")); + AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make("EnableAutoConfiguration")); classNode.addAnnotation(annotationNode); } } @@ -94,8 +82,7 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati private boolean hasEnableAutoConfigureAnnotation(ClassNode classNode) { for (AnnotationNode node : classNode.getAnnotations()) { String name = node.getClassNode().getNameWithoutPackage(); - if ("EnableAutoConfiguration".equals(name) - || "SpringBootApplication".equals(name)) { + if ("EnableAutoConfiguration".equals(name) || "SpringBootApplication".equals(name)) { return true; } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java index cb723cb6e90..e6da4974930 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Dave Syer * @author Artem Bilan */ -public class SpringIntegrationCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class SpringIntegrationCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -40,18 +39,14 @@ public class SpringIntegrationCompilerAutoConfiguration @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies - .ifAnyMissingClasses( - "org.springframework.integration.config.EnableIntegration") + dependencies.ifAnyMissingClasses("org.springframework.integration.config.EnableIntegration") .add("spring-boot-starter-integration"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addImports("org.springframework.messaging.Message", - "org.springframework.messaging.MessageChannel", - "org.springframework.messaging.PollableChannel", - "org.springframework.messaging.SubscribableChannel", + imports.addImports("org.springframework.messaging.Message", "org.springframework.messaging.MessageChannel", + "org.springframework.messaging.PollableChannel", "org.springframework.messaging.SubscribableChannel", "org.springframework.messaging.MessageHeaders", "org.springframework.integration.support.MessageBuilder", "org.springframework.integration.channel.DirectChannel", diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java index 465c9559016..1b443d4e7d6 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,24 +34,21 @@ public class SpringMvcCompilerAutoConfiguration extends CompilerAutoConfiguratio @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "Controller", "RestController", - "EnableWebMvc"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "Controller", "RestController", "EnableWebMvc"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { dependencies.ifAnyMissingClasses("org.springframework.web.servlet.mvc.Controller") .add("spring-boot-starter-web"); - dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine") - .add("groovy-templates"); + dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates"); } @Override public void applyImports(ImportCustomizer imports) { imports.addStarImports("org.springframework.web.bind.annotation", - "org.springframework.web.servlet.config.annotation", - "org.springframework.web.servlet", "org.springframework.http", - "org.springframework.web.servlet.handler", "org.springframework.http", + "org.springframework.web.servlet.config.annotation", "org.springframework.web.servlet", + "org.springframework.http", "org.springframework.web.servlet.handler", "org.springframework.http", "org.springframework.ui", "groovy.text"); imports.addStaticImport(GroovyTemplate.class.getName(), "template"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java index 9ab3b1e248d..6148bd0991f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,15 +33,13 @@ public class SpringRetryCompilerAutoConfiguration extends CompilerAutoConfigurat @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableRetry", "Retryable", - "Recover"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableRetry", "Retryable", "Recover"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies - .ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry") - .add("spring-retry", "spring-boot-starter-aop"); + dependencies.ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry").add("spring-retry", + "spring-boot-starter-aop"); } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java index 048319ae591..2f6d3a86158 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSecurity", - "EnableGlobalMethodSecurity"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSecurity", "EnableGlobalMethodSecurity"); } @Override @@ -48,8 +47,7 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu imports.addImports("org.springframework.security.core.Authentication", "org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity", "org.springframework.security.core.authority.AuthorityUtils") - .addStarImports( - "org.springframework.security.config.annotation.web.configuration", + .addStarImports("org.springframework.security.config.annotation.web.configuration", "org.springframework.security.authentication", "org.springframework.security.config.annotation.web", "org.springframework.security.config.annotation.web.builders"); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java index 028e963c5eb..891721bbacc 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.http.HttpHeaders") - .add("spring-boot-starter-web"); + dependencies.ifAnyMissingClasses("org.springframework.http.HttpHeaders").add("spring-boot-starter-web"); } @Override @@ -56,8 +55,7 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati throws CompilationFailedException { if (!AstUtils.hasAtLeastOneAnnotation(classNode, "RunWith")) { AnnotationNode runWith = new AnnotationNode(ClassHelper.make("RunWith")); - runWith.addMember("value", - new ClassExpression(ClassHelper.make("SpringRunner"))); + runWith.addMember("value", new ClassExpression(ClassHelper.make("SpringRunner"))); classNode.addAnnotation(runWith); } } @@ -65,11 +63,10 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { imports.addStarImports("org.junit.runner", "org.springframework.boot.test", - "org.springframework.boot.test.context", - "org.springframework.boot.test.web.client", "org.springframework.http", - "org.springframework.test.context.junit4", - "org.springframework.test.annotation").addImports( - "org.springframework.boot.test.context.SpringBootTest.WebEnvironment", + "org.springframework.boot.test.context", "org.springframework.boot.test.web.client", + "org.springframework.http", "org.springframework.test.context.junit4", + "org.springframework.test.annotation") + .addImports("org.springframework.boot.test.context.SpringBootTest.WebEnvironment", "org.springframework.boot.test.web.client.TestRestTemplate"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java index 8d1007f7f51..d7b939ab506 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,22 +32,19 @@ public class SpringWebsocketCompilerAutoConfiguration extends CompilerAutoConfig @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSocket", - "EnableWebSocketMessageBroker"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSocket", "EnableWebSocketMessageBroker"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses( - "org.springframework.web.socket.config.annotation.EnableWebSocket") + dependencies.ifAnyMissingClasses("org.springframework.web.socket.config.annotation.EnableWebSocket") .add("spring-boot-starter-websocket").add("spring-messaging"); } @Override public void applyImports(ImportCustomizer imports) { imports.addStarImports("org.springframework.messaging.handler.annotation", - "org.springframework.messaging.simp.config", - "org.springframework.web.socket.handler", + "org.springframework.messaging.simp.config", "org.springframework.web.socket.handler", "org.springframework.web.socket.sockjs.transport.handler", "org.springframework.web.socket.config.annotation") .addImports("org.springframework.web.socket.WebSocketHandler"); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java index 1d8539e451f..64d6dd615b1 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Dave Syer * @author Phillip Webb */ -public class TransactionManagementCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class TransactionManagementCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -39,16 +38,13 @@ public class TransactionManagementCompilerAutoConfiguration @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies - .ifAnyMissingClasses( - "org.springframework.transaction.annotation.Transactional") - .add("spring-tx", "spring-boot-starter-aop"); + dependencies.ifAnyMissingClasses("org.springframework.transaction.annotation.Transactional").add("spring-tx", + "spring-boot-starter-aop"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addStarImports("org.springframework.transaction.annotation", - "org.springframework.transaction.support"); + imports.addStarImports("org.springframework.transaction.annotation", "org.springframework.transaction.support"); imports.addImports("org.springframework.transaction.PlatformTransactionManager", "org.springframework.transaction.support.AbstractPlatformTransactionManager"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java index 1ec208d396d..05fbabcf373 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java @@ -54,8 +54,7 @@ public final class Dependency { * @param version the version * @param exclusions the exclusions */ - public Dependency(String groupId, String artifactId, String version, - List exclusions) { + public Dependency(String groupId, String artifactId, String version, List exclusions) { Assert.notNull(groupId, "GroupId must not be null"); Assert.notNull(artifactId, "ArtifactId must not be null"); Assert.notNull(version, "Version must not be null"); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java index f7beeaedf44..0fd5dd0e852 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @author Andy Wilkinson */ -public class DependencyManagementArtifactCoordinatesResolver - implements ArtifactCoordinatesResolver { +public class DependencyManagementArtifactCoordinatesResolver implements ArtifactCoordinatesResolver { private final DependencyManagement dependencyManagement; @@ -34,8 +33,7 @@ public class DependencyManagementArtifactCoordinatesResolver this(new SpringBootDependenciesDependencyManagement()); } - public DependencyManagementArtifactCoordinatesResolver( - DependencyManagement dependencyManagement) { + public DependencyManagementArtifactCoordinatesResolver(DependencyManagement dependencyManagement) { this.dependencyManagement = dependencyManagement; } @@ -58,8 +56,7 @@ public class DependencyManagementArtifactCoordinatesResolver } if (id != null) { if (id.startsWith("spring-boot")) { - return new Dependency("org.springframework.boot", id, - this.dependencyManagement.getSpringBootVersion()); + return new Dependency("org.springframework.boot", id, this.dependencyManagement.getSpringBootVersion()); } return this.dependencyManagement.find(id); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java index 803c0d425e2..01d8274712f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,17 +46,13 @@ public class MavenModelDependencyManagement implements DependencyManagement { private static List extractDependenciesFromModel(Model model) { List dependencies = new ArrayList<>(); - for (org.apache.maven.model.Dependency mavenDependency : model - .getDependencyManagement().getDependencies()) { + for (org.apache.maven.model.Dependency mavenDependency : model.getDependencyManagement().getDependencies()) { List exclusions = new ArrayList<>(); - for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency - .getExclusions()) { - exclusions.add(new Exclusion(mavenExclusion.getGroupId(), - mavenExclusion.getArtifactId())); + for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency.getExclusions()) { + exclusions.add(new Exclusion(mavenExclusion.getGroupId(), mavenExclusion.getArtifactId())); } - Dependency dependency = new Dependency(mavenDependency.getGroupId(), - mavenDependency.getArtifactId(), mavenDependency.getVersion(), - exclusions); + Dependency dependency = new Dependency(mavenDependency.getGroupId(), mavenDependency.getArtifactId(), + mavenDependency.getVersion(), exclusions); dependencies.add(dependency); } return dependencies; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java index 17f4b994378..694c2785428 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.apache.maven.model.locator.DefaultModelLocator; * @author Andy Wilkinson * @since 1.3.0 */ -public class SpringBootDependenciesDependencyManagement - extends MavenModelDependencyManagement { +public class SpringBootDependenciesDependencyManagement extends MavenModelDependencyManagement { public SpringBootDependenciesDependencyManagement() { super(readModel()); @@ -43,12 +42,11 @@ public class SpringBootDependenciesDependencyManagement modelProcessor.setModelReader(new DefaultModelReader()); try { - return modelProcessor.read(SpringBootDependenciesDependencyManagement.class - .getResourceAsStream("effective-pom.xml"), null); + return modelProcessor.read( + SpringBootDependenciesDependencyManagement.class.getResourceAsStream("effective-pom.xml"), null); } catch (IOException ex) { - throw new IllegalStateException("Failed to build model from effective pom", - ex); + throw new IllegalStateException("Failed to build model from effective pom", ex); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java index 13d1fcafc1c..f0f2b100c36 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,10 +73,8 @@ public class AetherGrapeEngine implements GrapeEngine { private final List repositories; - public AetherGrapeEngine(GroovyClassLoader classLoader, - RepositorySystem repositorySystem, - DefaultRepositorySystemSession repositorySystemSession, - List remoteRepositories, + public AetherGrapeEngine(GroovyClassLoader classLoader, RepositorySystem repositorySystem, + DefaultRepositorySystemSession repositorySystemSession, List remoteRepositories, DependencyResolutionContext resolutionContext, boolean quiet) { this.classLoader = classLoader; this.repositorySystem = repositorySystem; @@ -91,12 +89,10 @@ public class AetherGrapeEngine implements GrapeEngine { this.progressReporter = getProgressReporter(this.session, quiet); } - private ProgressReporter getProgressReporter(DefaultRepositorySystemSession session, - boolean quiet) { - String progressReporter = (quiet ? "none" : System.getProperty( - "org.springframework.boot.cli.compiler.grape.ProgressReporter")); - if ("detail".equals(progressReporter) - || Boolean.getBoolean("groovy.grape.report.downloads")) { + private ProgressReporter getProgressReporter(DefaultRepositorySystemSession session, boolean quiet) { + String progressReporter = (quiet ? "none" + : System.getProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter")); + if ("detail".equals(progressReporter) || Boolean.getBoolean("groovy.grape.report.downloads")) { return new DetailedProgressReporter(session, System.out); } if ("none".equals(progressReporter)) { @@ -132,8 +128,7 @@ public class AetherGrapeEngine implements GrapeEngine { private List createExclusions(Map args) { List exclusions = new ArrayList<>(); if (args != null) { - List> exclusionMaps = (List>) args - .get("excludes"); + List> exclusionMaps = (List>) args.get("excludes"); if (exclusionMaps != null) { for (Map exclusionMap : exclusionMaps) { exclusions.add(createExclusion(exclusionMap)); @@ -149,8 +144,7 @@ public class AetherGrapeEngine implements GrapeEngine { return new Exclusion(group, module, "*", "*"); } - private List createDependencies(Map[] dependencyMaps, - List exclusions) { + private List createDependencies(Map[] dependencyMaps, List exclusions) { List dependencies = new ArrayList<>(dependencyMaps.length); for (Map dependencyMap : dependencyMaps) { dependencies.add(createDependency(dependencyMap, exclusions)); @@ -158,8 +152,7 @@ public class AetherGrapeEngine implements GrapeEngine { return dependencies; } - private Dependency createDependency(Map dependencyMap, - List exclusions) { + private Dependency createDependency(Map dependencyMap, List exclusions) { Artifact artifact = createArtifact(dependencyMap); if (isTransitive(dependencyMap)) { return new Dependency(artifact, JavaScopes.COMPILE, false, exclusions); @@ -189,8 +182,7 @@ public class AetherGrapeEngine implements GrapeEngine { } } else if (ext != null && !type.equals(ext)) { - throw new IllegalArgumentException( - "If both type and ext are specified they must have the same value"); + throw new IllegalArgumentException("If both type and ext are specified they must have the same value"); } return type; } @@ -203,8 +195,7 @@ public class AetherGrapeEngine implements GrapeEngine { private List getDependencies(DependencyResult dependencyResult) { List dependencies = new ArrayList<>(); for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) { - dependencies.add( - new Dependency(artifactResult.getArtifact(), JavaScopes.COMPILE)); + dependencies.add(new Dependency(artifactResult.getArtifact(), JavaScopes.COMPILE)); } return dependencies; } @@ -226,8 +217,7 @@ public class AetherGrapeEngine implements GrapeEngine { public void addResolver(Map args) { String name = (String) args.get("name"); String root = (String) args.get("root"); - RemoteRepository.Builder builder = new RemoteRepository.Builder(name, "default", - root); + RemoteRepository.Builder builder = new RemoteRepository.Builder(name, "default", root); RemoteRepository repository = builder.build(); addRepository(repository); } @@ -243,8 +233,7 @@ public class AetherGrapeEngine implements GrapeEngine { } private RemoteRepository getPossibleMirror(RemoteRepository remoteRepository) { - RemoteRepository mirror = this.session.getMirrorSelector() - .getMirror(remoteRepository); + RemoteRepository mirror = this.session.getMirrorSelector().getMirror(remoteRepository); if (mirror != null) { return mirror; } @@ -263,8 +252,7 @@ public class AetherGrapeEngine implements GrapeEngine { private RemoteRepository applyAuthentication(RemoteRepository repository) { if (repository.getAuthentication() == null) { RemoteRepository.Builder builder = new RemoteRepository.Builder(repository); - builder.setAuthentication(this.session.getAuthenticationSelector() - .getAuthentication(repository)); + builder.setAuthentication(this.session.getAuthenticationSelector().getAuthentication(repository)); repository = builder.build(); } return repository; @@ -297,13 +285,11 @@ public class AetherGrapeEngine implements GrapeEngine { } } - private List resolve(List dependencies) - throws ArtifactResolutionException { + private List resolve(List dependencies) throws ArtifactResolutionException { try { CollectRequest collectRequest = getCollectRequest(dependencies); DependencyRequest dependencyRequest = getDependencyRequest(collectRequest); - DependencyResult result = this.repositorySystem - .resolveDependencies(this.session, dependencyRequest); + DependencyResult result = this.repositorySystem.resolveDependencies(this.session, dependencyRequest); addManagedDependencies(result); return getFiles(result); } @@ -316,16 +302,15 @@ public class AetherGrapeEngine implements GrapeEngine { } private CollectRequest getCollectRequest(List dependencies) { - CollectRequest collectRequest = new CollectRequest((Dependency) null, - dependencies, new ArrayList<>(this.repositories)); - collectRequest - .setManagedDependencies(this.resolutionContext.getManagedDependencies()); + CollectRequest collectRequest = new CollectRequest((Dependency) null, dependencies, + new ArrayList<>(this.repositories)); + collectRequest.setManagedDependencies(this.resolutionContext.getManagedDependencies()); return collectRequest; } private DependencyRequest getDependencyRequest(CollectRequest collectRequest) { - return new DependencyRequest(collectRequest, DependencyFilterUtils - .classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME)); + return new DependencyRequest(collectRequest, + DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME)); } private void addManagedDependencies(DependencyResult result) { @@ -339,8 +324,7 @@ public class AetherGrapeEngine implements GrapeEngine { @Override public Object grab(String endorsedModule) { - throw new UnsupportedOperationException( - "Grabbing an endorsed module is not supported"); + throw new UnsupportedOperationException("Grabbing an endorsed module is not supported"); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java index 36db33d0dc3..60b58f74033 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,44 +45,35 @@ public abstract class AetherGrapeEngineFactory { public static AetherGrapeEngine create(GroovyClassLoader classLoader, List repositoryConfigurations, DependencyResolutionContext dependencyResolutionContext, boolean quiet) { - RepositorySystem repositorySystem = createServiceLocator() - .getService(RepositorySystem.class); - DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils - .newSession(); + RepositorySystem repositorySystem = createServiceLocator().getService(RepositorySystem.class); + DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils.newSession(); ServiceLoader autoConfigurations = ServiceLoader .load(RepositorySystemSessionAutoConfiguration.class); for (RepositorySystemSessionAutoConfiguration autoConfiguration : autoConfigurations) { autoConfiguration.apply(repositorySystemSession, repositorySystem); } - new DefaultRepositorySystemSessionAutoConfiguration() - .apply(repositorySystemSession, repositorySystem); - return new AetherGrapeEngine(classLoader, repositorySystem, - repositorySystemSession, createRepositories(repositoryConfigurations), - dependencyResolutionContext, quiet); + new DefaultRepositorySystemSessionAutoConfiguration().apply(repositorySystemSession, repositorySystem); + return new AetherGrapeEngine(classLoader, repositorySystem, repositorySystemSession, + createRepositories(repositoryConfigurations), dependencyResolutionContext, quiet); } private static ServiceLocator createServiceLocator() { DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.addService(RepositorySystem.class, DefaultRepositorySystem.class); - locator.addService(RepositoryConnectorFactory.class, - BasicRepositoryConnectorFactory.class); + locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, HttpTransporterFactory.class); locator.addService(TransporterFactory.class, FileTransporterFactory.class); return locator; } - private static List createRepositories( - List repositoryConfigurations) { - List repositories = new ArrayList<>( - repositoryConfigurations.size()); + private static List createRepositories(List repositoryConfigurations) { + List repositories = new ArrayList<>(repositoryConfigurations.size()); for (RepositoryConfiguration repositoryConfiguration : repositoryConfigurations) { - RemoteRepository.Builder builder = new RemoteRepository.Builder( - repositoryConfiguration.getName(), "default", - repositoryConfiguration.getUri().toASCIIString()); + RemoteRepository.Builder builder = new RemoteRepository.Builder(repositoryConfiguration.getName(), + "default", repositoryConfiguration.getUri().toASCIIString()); if (!repositoryConfiguration.getSnapshotsEnabled()) { - builder.setSnapshotPolicy( - new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER, - RepositoryPolicy.CHECKSUM_POLICY_IGNORE)); + builder.setSnapshotPolicy(new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER, + RepositoryPolicy.CHECKSUM_POLICY_IGNORE)); } repositories.add(builder.build()); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java index c851e0cf621..c63c4155b5a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,25 +34,22 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -public class DefaultRepositorySystemSessionAutoConfiguration - implements RepositorySystemSessionAutoConfiguration { +public class DefaultRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration { @Override - public void apply(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem) { + public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) { if (session.getLocalRepositoryManager() == null) { LocalRepository localRepository = new LocalRepository(getM2RepoDirectory()); - LocalRepositoryManager localRepositoryManager = repositorySystem - .newLocalRepositoryManager(session, localRepository); + LocalRepositoryManager localRepositoryManager = repositorySystem.newLocalRepositoryManager(session, + localRepository); session.setLocalRepositoryManager(localRepositoryManager); } ProxySelector existing = session.getProxySelector(); if (existing == null || !(existing instanceof CompositeProxySelector)) { JreProxySelector fallback = new JreProxySelector(); - ProxySelector selector = (existing != null) - ? new CompositeProxySelector(Arrays.asList(existing, fallback)) + ProxySelector selector = (existing != null) ? new CompositeProxySelector(Arrays.asList(existing, fallback)) : fallback; session.setProxySelector(selector); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java index 943cd20f5ec..d0f0a8e08e9 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class DependencyResolutionContext { private ArtifactCoordinatesResolver artifactCoordinatesResolver; private String getIdentifier(Dependency dependency) { - return getIdentifier(dependency.getArtifact().getGroupId(), - dependency.getArtifact().getArtifactId()); + return getIdentifier(dependency.getArtifact().getGroupId(), dependency.getArtifact().getArtifactId()); } private String getIdentifier(String groupId, String artifactId) { @@ -64,8 +63,7 @@ public class DependencyResolutionContext { public String getManagedVersion(String groupId, String artifactId) { Dependency dependency = getManagedDependency(groupId, artifactId); if (dependency == null) { - dependency = this.managedDependencyByGroupAndArtifact - .get(getIdentifier(groupId, artifactId)); + dependency = this.managedDependencyByGroupAndArtifact.get(getIdentifier(groupId, artifactId)); } return (dependency != null) ? dependency.getArtifact().getVersion() : null; } @@ -75,15 +73,13 @@ public class DependencyResolutionContext { } private Dependency getManagedDependency(String group, String artifact) { - return this.managedDependencyByGroupAndArtifact - .get(getIdentifier(group, artifact)); + return this.managedDependencyByGroupAndArtifact.get(getIdentifier(group, artifact)); } public void addManagedDependencies(List dependencies) { this.managedDependencies.addAll(dependencies); for (Dependency dependency : dependencies) { - this.managedDependencyByGroupAndArtifact.put(getIdentifier(dependency), - dependency); + this.managedDependencyByGroupAndArtifact.put(getIdentifier(dependency), dependency); } } @@ -93,20 +89,16 @@ public class DependencyResolutionContext { List aetherExclusions = new ArrayList<>(); for (org.springframework.boot.cli.compiler.dependencies.Dependency.Exclusion exclusion : dependency .getExclusions()) { - aetherExclusions.add(new Exclusion(exclusion.getGroupId(), - exclusion.getArtifactId(), "*", "*")); + aetherExclusions.add(new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*")); } - Dependency aetherDependency = new Dependency( - new DefaultArtifact(dependency.getGroupId(), - dependency.getArtifactId(), "jar", dependency.getVersion()), - JavaScopes.COMPILE, false, aetherExclusions); + Dependency aetherDependency = new Dependency(new DefaultArtifact(dependency.getGroupId(), + dependency.getArtifactId(), "jar", dependency.getVersion()), JavaScopes.COMPILE, false, + aetherExclusions); this.managedDependencies.add(0, aetherDependency); - this.managedDependencyByGroupAndArtifact.put(getIdentifier(aetherDependency), - aetherDependency); + this.managedDependencyByGroupAndArtifact.put(getIdentifier(aetherDependency), aetherDependency); } this.dependencyManagement = (this.dependencyManagement != null) - ? new CompositeDependencyManagement(dependencyManagement, - this.dependencyManagement) + ? new CompositeDependencyManagement(dependencyManagement, this.dependencyManagement) : dependencyManagement; this.artifactCoordinatesResolver = new DependencyManagementArtifactCoordinatesResolver( this.dependencyManagement); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java index a7e80ef7f5d..611ee03378e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,21 +31,18 @@ import org.eclipse.aether.transfer.TransferResource; */ final class DetailedProgressReporter implements ProgressReporter { - DetailedProgressReporter(DefaultRepositorySystemSession session, - final PrintStream out) { + DetailedProgressReporter(DefaultRepositorySystemSession session, final PrintStream out) { session.setTransferListener(new AbstractTransferListener() { @Override - public void transferStarted(TransferEvent event) - throws TransferCancelledException { + public void transferStarted(TransferEvent event) throws TransferCancelledException { out.println("Downloading: " + getResourceIdentifier(event.getResource())); } @Override public void transferSucceeded(TransferEvent event) { - out.printf("Downloaded: %s (%s)%n", - getResourceIdentifier(event.getResource()), + out.printf("Downloaded: %s (%s)%n", getResourceIdentifier(event.getResource()), getTransferSpeed(event)); } }); @@ -57,8 +54,7 @@ final class DetailedProgressReporter implements ProgressReporter { private String getTransferSpeed(TransferEvent event) { long kb = event.getTransferredBytes() / 1024; - float seconds = (System.currentTimeMillis() - - event.getResource().getTransferStartTime()) / 1000.0f; + float seconds = (System.currentTimeMillis() - event.getResource().getTransferStartTime()) / 1000.0f; return String.format("%dKB at %.1fKB/sec", kb, (kb / seconds)); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java index ceafa0613b2..9e19c335e14 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,24 +32,22 @@ import org.springframework.util.StringUtils; * @author Andy Wilkinson * @since 1.2.5 */ -public class GrapeRootRepositorySystemSessionAutoConfiguration - implements RepositorySystemSessionAutoConfiguration { +public class GrapeRootRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration { @Override - public void apply(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem) { + public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) { String grapeRoot = System.getProperty("grape.root"); if (StringUtils.hasLength(grapeRoot)) { configureLocalRepository(session, repositorySystem, grapeRoot); } } - private void configureLocalRepository(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem, String grapeRoot) { + private void configureLocalRepository(DefaultRepositorySystemSession session, RepositorySystem repositorySystem, + String grapeRoot) { File repositoryDir = new File(grapeRoot, "repository"); LocalRepository localRepository = new LocalRepository(repositoryDir); - LocalRepositoryManager localRepositoryManager = repositorySystem - .newLocalRepositoryManager(session, localRepository); + LocalRepositoryManager localRepositoryManager = repositorySystem.newLocalRepositoryManager(session, + localRepository); session.setLocalRepositoryManager(localRepositoryManager); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java index 3bfbf208500..7b6f751f281 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,8 +92,8 @@ public final class RepositoryConfiguration { @Override public String toString() { - return "RepositoryConfiguration [name=" + this.name + ", uri=" + this.uri - + ", snapshotsEnabled=" + this.snapshotsEnabled + "]"; + return "RepositoryConfiguration [name=" + this.name + ", uri=" + this.uri + ", snapshotsEnabled=" + + this.snapshotsEnabled + "]"; } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java index 3ac602831ef..ed893269f40 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,17 +29,15 @@ import org.springframework.boot.cli.compiler.maven.MavenSettingsReader; * * @author Andy Wilkinson */ -public class SettingsXmlRepositorySystemSessionAutoConfiguration - implements RepositorySystemSessionAutoConfiguration { +public class SettingsXmlRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration { @Override - public void apply(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem) { + public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) { MavenSettings settings = getSettings(session); String localRepository = settings.getLocalRepository(); if (localRepository != null) { - session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager( - session, new LocalRepository(localRepository))); + session.setLocalRepositoryManager( + repositorySystem.newLocalRepositoryManager(session, new LocalRepository(localRepository))); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java index b62237422cc..d0c7e9af6ad 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,15 +73,13 @@ final class SummaryProgressReporter implements ProgressReporter { } private void reportProgress() { - if (!this.finished - && System.currentTimeMillis() - this.startTime > INITIAL_DELAY) { + if (!this.finished && System.currentTimeMillis() - this.startTime > INITIAL_DELAY) { if (!this.started) { this.started = true; this.out.print("Resolving dependencies.."); this.lastProgressTime = System.currentTimeMillis(); } - else if (System.currentTimeMillis() - - this.lastProgressTime > PROGRESS_DELAY) { + else if (System.currentTimeMillis() - this.lastProgressTime > PROGRESS_DELAY) { this.out.print("."); this.lastProgressTime = System.currentTimeMillis(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java index 547f3852394..917272960b0 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,14 +93,13 @@ public class MavenSettings { private MirrorSelector createMirrorSelector(Settings settings) { DefaultMirrorSelector selector = new DefaultMirrorSelector(); for (Mirror mirror : settings.getMirrors()) { - selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, - mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); + selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), + mirror.getMirrorOfLayouts()); } return selector; } - private AuthenticationSelector createAuthenticationSelector( - SettingsDecryptionResult decryptedSettings) { + private AuthenticationSelector createAuthenticationSelector(SettingsDecryptionResult decryptedSettings) { DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector(); for (Server server : decryptedSettings.getServers()) { AuthenticationBuilder auth = new AuthenticationBuilder(); @@ -111,28 +110,22 @@ public class MavenSettings { return new ConservativeAuthenticationSelector(selector); } - private ProxySelector createProxySelector( - SettingsDecryptionResult decryptedSettings) { + private ProxySelector createProxySelector(SettingsDecryptionResult decryptedSettings) { DefaultProxySelector selector = new DefaultProxySelector(); for (Proxy proxy : decryptedSettings.getProxies()) { - Authentication authentication = new AuthenticationBuilder() - .addUsername(proxy.getUsername()).addPassword(proxy.getPassword()) - .build(); - selector.add( - new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), - proxy.getHost(), proxy.getPort(), authentication), - proxy.getNonProxyHosts()); + Authentication authentication = new AuthenticationBuilder().addUsername(proxy.getUsername()) + .addPassword(proxy.getPassword()).build(); + selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), + authentication), proxy.getNonProxyHosts()); } return selector; } private List determineActiveProfiles(Settings settings) { SpringBootCliModelProblemCollector problemCollector = new SpringBootCliModelProblemCollector(); - List activeModelProfiles = createProfileSelector() - .getActiveProfiles(createModelProfiles(settings.getProfiles()), - new SpringBootCliProfileActivationContext( - settings.getActiveProfiles()), - problemCollector); + List activeModelProfiles = createProfileSelector().getActiveProfiles( + createModelProfiles(settings.getProfiles()), + new SpringBootCliProfileActivationContext(settings.getActiveProfiles()), problemCollector); if (!problemCollector.getProblems().isEmpty()) { throw new IllegalStateException(createFailureMessage(problemCollector)); } @@ -144,14 +137,12 @@ public class MavenSettings { return activeProfiles; } - private String createFailureMessage( - SpringBootCliModelProblemCollector problemCollector) { + private String createFailureMessage(SpringBootCliModelProblemCollector problemCollector) { StringWriter message = new StringWriter(); PrintWriter printer = new PrintWriter(message); printer.println("Failed to determine active profiles:"); for (ModelProblemCollectorRequest problem : problemCollector.getProblems()) { - String location = (problem.getLocation() != null) - ? " at " + problem.getLocation() : ""; + String location = (problem.getLocation() != null) ? " at " + problem.getLocation() : ""; printer.println(" " + problem.getMessage() + location); if (problem.getException() != null) { printer.println(indentStackTrace(problem.getException(), " ")); @@ -182,31 +173,27 @@ public class MavenSettings { private DefaultProfileSelector createProfileSelector() { DefaultProfileSelector selector = new DefaultProfileSelector(); - selector.addProfileActivator(new FileProfileActivator() - .setPathTranslator(new DefaultPathTranslator())); + selector.addProfileActivator(new FileProfileActivator().setPathTranslator(new DefaultPathTranslator())); selector.addProfileActivator(new JdkVersionProfileActivator()); selector.addProfileActivator(new PropertyProfileActivator()); selector.addProfileActivator(new OperatingSystemProfileActivator()); return selector; } - private List createModelProfiles( - List profiles) { + private List createModelProfiles(List profiles) { List modelProfiles = new ArrayList<>(); for (Profile profile : profiles) { org.apache.maven.model.Profile modelProfile = new org.apache.maven.model.Profile(); modelProfile.setId(profile.getId()); if (profile.getActivation() != null) { - modelProfile - .setActivation(createModelActivation(profile.getActivation())); + modelProfile.setActivation(createModelActivation(profile.getActivation())); } modelProfiles.add(modelProfile); } return modelProfiles; } - private org.apache.maven.model.Activation createModelActivation( - Activation activation) { + private org.apache.maven.model.Activation createModelActivation(Activation activation) { org.apache.maven.model.Activation modelActivation = new org.apache.maven.model.Activation(); modelActivation.setActiveByDefault(activation.isActiveByDefault()); if (activation.getFile() != null) { @@ -257,8 +244,7 @@ public class MavenSettings { return this.activeProfiles; } - private static final class SpringBootCliProfileActivationContext - implements ProfileActivationContext { + private static final class SpringBootCliProfileActivationContext implements ProfileActivationContext { private final List activeProfiles; @@ -299,8 +285,7 @@ public class MavenSettings { } - private static final class SpringBootCliModelProblemCollector - implements ModelProblemCollector { + private static final class SpringBootCliModelProblemCollector implements ModelProblemCollector { private final List problems = new ArrayList<>(); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java index a27df54bef3..10a8e7b02a4 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,7 @@ public class MavenSettingsReader { Settings settings = loadSettings(); SettingsDecryptionResult decrypted = decryptSettings(settings); if (!decrypted.getProblems().isEmpty()) { - Log.error( - "Maven settings decryption failed. Some Maven repositories may be inaccessible"); + Log.error("Maven settings decryption failed. Some Maven repositories may be inaccessible"); // Continue - the encrypted credentials may not be used } return new MavenSettings(settings, decrypted); @@ -70,18 +69,15 @@ public class MavenSettingsReader { request.setUserSettingsFile(settingsFile); request.setSystemProperties(System.getProperties()); try { - return new DefaultSettingsBuilderFactory().newInstance().build(request) - .getEffectiveSettings(); + return new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); } catch (SettingsBuildingException ex) { - throw new IllegalStateException( - "Failed to build settings from " + settingsFile, ex); + throw new IllegalStateException("Failed to build settings from " + settingsFile, ex); } } private SettingsDecryptionResult decryptSettings(Settings settings) { - DefaultSettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest( - settings); + DefaultSettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(settings); return createSettingsDecrypter().decrypt(request); } @@ -93,16 +89,14 @@ public class MavenSettingsReader { return settingsDecrypter; } - private void setField(Class sourceClass, String fieldName, Object target, - Object value) { + private void setField(Class sourceClass, String fieldName, Object target, Object value) { try { Field field = sourceClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(target, value); } catch (Exception ex) { - throw new IllegalStateException( - "Failed to set field '" + fieldName + "' on '" + target + "'", ex); + throw new IllegalStateException("Failed to set field '" + fieldName + "' on '" + target + "'", ex); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java index 47ba6fa3f6c..54ce6bdd8dc 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,13 +74,11 @@ public abstract class ResourceUtils { return getUrlsFromWildcardPath(path, classLoader); } catch (Exception ex) { - throw new IllegalArgumentException( - "Cannot create URL from path [" + path + "]", ex); + throw new IllegalArgumentException("Cannot create URL from path [" + path + "]", ex); } } - private static List getUrlsFromWildcardPath(String path, - ClassLoader classLoader) throws IOException { + private static List getUrlsFromWildcardPath(String path, ClassLoader classLoader) throws IOException { if (path.contains(":")) { return getUrlsFromPrefixedWildcardPath(path, classLoader); } @@ -96,15 +94,14 @@ public abstract class ResourceUtils { return new ArrayList<>(result); } - private static List getUrlsFromPrefixedWildcardPath(String path, - ClassLoader classLoader) throws IOException { - Resource[] resources = new PathMatchingResourcePatternResolver( - new FileSearchResourceLoader(classLoader)).getResources(path); + private static List getUrlsFromPrefixedWildcardPath(String path, ClassLoader classLoader) + throws IOException { + Resource[] resources = new PathMatchingResourcePatternResolver(new FileSearchResourceLoader(classLoader)) + .getResources(path); List result = new ArrayList<>(); for (Resource resource : resources) { if (resource.exists()) { - if (resource.getURI().getScheme().equals("file") - && resource.getFile().isDirectory()) { + if (resource.getURI().getScheme().equals("file") && resource.getFile().isDirectory()) { result.addAll(getChildFiles(resource)); continue; } @@ -115,8 +112,7 @@ public abstract class ResourceUtils { } private static List getChildFiles(Resource resource) throws IOException { - Resource[] children = new PathMatchingResourcePatternResolver() - .getResources(resource.getURL() + "/**"); + Resource[] children = new PathMatchingResourcePatternResolver().getResources(resource.getURL() + "/**"); List childFiles = new ArrayList<>(); for (Resource child : children) { if (!child.getFile().isDirectory()) { @@ -153,9 +149,7 @@ public abstract class ResourceUtils { public Resource getResource(String location) { Assert.notNull(location, "Location must not be null"); if (location.startsWith(CLASSPATH_URL_PREFIX)) { - return new ClassPathResource( - location.substring(CLASSPATH_URL_PREFIX.length()), - getClassLoader()); + return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader()); } else { if (location.startsWith(FILE_URL_PREFIX)) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java index 1e80e7d634b..7fac16c5f21 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ import java.lang.annotation.Target; * @author Andy Wilkinson * @since 1.3.0 */ -@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, - ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE }) +@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, + ElementType.PARAMETER, ElementType.TYPE }) @Retention(RetentionPolicy.SOURCE) @Documented public @interface DependencyManagementBom { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java index e577ad3a3c6..961d65b404a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.codehaus.groovy.control.CompilationFailedException; */ public abstract class GroovyTemplate { - public static String template(String name) - throws IOException, CompilationFailedException, ClassNotFoundException { + public static String template(String name) throws IOException, CompilationFailedException, ClassNotFoundException { return template(name, Collections.emptyMap()); } @@ -46,8 +45,7 @@ public abstract class GroovyTemplate { return template(new GStringTemplateEngine(), name, model); } - public static String template(TemplateEngine engine, String name, - Map model) + public static String template(TemplateEngine engine, String name, Map model) throws IOException, CompilationFailedException, ClassNotFoundException { Writable writable = getTemplate(engine, name).make(model); StringWriter result = new StringWriter(); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java index e51fc9c91be..293c54c9dc1 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ public class ClassLoaderIntegrationTests { @Test public void runWithIsolatedClassLoader() throws Exception { // CLI classes or dependencies should not be exposed to the app - String output = this.cli.run("classloader-test-app.groovy", - SpringCli.class.getName()); + String output = this.cli.run("classloader-test-app.groovy", SpringCli.class.getName()); assertThat(output).contains("HasClasses-false-true-false"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java index 9a84f5a4663..47b31a2de0f 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java @@ -85,18 +85,15 @@ public class CliTester implements TestRule { boolean classpathUpdated = false; for (String arg : args) { if (arg.startsWith("--classpath=")) { - arg = arg + ":" - + this.buildOutput.getTestClassesLocation().getAbsolutePath(); + arg = arg + ":" + this.buildOutput.getTestClassesLocation().getAbsolutePath(); classpathUpdated = true; } updatedArgs.add(arg); } if (!classpathUpdated) { - updatedArgs.add("--classpath=.:" - + this.buildOutput.getTestClassesLocation().getAbsolutePath()); + updatedArgs.add("--classpath=.:" + this.buildOutput.getTestClassesLocation().getAbsolutePath()); } - Future future = submitCommand(new RunCommand(), - StringUtils.toStringArray(updatedArgs)); + Future future = submitCommand(new RunCommand(), StringUtils.toStringArray(updatedArgs)); this.commands.add(future.get(this.timeout, TimeUnit.MILLISECONDS)); return getOutput(); } @@ -113,8 +110,7 @@ public class CliTester implements TestRule { return getOutput(); } - private Future submitCommand(T command, - String... args) { + private Future submitCommand(T command, String... args) { clearUrlHandler(); final String[] sources = getSources(args); return Executors.newSingleThreadExecutor().submit(() -> { @@ -172,25 +168,21 @@ public class CliTester implements TestRule { } private String getOutput() { - String output = this.outputCapture.toString() - .substring(this.previousOutput.length()); + String output = this.outputCapture.toString().substring(this.previousOutput.length()); this.previousOutput = output; return output; } @Override public Statement apply(Statement base, Description description) { - final Statement statement = this.temp.apply( - this.outputCapture.apply(new RunLauncherStatement(base), description), - description); + final Statement statement = this.temp + .apply(this.outputCapture.apply(new RunLauncherStatement(base), description), description); return new Statement() { @Override public void evaluate() throws Throwable { - Assume.assumeTrue( - "Not running sample integration tests because integration profile not active", - System.getProperty("spring.profiles.active", "integration") - .contains("integration")); + Assume.assumeTrue("Not running sample integration tests because integration profile not active", + System.getProperty("spring.profiles.active", "integration").contains("integration")); statement.evaluate(); } @@ -203,10 +195,8 @@ public class CliTester implements TestRule { public String getHttpOutput(String uri) { try { - int port = Integer.parseInt( - FileCopyUtils.copyToString(new FileReader(this.serverPortFile))); - InputStream stream = URI.create("http://localhost:" + port + uri).toURL() - .openStream(); + int port = Integer.parseInt(FileCopyUtils.copyToString(new FileReader(this.serverPortFile))); + InputStream stream = URI.create("http://localhost:" + port + uri).toURL().openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); return reader.lines().collect(Collectors.joining()); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java index aeccb5953a8..8035902e6bc 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java @@ -59,8 +59,7 @@ public class GrabCommandIntegrationTests { // Use --autoconfigure=false to limit the amount of downloaded dependencies String output = this.cli.grab("grab.groovy", "--autoconfigure=false"); - assertThat(new File(this.temp.getRoot(), "repository/joda-time/joda-time")) - .isDirectory(); + assertThat(new File(this.temp.getRoot(), "repository/joda-time/joda-time")).isDirectory(); // Should be resolved from local repository cache assertThat(output.contains("Downloading: file:")).isTrue(); } @@ -68,8 +67,7 @@ public class GrabCommandIntegrationTests { @Test public void duplicateDependencyManagementBomAnnotationsProducesAnError() { assertThatExceptionOfType(Exception.class) - .isThrownBy( - () -> this.cli.grab("duplicateDependencyManagementBom.groovy")) + .isThrownBy(() -> this.cli.grab("duplicateDependencyManagementBom.groovy")) .withMessageContaining("Duplicate @DependencyManagementBom annotation"); } @@ -77,8 +75,7 @@ public class GrabCommandIntegrationTests { public void customMetadata() throws Exception { System.setProperty("grape.root", this.temp.getRoot().getAbsolutePath()); File repository = new File(this.temp.getRoot().getAbsolutePath(), "repository"); - FileSystemUtils.copyRecursively( - new File("src/test/resources/grab-samples/repository"), repository); + FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"), repository); this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false"); assertThat(new File(repository, "javax/ejb/ejb-api/3.0")).isDirectory(); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java index e7882603ef0..b1b765fb6a4 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,8 +129,7 @@ public class SampleIntegrationTests { System.setProperty("spring.artemis.embedded.queues", "spring-boot"); try { String output = this.cli.run("jms.groovy"); - assertThat(output) - .contains("Received Greetings from Spring Boot via Artemis"); + assertThat(output).contains("Received Greetings from Spring Boot via Artemis"); } finally { System.clearProperty("spring.artemis.embedded.queues"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java index c827dad657d..c963f644c75 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,32 +47,27 @@ public class SpringApplicationLauncherTests { @Test public void launchWithClassConfiguredBySystemProperty() { - System.setProperty("spring.application.class.name", - "system.property.SpringApplication"); + System.setProperty("spring.application.class.name", "system.property.SpringApplication"); assertThat(launch()).contains("system.property.SpringApplication"); } @Test public void launchWithClassConfiguredByEnvironmentVariable() { - this.env.put("SPRING_APPLICATION_CLASS_NAME", - "environment.variable.SpringApplication"); + this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); assertThat(launch()).contains("environment.variable.SpringApplication"); } @Test public void systemPropertyOverridesEnvironmentVariable() { - System.setProperty("spring.application.class.name", - "system.property.SpringApplication"); - this.env.put("SPRING_APPLICATION_CLASS_NAME", - "environment.variable.SpringApplication"); + System.setProperty("spring.application.class.name", "system.property.SpringApplication"); + this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); assertThat(launch()).contains("system.property.SpringApplication"); } @Test public void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception { - System.setProperty("spring.application.class.name", - TestSpringApplication.class.getName()); + System.setProperty("spring.application.class.name", TestSpringApplication.class.getName()); Class[] sources = new Class[0]; String[] args = new String[0]; new SpringApplicationLauncher(getClass().getClassLoader()).launch(sources, args); @@ -81,15 +76,14 @@ public class SpringApplicationLauncherTests { assertThat(args == TestSpringApplication.args).isTrue(); Map defaultProperties = TestSpringApplication.defaultProperties; - assertThat(defaultProperties).hasSize(1) - .containsEntry("spring.groovy.template.check-template-location", "false"); + assertThat(defaultProperties).hasSize(1).containsEntry("spring.groovy.template.check-template-location", + "false"); } private Set launch() { TestClassLoader classLoader = new TestClassLoader(getClass().getClassLoader()); try { - new TestSpringApplicationLauncher(classLoader).launch(new Class[0], - new String[0]); + new TestSpringApplicationLauncher(classLoader).launch(new Class[0], new String[0]); } catch (Exception ex) { // Launch will fail, but we can still check that the launcher tried to use @@ -107,8 +101,7 @@ public class SpringApplicationLauncherTests { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { this.classes.add(name); return super.loadClass(name, resolve); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java index 0f44718e062..b3ea82bcc00 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,8 +94,7 @@ public class CommandRunnerTests { @Test public void runWithoutArguments() throws Exception { - assertThatExceptionOfType(NoArgumentsException.class) - .isThrownBy(this.commandRunner::run); + assertThatExceptionOfType(NoArgumentsException.class).isThrownBy(this.commandRunner::run); } @Test @@ -106,8 +105,7 @@ public class CommandRunnerTests { @Test public void missingCommand() throws Exception { - assertThatExceptionOfType(NoSuchCommandException.class) - .isThrownBy(() -> this.commandRunner.run("missing")); + assertThatExceptionOfType(NoSuchCommandException.class).isThrownBy(() -> this.commandRunner.run("missing")); } @Test diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java index 183d3d3bfcb..84227a65b42 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class OptionParsingCommandTests { public void optionHelp() { OptionHandler handler = new OptionHandler(); handler.option("bar", "Bar"); - OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", - handler); + OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", handler); assertThat(command.getHelp()).contains("--bar"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java index e54d4f4a085..05303d12614 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,33 +40,26 @@ public class ResourceMatcherTests { @Test public void nonExistentRoot() throws IOException { - ResourceMatcher resourceMatcher = new ResourceMatcher( - Arrays.asList("alpha/**", "bravo/*", "*"), + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); - List matchedResources = resourceMatcher - .find(Arrays.asList(new File("does-not-exist"))); + List matchedResources = resourceMatcher.find(Arrays.asList(new File("does-not-exist"))); assertThat(matchedResources).isEmpty(); } @SuppressWarnings("unchecked") @Test public void defaults() { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), - Arrays.asList("")); - Collection includes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "includes"); - Collection excludes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "excludes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("")); + Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); + Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(includes).contains("static/**"); assertThat(excludes).contains("**/*.jar"); } @Test public void excludedWins() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), - Arrays.asList("**/*.jar")); - List found = resourceMatcher - .find(Arrays.asList(new File("src/test/resources"))); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); + List found = resourceMatcher.find(Arrays.asList(new File("src/test/resources"))); assertThat(found).areNot(new Condition() { @Override @@ -80,10 +73,8 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test public void includedDeltas() { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), - Arrays.asList("")); - Collection includes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "includes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), Arrays.asList("")); + Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); assertThat(includes).contains("templates/**"); assertThat(includes).doesNotContain("static/**"); } @@ -91,12 +82,10 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test public void includedDeltasAndNewEntries() { - ResourceMatcher resourceMatcher = new ResourceMatcher( - Arrays.asList("-static/**", "foo.jar"), Arrays.asList("-**/*.jar")); - Collection includes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "includes"); - Collection excludes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "excludes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**", "foo.jar"), + Arrays.asList("-**/*.jar")); + Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); + Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(includes).contains("foo.jar"); assertThat(includes).contains("templates/**"); assertThat(includes).doesNotContain("static/**"); @@ -106,20 +95,16 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test public void excludedDeltas() { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), - Arrays.asList("-**/*.jar")); - Collection excludes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "excludes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar")); + Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(excludes).doesNotContain("**/*.jar"); } @Test public void jarFileAlwaysMatches() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), - Arrays.asList("**/*.jar")); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); List found = resourceMatcher - .find(Arrays.asList(new File("src/test/resources/templates"), - new File("src/test/resources/foo.jar"))); + .find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar"))); assertThat(found).areAtLeastOne(new Condition() { @Override @@ -132,8 +117,7 @@ public class ResourceMatcherTests { @Test public void resourceMatching() throws IOException { - ResourceMatcher resourceMatcher = new ResourceMatcher( - Arrays.asList("alpha/**", "bravo/*", "*"), + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); List matchedResources = resourceMatcher .find(Arrays.asList(new File("src/test/resources/resource-matcher/one"), @@ -143,8 +127,7 @@ public class ResourceMatcherTests { for (MatchedResource resource : matchedResources) { paths.add(resource.getName()); } - assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", - "bravo/fileE", "fileF", "three"); + assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", "bravo/fileE", "fileF", "three"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java index f29bf2827c0..e34fea45f13 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,8 @@ public class EncodePasswordCommandTests { ExitStatus status = command.run("boot"); verify(this.log).info(this.message.capture()); assertThat(this.message.getValue()).startsWith("{bcrypt}"); - assertThat(PasswordEncoderFactories.createDelegatingPasswordEncoder() - .matches("boot", this.message.getValue())).isTrue(); + assertThat(PasswordEncoderFactories.createDelegatingPasswordEncoder().matches("boot", this.message.getValue())) + .isTrue(); assertThat(status).isEqualTo(ExitStatus.OK); } @@ -72,8 +72,7 @@ public class EncodePasswordCommandTests { ExitStatus status = command.run("-a", "bcrypt", "boot"); verify(this.log).info(this.message.capture()); assertThat(this.message.getValue()).doesNotStartWith("{"); - assertThat(new BCryptPasswordEncoder().matches("boot", this.message.getValue())) - .isTrue(); + assertThat(new BCryptPasswordEncoder().matches("boot", this.message.getValue())).isTrue(); assertThat(status).isEqualTo(ExitStatus.OK); } @@ -83,8 +82,7 @@ public class EncodePasswordCommandTests { ExitStatus status = command.run("-a", "pbkdf2", "boot"); verify(this.log).info(this.message.capture()); assertThat(this.message.getValue()).doesNotStartWith("{"); - assertThat(new Pbkdf2PasswordEncoder().matches("boot", this.message.getValue())) - .isTrue(); + assertThat(new Pbkdf2PasswordEncoder().matches("boot", this.message.getValue())).isTrue(); assertThat(status).isEqualTo(ExitStatus.OK); } @@ -92,8 +90,7 @@ public class EncodePasswordCommandTests { public void encodeWithUnknownAlgorithmShouldExitWithError() throws Exception { EncodePasswordCommand command = new EncodePasswordCommand(); ExitStatus status = command.run("--algorithm", "bad", "boot"); - verify(this.log) - .error("Unknown algorithm, valid options are: default,bcrypt,pbkdf2"); + verify(this.log).error("Unknown algorithm, valid options are: default,bcrypt,pbkdf2"); assertThat(status).isEqualTo(ExitStatus.ERROR); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java index c4675f24d53..43832319b64 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,30 +50,26 @@ public abstract class AbstractHttpClientMockTests { protected final CloseableHttpClient http = mock(CloseableHttpClient.class); protected void mockSuccessfulMetadataTextGet() throws IOException { - mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain", - true); + mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain", true); } - protected void mockSuccessfulMetadataGet(boolean serviceCapabilities) + protected void mockSuccessfulMetadataGet(boolean serviceCapabilities) throws IOException { + mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json", "application/vnd.initializr.v2.1+json", + serviceCapabilities); + } + + protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities) throws IOException { + mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json", "application/vnd.initializr.v2+json", + serviceCapabilities); + } + + protected void mockSuccessfulMetadataGet(String contentPath, String contentType, boolean serviceCapabilities) throws IOException { - mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json", - "application/vnd.initializr.v2.1+json", serviceCapabilities); - } - - protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities) - throws IOException { - mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json", - "application/vnd.initializr.v2+json", serviceCapabilities); - } - - protected void mockSuccessfulMetadataGet(String contentPath, String contentType, - boolean serviceCapabilities) throws IOException { CloseableHttpResponse response = mock(CloseableHttpResponse.class); byte[] content = readClasspathResource(contentPath); mockHttpEntity(response, content, contentType); mockStatus(response, 200); - given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))) - .willReturn(response); + given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))).willReturn(response); } protected byte[] readClasspathResource(String contentPath) throws IOException { @@ -81,46 +77,38 @@ public abstract class AbstractHttpClientMockTests { return StreamUtils.copyToByteArray(resource.getInputStream()); } - protected void mockSuccessfulProjectGeneration( - MockHttpProjectGenerationRequest request) throws IOException { + protected void mockSuccessfulProjectGeneration(MockHttpProjectGenerationRequest request) throws IOException { // Required for project generation as the metadata is read first mockSuccessfulMetadataGet(false); CloseableHttpResponse response = mock(CloseableHttpResponse.class); mockHttpEntity(response, request.content, request.contentType); mockStatus(response, 200); - String header = (request.fileName != null) - ? contentDispositionValue(request.fileName) : null; + String header = (request.fileName != null) ? contentDispositionValue(request.fileName) : null; mockHttpHeader(response, "Content-Disposition", header); given(this.http.execute(argThat(getForNonMetadata()))).willReturn(response); } - protected void mockProjectGenerationError(int status, String message) - throws IOException, JSONException { + protected void mockProjectGenerationError(int status, String message) throws IOException, JSONException { // Required for project generation as the metadata is read first mockSuccessfulMetadataGet(false); CloseableHttpResponse response = mock(CloseableHttpResponse.class); - mockHttpEntity(response, createJsonError(status, message).getBytes(), - "application/json"); + mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json"); mockStatus(response, status); given(this.http.execute(isA(HttpGet.class))).willReturn(response); } - protected void mockMetadataGetError(int status, String message) - throws IOException, JSONException { + protected void mockMetadataGetError(int status, String message) throws IOException, JSONException { CloseableHttpResponse response = mock(CloseableHttpResponse.class); - mockHttpEntity(response, createJsonError(status, message).getBytes(), - "application/json"); + mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json"); mockStatus(response, status); given(this.http.execute(isA(HttpGet.class))).willReturn(response); } - protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content, - String contentType) { + protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content, String contentType) { try { HttpEntity entity = mock(HttpEntity.class); given(entity.getContent()).willReturn(new ByteArrayInputStream(content)); - Header contentTypeHeader = (contentType != null) - ? new BasicHeader("Content-Type", contentType) : null; + Header contentTypeHeader = (contentType != null) ? new BasicHeader("Content-Type", contentType) : null; given(entity.getContentType()).willReturn(contentTypeHeader); given(response.getEntity()).willReturn(entity); return entity; @@ -136,8 +124,7 @@ public abstract class AbstractHttpClientMockTests { given(response.getStatusLine()).willReturn(statusLine); } - protected void mockHttpHeader(CloseableHttpResponse response, String headerName, - String value) { + protected void mockHttpHeader(CloseableHttpResponse response, String headerName, String value) { Header header = (value != null) ? new BasicHeader(headerName, value) : null; given(response.getFirstHeader(headerName)).willReturn(header); } @@ -178,8 +165,7 @@ public abstract class AbstractHttpClientMockTests { this(contentType, fileName, new byte[] { 0, 0, 0, 0 }); } - public MockHttpProjectGenerationRequest(String contentType, String fileName, - byte[] content) { + public MockHttpProjectGenerationRequest(String contentType, String fileName, byte[] content) { this.contentType = contentType; this.fileName = fileName; this.content = content; diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java index f71790c368a..fdfcbde0191 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java @@ -92,8 +92,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); assertThat(file.exists()).as("file should not exist").isFalse(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", fileName); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", fileName); mockSuccessfulProjectGeneration(request); try { assertThat(this.command.run()).isEqualTo(ExitStatus.OK); @@ -106,8 +105,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { @Test public void generateProjectNoFileNameAvailable() throws Exception { - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", null); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", null); mockSuccessfulProjectGeneration(request); assertThat(this.command.run()).isEqualTo(ExitStatus.ERROR); } @@ -116,25 +114,22 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void generateProjectAndExtract() throws Exception { File folder = this.temporaryFolder.newFolder(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); File archiveFile = new File(folder, "test.txt"); assertThat(archiveFile).exists(); } @Test - public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() - throws Exception { + public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() throws Exception { File folder = this.temporaryFolder.newFolder(); byte[] archive = createFakeZipArchive("../outside.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.ERROR); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); File archiveFile = new File(folder.getParentFile(), "outside.txt"); assertThat(archiveFile).doesNotExist(); } @@ -143,11 +138,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void generateProjectAndExtractWithConvention() throws Exception { File folder = this.temporaryFolder.newFolder(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run(folder.getAbsolutePath() + "/")) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run(folder.getAbsolutePath() + "/")).isEqualTo(ExitStatus.OK); File archiveFile = new File(folder, "test.txt"); assertThat(archiveFile).exists(); } @@ -157,8 +151,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { String fileName = UUID.randomUUID().toString(); assertThat(fileName.contains(".")).as("No dot in filename").isFalse(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); File file = new File(fileName); File archiveFile = new File(file, "test.txt"); @@ -177,8 +171,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { String fileName = UUID.randomUUID().toString(); String content = "Fake Content"; byte[] archive = content.getBytes(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/octet-stream", "pom.xml", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/octet-stream", + "pom.xml", archive); mockSuccessfulProjectGeneration(request); File file = new File(fileName); try { @@ -199,11 +193,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests { assertThat(file.exists()).as("file should not exist").isFalse(); try { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/foobar", fileName, archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/foobar", + fileName, archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { @@ -219,11 +212,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests { assertThat(file.exists()).as("file should not exist").isFalse(); try { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - null, fileName, archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(null, fileName, archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { @@ -235,21 +226,19 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void fileNotOverwrittenByDefault() throws Exception { File file = this.temporaryFolder.newFile(); long fileLength = file.length(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", file.getAbsolutePath()); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", + file.getAbsolutePath()); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run()).as("Should have failed") - .isEqualTo(ExitStatus.ERROR); - assertThat(file.length()).as("File should not have changed") - .isEqualTo(fileLength); + assertThat(this.command.run()).as("Should have failed").isEqualTo(ExitStatus.ERROR); + assertThat(file.length()).as("File should not have changed").isEqualTo(fileLength); } @Test public void overwriteFile() throws Exception { File file = this.temporaryFolder.newFile(); long fileLength = file.length(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", file.getAbsolutePath()); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", + file.getAbsolutePath()); mockSuccessfulProjectGeneration(request); assertThat(this.command.run("--force")).isEqualTo(ExitStatus.OK); assertThat(fileLength != file.length()).as("File should have changed").isTrue(); @@ -259,33 +248,28 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void fileInArchiveNotOverwrittenByDefault() throws Exception { File folder = this.temporaryFolder.newFolder(); File conflict = new File(folder, "test.txt"); - assertThat(conflict.createNewFile()).as("Should have been able to create file") - .isTrue(); + assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue(); long fileLength = conflict.length(); // also contains test.txt byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.ERROR); - assertThat(conflict.length()).as("File should not have changed") - .isEqualTo(fileLength); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); + assertThat(conflict.length()).as("File should not have changed").isEqualTo(fileLength); } @Test public void parseProjectOptions() throws Exception { this.handler.disableProjectGeneration(); this.command.run("-g=org.demo", "-a=acme", "-v=1.2.3-SNAPSHOT", "-n=acme-sample", - "--description=Acme sample project", "--package-name=demo.foo", - "-t=ant-project", "--build=grunt", "--format=web", "-p=war", "-j=1.9", - "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa"); + "--description=Acme sample project", "--package-name=demo.foo", "-t=ant-project", "--build=grunt", + "--format=web", "-p=war", "-j=1.9", "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa"); assertThat(this.handler.lastRequest.getGroupId()).isEqualTo("org.demo"); assertThat(this.handler.lastRequest.getArtifactId()).isEqualTo("acme"); assertThat(this.handler.lastRequest.getVersion()).isEqualTo("1.2.3-SNAPSHOT"); assertThat(this.handler.lastRequest.getName()).isEqualTo("acme-sample"); - assertThat(this.handler.lastRequest.getDescription()) - .isEqualTo("Acme sample project"); + assertThat(this.handler.lastRequest.getDescription()).isEqualTo("Acme sample project"); assertThat(this.handler.lastRequest.getPackageName()).isEqualTo("demo.foo"); assertThat(this.handler.lastRequest.getType()).isEqualTo("ant-project"); assertThat(this.handler.lastRequest.getBuild()).isEqualTo("grunt"); @@ -304,18 +288,15 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void overwriteFileInArchive() throws Exception { File folder = this.temporaryFolder.newFolder(); File conflict = new File(folder, "test.txt"); - assertThat(conflict.createNewFile()).as("Should have been able to create file") - .isTrue(); + assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue(); long fileLength = conflict.length(); // also contains test.txt byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); - assertThat(fileLength != conflict.length()).as("File should have changed") - .isTrue(); + assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); + assertThat(fileLength != conflict.length()).as("File should have changed").isTrue(); } @Test @@ -377,10 +358,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { assertThat(agent.getValue()).startsWith("SpringBootCli/"); } - private byte[] createFakeZipArchive(String fileName, String content) - throws IOException { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(bos)) { + private byte[] createFakeZipArchive(String fileName, String content) throws IOException { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos)) { ZipEntry entry = new ZipEntry(fileName); zos.putNextEntry(entry); zos.write(content.getBytes()); @@ -389,8 +368,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } } - private static class TestableInitCommandOptionHandler - extends InitCommand.InitOptionHandler { + private static class TestableInitCommandOptionHandler extends InitCommand.InitOptionHandler { private boolean disableProjectGeneration; diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java index 628bf294607..cf7180b6437 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ public class InitializrServiceMetadataTests { assertThat(metadata.getDefaults().get("javaVersion")).isEqualTo("1.7"); assertThat(metadata.getDefaults().get("groupId")).isEqualTo("org.test"); assertThat(metadata.getDefaults().get("name")).isEqualTo("demo"); - assertThat(metadata.getDefaults().get("description")) - .isEqualTo("Demo project for Spring Boot"); + assertThat(metadata.getDefaults().get("description")).isEqualTo("Demo project for Spring Boot"); assertThat(metadata.getDefaults().get("packaging")).isEqualTo("jar"); assertThat(metadata.getDefaults().get("language")).isEqualTo("java"); assertThat(metadata.getDefaults().get("artifactId")).isEqualTo("demo"); @@ -63,8 +62,7 @@ public class InitializrServiceMetadataTests { // Security description assertThat(metadata.getDependency("aop").getName()).isEqualTo("AOP"); assertThat(metadata.getDependency("security").getName()).isEqualTo("Security"); - assertThat(metadata.getDependency("security").getDescription()) - .isEqualTo("Security description"); + assertThat(metadata.getDependency("security").getDescription()).isEqualTo("Security description"); assertThat(metadata.getDependency("jdbc").getName()).isEqualTo("JDBC"); assertThat(metadata.getDependency("data-jpa").getName()).isEqualTo("JPA"); assertThat(metadata.getDependency("data-mongodb").getName()).isEqualTo("MongoDB"); @@ -79,8 +77,7 @@ public class InitializrServiceMetadataTests { assertThat(projectType.getTags().get("format")).isEqualTo("project"); } - private static InitializrServiceMetadata createInstance(String version) - throws JSONException { + private static InitializrServiceMetadata createInstance(String version) throws JSONException { try { return new InitializrServiceMetadata(readJson(version)); } @@ -90,11 +87,9 @@ public class InitializrServiceMetadataTests { } private static JSONObject readJson(String version) throws IOException, JSONException { - Resource resource = new ClassPathResource( - "metadata/service-metadata-" + version + ".json"); + Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json"); try (InputStream stream = resource.getInputStream()) { - return new JSONObject( - StreamUtils.copyToString(stream, StandardCharsets.UTF_8)); + return new JSONObject(StreamUtils.copyToString(stream, StandardCharsets.UTF_8)); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index 7d0b39119ea..1daeef24be5 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -45,19 +45,18 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { @Test public void generateSimpleProject() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); - MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest( - "application/xml", "foo.zip"); + MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", + "foo.zip"); ProjectGenerationResponse entity = generateProject(request, mockHttpRequest); - assertProjectEntity(entity, mockHttpRequest.contentType, - mockHttpRequest.fileName); + assertProjectEntity(entity, mockHttpRequest.contentType, mockHttpRequest.fileName); } @Test public void generateProjectCustomTargetFilename() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); request.setOutput("bar.zip"); - MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest( - "application/xml", null); + MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", + null); ProjectGenerationResponse entity = generateProject(request, mockHttpRequest); assertProjectEntity(entity, mockHttpRequest.contentType, null); } @@ -65,8 +64,8 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { @Test public void generateProjectNoDefaultFileName() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); - MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest( - "application/xml", null); + MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", + null); ProjectGenerationResponse entity = generateProject(request, mockHttpRequest); assertProjectEntity(entity, mockHttpRequest.contentType, null); } @@ -77,8 +76,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockProjectGenerationError(400, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); request.getDependencies().add("foo:bar"); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.invoker.generate(request)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) .withMessageContaining(jsonMessage); } @@ -86,8 +84,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { public void generateProjectBadRequestNoExtraMessage() throws Exception { mockProjectGenerationError(400, null); ProjectGenerationRequest request = new ProjectGenerationRequest(); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.invoker.generate(request)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) .withMessageContaining("unexpected 400 error"); } @@ -98,8 +95,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockStatus(response, 500); given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.invoker.generate(request)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) .withMessageContaining("No content received from server"); } @@ -108,8 +104,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { String jsonMessage = "whatever error on the server"; mockMetadataGetError(500, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.invoker.generate(request)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) .withMessageContaining(jsonMessage); } @@ -120,8 +115,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockStatus(response, 200); given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.invoker.generate(request)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) .withMessageContaining("Invalid content received from server"); } @@ -131,8 +125,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockStatus(response, 500); given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.invoker.generate(request)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) .withMessageContaining("No content received from server"); } @@ -140,13 +133,11 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest mockRequest) throws Exception { mockSuccessfulProjectGeneration(mockRequest); ProjectGenerationResponse entity = this.invoker.generate(request); - assertThat(entity.getContent()).as("wrong body content") - .isEqualTo(mockRequest.content); + assertThat(entity.getContent()).as("wrong body content").isEqualTo(mockRequest.content); return entity; } - private static void assertProjectEntity(ProjectGenerationResponse entity, - String mimeType, String fileName) { + private static void assertProjectEntity(ProjectGenerationResponse entity, String mimeType, String fileName) { if (mimeType == null) { assertThat(entity.getContentType()).isNull(); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index 145d6035e7b..0c34eaee764 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -48,8 +48,7 @@ public class ProjectGenerationRequestTests { @Test public void defaultSettings() { - assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(createDefaultUrl("?type=test-type")); } @Test @@ -57,8 +56,8 @@ public class ProjectGenerationRequestTests { String customServerUrl = "https://foo:8080/initializr"; this.request.setServiceUrl(customServerUrl); this.request.getDependencies().add("security"); - assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(new URI( - customServerUrl + "/starter.zip?dependencies=security&type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type")); } @Test @@ -79,8 +78,8 @@ public class ProjectGenerationRequestTests { public void multipleDependencies() { this.request.getDependencies().add("web"); this.request.getDependencies().add("data-jpa"); - assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo( - createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); } @Test @@ -99,14 +98,12 @@ public class ProjectGenerationRequestTests { @Test public void customType() throws URISyntaxException { - ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, - EMPTY_TAGS); + ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, EMPTY_TAGS); InitializrServiceMetadata metadata = new InitializrServiceMetadata(projectType); this.request.setType("custom"); this.request.getDependencies().add("data-rest"); - assertThat(this.request.generateUrl(metadata)) - .isEqualTo(new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL - + "/foo?dependencies=data-rest&type=custom")); + assertThat(this.request.generateUrl(metadata)).isEqualTo( + new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL + "/foo?dependencies=data-rest&type=custom")); } @Test @@ -130,9 +127,8 @@ public class ProjectGenerationRequestTests { this.request.setVersion("1.0.1-SNAPSHOT"); this.request.setDescription("Spring Boot Test"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl( - "?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" - + "&description=Spring+Boot+Test&type=test-type")); + .isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" + + "&description=Spring+Boot+Test&type=test-type")); } @Test @@ -152,8 +148,8 @@ public class ProjectGenerationRequestTests { @Test public void outputArchiveWithDotsCustomizeArtifactId() { this.request.setOutput("my.nice.project.zip"); - assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo( - createDefaultUrl("?artifactId=my.nice.project&type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); } @Test @@ -168,8 +164,7 @@ public class ProjectGenerationRequestTests { public void buildNoMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("does-not-exist", null); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.request.generateUrl(metadata)) + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) .withMessageContaining("does-not-exist"); } @@ -177,18 +172,15 @@ public class ProjectGenerationRequestTests { public void buildMultipleMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata("types-conflict"); setBuildAndFormat("gradle", null); - assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.request.generateUrl(metadata)) - .withMessageContaining("gradle-project") - .withMessageContaining("gradle-project-2"); + assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) + .withMessageContaining("gradle-project").withMessageContaining("gradle-project-2"); } @Test public void buildOneMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", null); - assertThat(this.request.generateUrl(metadata)) - .isEqualTo(createDefaultUrl("?type=gradle-project")); + assertThat(this.request.generateUrl(metadata)).isEqualTo(createDefaultUrl("?type=gradle-project")); } @Test @@ -196,8 +188,7 @@ public class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", "project"); this.request.setType("maven-build"); - assertThat(this.request.generateUrl(metadata)) - .isEqualTo(createUrl("/pom.xml?type=maven-build")); + assertThat(this.request.generateUrl(metadata)).isEqualTo(createUrl("/pom.xml?type=maven-build")); } @Test @@ -210,8 +201,7 @@ public class ProjectGenerationRequestTests { @Test public void noTypeAndNoDefault() throws Exception { assertThatExceptionOfType(ReportableException.class) - .isThrownBy( - () -> this.request.generateUrl(readMetadata("types-conflict"))) + .isThrownBy(() -> this.request.generateUrl(readMetadata("types-conflict"))) .withMessageContaining("no default is defined"); } @@ -235,8 +225,7 @@ public class ProjectGenerationRequestTests { } private static InitializrServiceMetadata createDefaultMetadata() { - ProjectType projectType = new ProjectType("test-type", "The test type", - "/starter.zip", true, EMPTY_TAGS); + ProjectType projectType = new ProjectType("test-type", "The test type", "/starter.zip", true, EMPTY_TAGS); return new InitializrServiceMetadata(projectType); } @@ -244,13 +233,10 @@ public class ProjectGenerationRequestTests { return readMetadata("2.0.0"); } - private static InitializrServiceMetadata readMetadata(String version) - throws JSONException { + private static InitializrServiceMetadata readMetadata(String version) throws JSONException { try { - Resource resource = new ClassPathResource( - "metadata/service-metadata-" + version + ".json"); - String content = StreamUtils.copyToString(resource.getInputStream(), - StandardCharsets.UTF_8); + Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json"); + String content = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8); JSONObject json = new JSONObject(content); return new InitializrServiceMetadata(json); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java index 6c1e886df07..1ce44a082bb 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientM @Test public void listMetadataFromServer() throws IOException { mockSuccessfulMetadataTextGet(); - String expected = new String( - readClasspathResource("metadata/service-metadata-2.1.0.txt")); + String expected = new String(readClasspathResource("metadata/service-metadata-2.1.0.txt")); String content = this.command.generate("http://localhost"); assertThat(content).isEqualTo(expected); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java index 0cd37d6a8d7..391f23a9734 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java @@ -72,8 +72,7 @@ public class GroovyGrabDependencyResolverTests { @Override public List getRepositoryConfiguration() { - return RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + return RepositoryConfigurationFactory.createDefaultRepositoryConfiguration(); } @Override @@ -92,19 +91,16 @@ public class GroovyGrabDependencyResolverTests { @Test public void resolveArtifactWithNoDependencies() throws Exception { - List resolved = this.resolver - .resolve(Arrays.asList("commons-logging:commons-logging:1.1.3")); + List resolved = this.resolver.resolve(Arrays.asList("commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(1); assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar"); } @Test public void resolveArtifactWithDependencies() throws Exception { - List resolved = this.resolver - .resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE")); + List resolved = this.resolver.resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE")); assertThat(resolved).hasSize(2); - assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", - "spring-core-4.1.1.RELEASE.jar"); + assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", "spring-core-4.1.1.RELEASE.jar"); } @Test @@ -112,18 +108,17 @@ public class GroovyGrabDependencyResolverTests { public void resolveShorthandArtifactWithDependencies() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("spring-beans")); assertThat(resolved).hasSize(3); - assertThat(getNames(resolved)) - .has((Condition) Matched.by(hasItems(startsWith("spring-core-"), - startsWith("spring-beans-"), startsWith("spring-jcl-")))); + assertThat(getNames(resolved)).has((Condition) Matched + .by(hasItems(startsWith("spring-core-"), startsWith("spring-beans-"), startsWith("spring-jcl-")))); } @Test public void resolveMultipleArtifacts() throws Exception { - List resolved = this.resolver.resolve(Arrays.asList("junit:junit:4.11", - "commons-logging:commons-logging:1.1.3")); + List resolved = this.resolver + .resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(4); - assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", - "commons-logging-1.1.3.jar", "hamcrest-core-2.1.jar", "hamcrest-2.1.jar"); + assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", "commons-logging-1.1.3.jar", + "hamcrest-core-2.1.jar", "hamcrest-2.1.jar"); } public Set getNames(Collection files) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java index 677749dc5fc..0d60c8b877d 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,19 +79,14 @@ public class InstallerTests { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); - given(this.resolver.resolve(Arrays.asList("bravo"))) - .willReturn(Arrays.asList(bravo, alpha)); - given(this.resolver.resolve(Arrays.asList("charlie"))) - .willReturn(Arrays.asList(charlie, alpha)); + given(this.resolver.resolve(Arrays.asList("bravo"))).willReturn(Arrays.asList(bravo, alpha)); + given(this.resolver.resolve(Arrays.asList("charlie"))).willReturn(Arrays.asList(charlie, alpha)); this.installer.install(Arrays.asList("bravo")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", - ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", ".installed"); this.installer.install(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", - "charlie.jar", ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed"); this.installer.uninstall(Arrays.asList("bravo")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar", - ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar", ".installed"); this.installer.uninstall(Arrays.asList("charlie")); assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed"); } @@ -101,14 +96,11 @@ public class InstallerTests { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); - given(this.resolver.resolve(Arrays.asList("bravo"))) - .willReturn(Arrays.asList(bravo, alpha)); - given(this.resolver.resolve(Arrays.asList("charlie"))) - .willReturn(Arrays.asList(charlie, alpha)); + given(this.resolver.resolve(Arrays.asList("bravo"))).willReturn(Arrays.asList(bravo, alpha)); + given(this.resolver.resolve(Arrays.asList("charlie"))).willReturn(Arrays.asList(charlie, alpha)); this.installer.install(Arrays.asList("bravo")); this.installer.install(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", - "charlie.jar", ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed"); this.installer.uninstallAll(); assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java index 8250e0b29be..3ad83fb2a6e 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,13 +33,12 @@ public class SpringApplicationRunnerTests { @Test public void exceptionMessageWhenSourcesContainsNoClasses() throws Exception { - SpringApplicationRunnerConfiguration configuration = mock( - SpringApplicationRunnerConfiguration.class); + SpringApplicationRunnerConfiguration configuration = mock(SpringApplicationRunnerConfiguration.class); given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" }); given(configuration.getLogLevel()).willReturn(Level.INFO); assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> new SpringApplicationRunner(configuration, - new String[] { "foo", "bar" }).compileAndRun()) + .isThrownBy( + () -> new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun()) .withMessage("No classes found in '[foo, bar]'"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java index b1829ff7172..ad4b2849da6 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void simple() { String s = "one two"; - assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", - "two"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", "two"); assertThat(this.delimiter.parseArguments(s)).containsExactly("one", "two"); assertThat(this.delimiter.isDelimiter(s, 2)).isFalse(); assertThat(this.delimiter.isDelimiter(s, 3)).isTrue(); @@ -44,8 +43,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void escaped() { String s = "o\\ ne two"; - assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", - "two"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", "two"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "two"); assertThat(this.delimiter.isDelimiter(s, 2)).isFalse(); assertThat(this.delimiter.isDelimiter(s, 3)).isFalse(); @@ -56,26 +54,22 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void quoted() { String s = "'o ne' 't w o'"; - assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", - "'t w o'"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", "'t w o'"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test public void doubleQuoted() { String s = "\"o ne\" \"t w o\""; - assertThat(this.delimiter.delimit(s, 0).getArguments()) - .containsExactly("\"o ne\"", "\"t w o\""); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o ne\"", "\"t w o\""); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test public void nestedQuotes() { String s = "\"o 'n''e\" 't \"w o'"; - assertThat(this.delimiter.delimit(s, 0).getArguments()) - .containsExactly("\"o 'n''e\"", "'t \"w o'"); - assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", - "t \"w o"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o 'n''e\"", "'t \"w o'"); + assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", "t \"w o"); } @Test diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java index d5d9a16e462..cd1cdc9c7d0 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,14 +55,11 @@ public class DependencyCustomizerTests { @Before public void setUp() { MockitoAnnotations.initMocks(this); - given(this.resolver.getGroupId("spring-boot-starter-logging")) - .willReturn("org.springframework.boot"); - given(this.resolver.getArtifactId("spring-boot-starter-logging")) - .willReturn("spring-boot-starter-logging"); + given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); + given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging"); this.moduleNode.addClass(this.classNode); - this.dependencyCustomizer = new DependencyCustomizer( - new GroovyClassLoader(getClass().getClassLoader()), this.moduleNode, - new DependencyResolutionContext() { + this.dependencyCustomizer = new DependencyCustomizer(new GroovyClassLoader(getClass().getClassLoader()), + this.moduleNode, new DependencyResolutionContext() { @Override public ArtifactCoordinatesResolver getArtifactCoordinatesResolver() { @@ -75,86 +72,74 @@ public class DependencyCustomizerTests { @Test public void basicAdd() { this.dependencyCustomizer.add("spring-boot-starter-logging"); - List grabAnnotations = this.classNode - .getAnnotations(new ClassNode(Grab.class)); + List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); - assertGrabAnnotation(annotationNode, "org.springframework.boot", - "spring-boot-starter-logging", "1.2.3", null, null, true); + assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null, + null, true); } @Test public void nonTransitiveAdd() { this.dependencyCustomizer.add("spring-boot-starter-logging", false); - List grabAnnotations = this.classNode - .getAnnotations(new ClassNode(Grab.class)); + List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); - assertGrabAnnotation(annotationNode, "org.springframework.boot", - "spring-boot-starter-logging", "1.2.3", null, null, false); + assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null, + null, false); } @Test public void fullyCustomized() { - this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier", - "my-type", false); - List grabAnnotations = this.classNode - .getAnnotations(new ClassNode(Grab.class)); + this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier", "my-type", false); + List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); - assertGrabAnnotation(annotationNode, "org.springframework.boot", - "spring-boot-starter-logging", "1.2.3", "my-classifier", "my-type", - false); + assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", + "my-classifier", "my-type", false); } @Test public void anyMissingClassesWithMissingClassesPerformsAdd() { - this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist") - .add("spring-boot-starter-logging"); + this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist").add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test public void anyMissingClassesWithMixtureOfClassesPerformsAdd() { - this.dependencyCustomizer - .ifAnyMissingClasses(getClass().getName(), "does.not.Exist") + this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test public void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() { - this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()) - .add("spring-boot-starter-logging"); + this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()).add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() { - this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()) - .add("spring-boot-starter-logging"); + this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()).add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() { - this.dependencyCustomizer - .ifAllMissingClasses(getClass().getName(), "does.not.Exist") + this.dependencyCustomizer.ifAllMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithAllClassesMissingPerformsAdd() { - this.dependencyCustomizer - .ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") + this.dependencyCustomizer.ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } - private void assertGrabAnnotation(AnnotationNode annotationNode, String group, - String module, String version, String classifier, String type, - boolean transitive) { + private void assertGrabAnnotation(AnnotationNode annotationNode, String group, String module, String version, + String classifier, String type, boolean transitive) { assertThat(getMemberValue(annotationNode, "group")).isEqualTo(group); assertThat(getMemberValue(annotationNode, "module")).isEqualTo(module); if (type == null) { @@ -167,8 +152,7 @@ public class DependencyCustomizerTests { assertThat(annotationNode.getMember("classifier")).isNull(); } else { - assertThat(getMemberValue(annotationNode, "classifier")) - .isEqualTo(classifier); + assertThat(getMemberValue(annotationNode, "classifier")).isEqualTo(classifier); } assertThat(getMemberValue(annotationNode, "transitive")).isEqualTo(transitive); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java index e1398a66083..2f2f0d9cea2 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class ExtendedGroovyClassLoaderTests { @Before public void setup() { this.contextClassLoader = Thread.currentThread().getContextClassLoader(); - this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader( - GroovyCompilerScope.DEFAULT); + this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(GroovyCompilerScope.DEFAULT); } @Test @@ -51,8 +50,7 @@ public class ExtendedGroovyClassLoaderTests { public void filtersNonGroovy() throws Exception { this.contextClassLoader.loadClass("org.springframework.util.StringUtils"); assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> this.defaultScopeGroovyClassLoader - .loadClass("org.springframework.util.StringUtils")); + .isThrownBy(() -> this.defaultScopeGroovyClassLoader.loadClass("org.springframework.util.StringUtils")); } @Test diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java index 066dc12ddeb..e788f657916 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public final class GenericBomAstTransformationTests { - private final SourceUnit sourceUnit = new SourceUnit((String) null, - (ReaderSource) null, null, null, null); + private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null); private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit); @@ -83,13 +82,11 @@ public final class GenericBomAstTransformationTests { this.moduleNode.setPackage(new PackageNode("foo")); ClassNode cls = ClassHelper.make("MyClass"); this.moduleNode.addClass(cls); - AnnotationNode annotation = new AnnotationNode( - ClassHelper.make(DependencyManagementBom.class)); + AnnotationNode annotation = new AnnotationNode(ClassHelper.make(DependencyManagementBom.class)); annotation.addMember("value", new ConstantExpression("test:parent:1.0.0")); cls.addAnnotation(annotation); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertThat(getValue().toString()) - .isEqualTo("[test:parent:1.0.0, test:child:1.0.0]"); + assertThat(getValue().toString()).isEqualTo("[test:parent:1.0.0, test:child:1.0.0]"); } private List getValue() { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java index 1ae27155aae..fa7116d6b2e 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,72 +36,64 @@ public class RepositoryConfigurationFactoryTests { @Test public void defaultRepositories() { - TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic") - .applyToSystemProperties(() -> { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local", "spring-snapshot", "spring-milestone"); - return null; - }); + TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic").applyToSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone"); + return null; + }); } @Test public void snapshotRepositoriesDisabled() { - TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic", - "disableSpringSnapshotRepos:true").applyToSystemProperties(() -> { + TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true") + .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local"); return null; }); } @Test public void activeByDefaultProfileRepositories() { - TestPropertyValues.of( - "user.home:src/test/resources/maven-settings/active-profile-repositories") + TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories") .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local", "spring-snapshot", "spring-milestone", - "active-by-default"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "active-by-default"); return null; }); } @Test public void activeByPropertyProfileRepositories() { - TestPropertyValues.of( - "user.home:src/test/resources/maven-settings/active-profile-repositories", - "foo:bar").applyToSystemProperties(() -> { + TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar") + .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local", "spring-snapshot", "spring-milestone", - "active-by-property"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "active-by-property"); return null; }); } @Test public void interpolationProfileRepositories() { - TestPropertyValues.of( - "user.home:src/test/resources/maven-settings/active-profile-repositories", - "interpolate:true").applyToSystemProperties(() -> { + TestPropertyValues + .of("user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true") + .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local", "spring-snapshot", "spring-milestone", - "interpolate-releases", "interpolate-snapshots"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "interpolate-releases", "interpolate-snapshots"); return null; }); } - private void assertRepositoryConfiguration( - List configurations, String... expectedNames) { + private void assertRepositoryConfiguration(List configurations, String... expectedNames) { assertThat(configurations).hasSize(expectedNames.length); Set actualNames = new HashSet<>(); for (RepositoryConfiguration configuration : configurations) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java index 7522e1734c0..26ceeaf0e91 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,15 +57,13 @@ import static org.mockito.Mockito.mock; */ public final class ResolveDependencyCoordinatesTransformationTests { - private final SourceUnit sourceUnit = new SourceUnit((String) null, - (ReaderSource) null, null, null, null); + private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null); private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit); private final AnnotationNode grabAnnotation = createGrabAnnotation(); - private final ArtifactCoordinatesResolver coordinatesResolver = mock( - ArtifactCoordinatesResolver.class); + private final ArtifactCoordinatesResolver coordinatesResolver = mock(ArtifactCoordinatesResolver.class); private final DependencyResolutionContext resolutionContext = new DependencyResolutionContext() { @@ -85,8 +83,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { @Before public void setupExpectations() { - given(this.coordinatesResolver.getGroupId("spring-core")) - .willReturn("org.springframework"); + given(this.coordinatesResolver.getGroupId("spring-core")).willReturn("org.springframework"); } @Test @@ -97,24 +94,21 @@ public final class ResolveDependencyCoordinatesTransformationTests { @Test public void transformationOfAnnotationOnStarImport() { - this.moduleNode.addStarImport("org.springframework.util", - Arrays.asList(this.grabAnnotation)); + this.moduleNode.addStarImport("org.springframework.util", Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test public void transformationOfAnnotationOnStaticImport() { - this.moduleNode.addStaticImport(null, null, null, - Arrays.asList(this.grabAnnotation)); + this.moduleNode.addStaticImport(null, null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test public void transformationOfAnnotationOnStaticStarImport() { - this.moduleNode.addStaticStarImport(null, null, - Arrays.asList(this.grabAnnotation)); + this.moduleNode.addStaticStarImport(null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @@ -146,8 +140,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); - FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class), - classNode, null); + FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class), classNode, null); classNode.addField(fieldNode); fieldNode.addAnnotation(this.grabAnnotation); @@ -172,8 +165,8 @@ public final class ResolveDependencyCoordinatesTransformationTests { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); - MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), - new Parameter[0], new ClassNode[0], null); + MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0], + null); methodNode.addAnnotation(this.grabAnnotation); classNode.addMethod(methodNode); @@ -188,8 +181,8 @@ public final class ResolveDependencyCoordinatesTransformationTests { Parameter parameter = new Parameter(new ClassNode(Object.class), "test"); parameter.addAnnotation(this.grabAnnotation); - MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), - new Parameter[] { parameter }, new ClassNode[0], null); + MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[] { parameter }, + new ClassNode[0], null); classNode.addMethod(methodNode); assertGrabAnnotationHasBeenTransformed(); @@ -200,16 +193,15 @@ public final class ResolveDependencyCoordinatesTransformationTests { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); - DeclarationExpression declarationExpression = new DeclarationExpression( - new VariableExpression("test"), null, new ConstantExpression("test")); + DeclarationExpression declarationExpression = new DeclarationExpression(new VariableExpression("test"), null, + new ConstantExpression("test")); declarationExpression.addAnnotation(this.grabAnnotation); BlockStatement code = new BlockStatement( - Arrays.asList((Statement) new ExpressionStatement(declarationExpression)), - new VariableScope()); + Arrays.asList((Statement) new ExpressionStatement(declarationExpression)), new VariableScope()); - MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), - new Parameter[0], new ClassNode[0], code); + MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0], + code); classNode.addMethod(methodNode); @@ -225,8 +217,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { private void assertGrabAnnotationHasBeenTransformed() { this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertThat(getGrabAnnotationMemberAsString("group")) - .isEqualTo("org.springframework"); + assertThat(getGrabAnnotationMemberAsString("group")).isEqualTo("org.springframework"); assertThat(getGrabAnnotationMemberAsString("module")).isEqualTo("spring-core"); } @@ -239,8 +230,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { return null; } else { - throw new IllegalStateException( - "Member '" + memberName + "' is not a ConstantExpression"); + throw new IllegalStateException("Member '" + memberName + "' is not a ConstantExpression"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java index fa5b767cdff..95defdad293 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,35 +48,32 @@ public class CompositeDependencyManagementTests { public void unknownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null); given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getSpringBootVersion()).isNull(); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .getSpringBootVersion()).isNull(); } @Test public void knownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3"); given(this.dependencyManagement2.getSpringBootVersion()).willReturn("1.2.4"); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getSpringBootVersion()).isEqualTo("1.2.3"); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .getSpringBootVersion()).isEqualTo("1.2.3"); } @Test public void unknownDependency() { given(this.dependencyManagement1.find("artifact")).willReturn(null); given(this.dependencyManagement2.find("artifact")).willReturn(null); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).find("artifact")).isNull(); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .find("artifact")).isNull(); } @Test public void knownDependency() { - given(this.dependencyManagement1.find("artifact")) - .willReturn(new Dependency("test", "artifact", "1.2.3")); - given(this.dependencyManagement2.find("artifact")) - .willReturn(new Dependency("test", "artifact", "1.2.4")); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).find("artifact")) - .isEqualTo(new Dependency("test", "artifact", "1.2.3")); + given(this.dependencyManagement1.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.3")); + given(this.dependencyManagement2.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.4")); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3")); } @Test @@ -85,9 +82,8 @@ public class CompositeDependencyManagementTests { .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3"))); given(this.dependencyManagement2.getDependencies()) .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.4"))); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getDependencies()).containsOnly( - new Dependency("test", "artifact", "1.2.3"), + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .getDependencies()).containsOnly(new Dependency("test", "artifact", "1.2.3"), new Dependency("test", "artifact", "1.2.4")); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java index 9190054e27b..ea3dfe2349e 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,17 +41,14 @@ public class DependencyManagementArtifactCoordinatesResolverTests { @Before public void setup() { this.dependencyManagement = mock(DependencyManagement.class); - given(this.dependencyManagement.find("a1")) - .willReturn(new Dependency("g1", "a1", "0")); + given(this.dependencyManagement.find("a1")).willReturn(new Dependency("g1", "a1", "0")); given(this.dependencyManagement.getSpringBootVersion()).willReturn("1"); - this.resolver = new DependencyManagementArtifactCoordinatesResolver( - this.dependencyManagement); + this.resolver = new DependencyManagementArtifactCoordinatesResolver(this.dependencyManagement); } @Test public void getGroupIdForBootArtifact() { - assertThat(this.resolver.getGroupId("spring-boot-something")) - .isEqualTo("org.springframework.boot"); + assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot"); verify(this.dependencyManagement, never()).find(anyString()); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java index dd41caa3b4c..e7f3ae02c8b 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java @@ -47,20 +47,18 @@ public class AetherGrapeEngineTests { private final GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); - private final RepositoryConfiguration springMilestones = new RepositoryConfiguration( - "spring-milestones", URI.create("https://repo.spring.io/milestone"), false); + private final RepositoryConfiguration springMilestones = new RepositoryConfiguration("spring-milestones", + URI.create("https://repo.spring.io/milestone"), false); - private AetherGrapeEngine createGrapeEngine( - RepositoryConfiguration... additionalRepositories) { + private AetherGrapeEngine createGrapeEngine(RepositoryConfiguration... additionalRepositories) { List repositoryConfigurations = new ArrayList<>(); - repositoryConfigurations.add(new RepositoryConfiguration("central", - URI.create("https://repo1.maven.org/maven2"), false)); + repositoryConfigurations + .add(new RepositoryConfiguration("central", URI.create("https://repo1.maven.org/maven2"), false)); repositoryConfigurations.addAll(Arrays.asList(additionalRepositories)); DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext(); - dependencyResolutionContext.addDependencyManagement( - new SpringBootDependenciesDependencyManagement()); - return AetherGrapeEngineFactory.create(this.groovyClassLoader, - repositoryConfigurations, dependencyResolutionContext, false); + dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); + return AetherGrapeEngineFactory.create(this.groovyClassLoader, repositoryConfigurations, + dependencyResolutionContext, false); } @Test @@ -78,8 +76,7 @@ public class AetherGrapeEngineTests { DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils .getField(grapeEngine, "session"); - assertThat(session.getProxySelector() instanceof CompositeProxySelector) - .isTrue(); + assertThat(session.getProxySelector() instanceof CompositeProxySelector).isTrue(); }); } @@ -105,8 +102,7 @@ public class AetherGrapeEngineTests { @Test public void dependencyResolutionWithExclusions() { Map args = new HashMap<>(); - args.put("excludes", - Arrays.asList(createExclusion("org.springframework", "spring-core"))); + args.put("excludes", Arrays.asList(createExclusion("org.springframework", "spring-core"))); createGrapeEngine(this.springMilestones).grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE"), @@ -119,8 +115,7 @@ public class AetherGrapeEngineTests { public void nonTransitiveDependencyResolution() { Map args = new HashMap<>(); - createGrapeEngine().grab(args, createDependency("org.springframework", - "spring-jdbc", "3.2.4.RELEASE", false)); + createGrapeEngine().grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false)); assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1); } @@ -142,10 +137,9 @@ public class AetherGrapeEngineTests { public void resolutionWithCustomResolver() { Map args = new HashMap<>(); AetherGrapeEngine grapeEngine = this.createGrapeEngine(); - grapeEngine.addResolver( - createResolver("spring-releases", "https://repo.spring.io/release")); - Map dependency = createDependency("io.spring.docresources", - "spring-doc-resources", "0.1.1.RELEASE"); + grapeEngine.addResolver(createResolver("spring-releases", "https://repo.spring.io/release")); + Map dependency = createDependency("io.spring.docresources", "spring-doc-resources", + "0.1.1.RELEASE"); dependency.put("ext", "zip"); grapeEngine.grab(args, dependency); assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1); @@ -153,20 +147,18 @@ public class AetherGrapeEngineTests { @Test public void differingTypeAndExt() { - Map dependency = createDependency("org.grails", - "grails-dependencies", "2.4.0"); + Map dependency = createDependency("org.grails", "grails-dependencies", "2.4.0"); dependency.put("type", "foo"); dependency.put("ext", "bar"); AetherGrapeEngine grapeEngine = createGrapeEngine(); - assertThatIllegalArgumentException() - .isThrownBy(() -> grapeEngine.grab(Collections.emptyMap(), dependency)); + assertThatIllegalArgumentException().isThrownBy(() -> grapeEngine.grab(Collections.emptyMap(), dependency)); } @Test public void pomDependencyResolutionViaType() { Map args = new HashMap<>(); - Map dependency = createDependency("org.springframework", - "spring-framework-bom", "4.0.5.RELEASE"); + Map dependency = createDependency("org.springframework", "spring-framework-bom", + "4.0.5.RELEASE"); dependency.put("type", "pom"); createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); @@ -177,8 +169,8 @@ public class AetherGrapeEngineTests { @Test public void pomDependencyResolutionViaExt() { Map args = new HashMap<>(); - Map dependency = createDependency("org.springframework", - "spring-framework-bom", "4.0.5.RELEASE"); + Map dependency = createDependency("org.springframework", "spring-framework-bom", + "4.0.5.RELEASE"); dependency.put("ext", "pom"); createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); @@ -190,8 +182,7 @@ public class AetherGrapeEngineTests { public void resolutionWithClassifier() { Map args = new HashMap<>(); - Map dependency = createDependency("org.springframework", - "spring-jdbc", "3.2.4.RELEASE", false); + Map dependency = createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false); dependency.put("classifier", "sources"); createGrapeEngine().grab(args, dependency); @@ -203,12 +194,10 @@ public class AetherGrapeEngineTests { @SuppressWarnings("unchecked") private List getRepositories() { AetherGrapeEngine grapeEngine = createGrapeEngine(); - return (List) ReflectionTestUtils.getField(grapeEngine, - "repositories"); + return (List) ReflectionTestUtils.getField(grapeEngine, "repositories"); } - private Map createDependency(String group, String module, - String version) { + private Map createDependency(String group, String module, String version) { Map dependency = new HashMap<>(); dependency.put("group", group); dependency.put("module", module); @@ -216,8 +205,7 @@ public class AetherGrapeEngineTests { return dependency; } - private Map createDependency(String group, String module, - String version, boolean transitive) { + private Map createDependency(String group, String module, String version, boolean transitive) { Map dependency = createDependency(group, module, version); dependency.put("transitive", transitive); return dependency; @@ -238,8 +226,7 @@ public class AetherGrapeEngineTests { } private void doWithCustomUserHome(Runnable action) { - doWithSystemProperty("user.home", - new File("src/test/resources").getAbsolutePath(), action); + doWithSystemProperty("user.home", new File("src/test/resources").getAbsolutePath(), action); } private void doWithSystemProperty(String key, String value, Runnable action) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java index 5f7c708e0d7..f5e51663658 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class DependencyResolutionContextTests { @Test public void canAddSpringBootDependencies() { DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext(); - dependencyResolutionContext.addDependencyManagement( - new SpringBootDependenciesDependencyManagement()); + dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); assertThat(dependencyResolutionContext.getManagedDependencies()).isNotEmpty(); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java index 2f73d243a7a..1b4746b9640 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java @@ -39,8 +39,7 @@ public final class DetailedProgressReporterTests { private static final String ARTIFACT = "org/alpha/bravo/charlie/1.2.3/charlie-1.2.3.jar"; - private final TransferResource resource = new TransferResource(null, REPOSITORY, - ARTIFACT, null, null); + private final TransferResource resource = new TransferResource(null, REPOSITORY, ARTIFACT, null, null); private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -55,8 +54,7 @@ public final class DetailedProgressReporterTests { @Test public void downloading() throws TransferCancelledException { - TransferEvent startedEvent = new TransferEvent.Builder(this.session, - this.resource).build(); + TransferEvent startedEvent = new TransferEvent.Builder(this.session, this.resource).build(); this.session.getTransferListener().transferStarted(startedEvent); assertThat(new String(this.baos.toByteArray())) .isEqualTo(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT)); @@ -66,8 +64,8 @@ public final class DetailedProgressReporterTests { public void downloaded() throws InterruptedException { // Ensure some transfer time Thread.sleep(100); - TransferEvent completedEvent = new TransferEvent.Builder(this.session, - this.resource).addTransferredBytes(4096).build(); + TransferEvent completedEvent = new TransferEvent.Builder(this.session, this.resource).addTransferredBytes(4096) + .build(); this.session.getTransferListener().transferSucceeded(completedEvent); String message = new String(this.baos.toByteArray()).replace("\\", "/"); assertThat(message).startsWith("Downloaded: " + REPOSITORY + ARTIFACT); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java index 076d0a2744d..acdca4f64c9 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ import static org.mockito.Mockito.verify; */ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { - private DefaultRepositorySystemSession session = MavenRepositorySystemUtils - .newSession(); + private DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); @Mock private RepositorySystem repositorySystem; @@ -59,37 +58,31 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { @Test public void noLocalRepositoryWhenNoGrapeRoot() { - given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class))).willAnswer((invocation) -> { + given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) + .willAnswer((invocation) -> { LocalRepository localRepository = invocation.getArgument(1); return new SimpleLocalRepositoryManagerFactory().newInstance( - GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, - localRepository); + GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); }); - new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, - this.repositorySystem); - verify(this.repositorySystem, never()).newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class)); + new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); + verify(this.repositorySystem, never()).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); assertThat(this.session.getLocalRepository()).isNull(); } @Test public void grapeRootConfiguresLocalRepositoryLocation() { - given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class))) - .willAnswer(new LocalRepositoryManagerAnswer()); + given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) + .willAnswer(new LocalRepositoryManagerAnswer()); System.setProperty("grape.root", "foo"); try { - new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, - this.repositorySystem); + new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); } finally { System.clearProperty("grape.root"); } - verify(this.repositorySystem, times(1)) - .newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); + verify(this.repositorySystem, times(1)).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); assertThat(this.session.getLocalRepository()).isNotNull(); assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath()) @@ -99,12 +92,10 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { private class LocalRepositoryManagerAnswer implements Answer { @Override - public LocalRepositoryManager answer(InvocationOnMock invocation) - throws Throwable { + public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable { LocalRepository localRepository = invocation.getArgument(1); - return new SimpleLocalRepositoryManagerFactory().newInstance( - GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, - localRepository); + return new SimpleLocalRepositoryManagerFactory() + .newInstance(GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java index a39785e6200..db060b33fc6 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java @@ -66,20 +66,15 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { @Test public void propertyInterpolation() { - final DefaultRepositorySystemSession session = MavenRepositorySystemUtils - .newSession(); - given(this.repositorySystem.newLocalRepositoryManager(eq(session), - any(LocalRepository.class))).willAnswer((invocation) -> { + final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); + given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class))) + .willAnswer((invocation) -> { LocalRepository localRepository = invocation.getArgument(1); - return new SimpleLocalRepositoryManagerFactory().newInstance(session, - localRepository); + return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository); }); - TestPropertyValues - .of("user.home:src/test/resources/maven-settings/property-interpolation", - "foo:bar") + TestPropertyValues.of("user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar") .applyToSystemProperties(() -> { - new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( - session, + new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); return null; }); @@ -88,53 +83,42 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { } private void assertSessionCustomization(String userHome) { - final DefaultRepositorySystemSession session = MavenRepositorySystemUtils - .newSession(); + final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); TestPropertyValues.of("user.home:" + userHome).applyToSystemProperties(() -> { new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); return null; }); - RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", - "https://maven.example.com").build(); + RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "https://maven.example.com") + .build(); assertMirrorSelectorConfiguration(session, repository); assertProxySelectorConfiguration(session, repository); assertAuthenticationSelectorConfiguration(session, repository); } - private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session, - RemoteRepository repository) { + private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { Proxy proxy = session.getProxySelector().getProxy(repository); repository = new RemoteRepository.Builder(repository).setProxy(proxy).build(); - AuthenticationContext authenticationContext = AuthenticationContext - .forProxy(session, repository); + AuthenticationContext authenticationContext = AuthenticationContext.forProxy(session, repository); assertThat(proxy.getHost()).isEqualTo("proxy.example.com"); - assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) - .isEqualTo("proxyuser"); - assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) - .isEqualTo("somepassword"); + assertThat(authenticationContext.get(AuthenticationContext.USERNAME)).isEqualTo("proxyuser"); + assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)).isEqualTo("somepassword"); } private void assertMirrorSelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { RemoteRepository mirror = session.getMirrorSelector().getMirror(repository); - assertThat(mirror).as("Mirror configured for repository " + repository.getId()) - .isNotNull(); + assertThat(mirror).as("Mirror configured for repository " + repository.getId()).isNotNull(); assertThat(mirror.getHost()).isEqualTo("maven.example.com"); } - private void assertAuthenticationSelectorConfiguration( - DefaultRepositorySystemSession session, RemoteRepository repository) { - Authentication authentication = session.getAuthenticationSelector() - .getAuthentication(repository); - repository = new RemoteRepository.Builder(repository) - .setAuthentication(authentication).build(); - AuthenticationContext authenticationContext = AuthenticationContext - .forRepository(session, repository); - assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) - .isEqualTo("tester"); - assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) - .isEqualTo("secret"); + private void assertAuthenticationSelectorConfiguration(DefaultRepositorySystemSession session, + RemoteRepository repository) { + Authentication authentication = session.getAuthenticationSelector().getAuthentication(repository); + repository = new RemoteRepository.Builder(repository).setAuthentication(authentication).build(); + AuthenticationContext authenticationContext = AuthenticationContext.forRepository(session, repository); + assertThat(authenticationContext.get(AuthenticationContext.USERNAME)).isEqualTo("tester"); + assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)).isEqualTo("secret"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java index e0193224f3e..dea6fdba79a 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,16 +36,14 @@ public class ResourceUtilsTests { @Test public void explicitClasspathResource() { - List urls = ResourceUtils.getUrls("classpath:init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("classpath:init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void duplicateResource() throws Exception { - URLClassLoader loader = new URLClassLoader(new URL[] { - new URL("file:./src/test/resources/"), + URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:./src/test/resources/"), new File("src/test/resources/").getAbsoluteFile().toURI().toURL() }); List urls = ResourceUtils.getUrls("classpath:init.groovy", loader); assertThat(urls).hasSize(1); @@ -54,24 +52,21 @@ public class ResourceUtilsTests { @Test public void explicitClasspathResourceWithSlash() { - List urls = ResourceUtils.getUrls("classpath:/init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("classpath:/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitClasspathResource() { - List urls = ResourceUtils.getUrls("init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitClasspathResourceWithSlash() { - List urls = ResourceUtils.getUrls("/init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @@ -92,8 +87,7 @@ public class ResourceUtilsTests { @Test public void implicitFile() { - List urls = ResourceUtils.getUrls("src/test/resources/init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @@ -106,16 +100,14 @@ public class ResourceUtilsTests { @Test public void recursiveFiles() { - List urls = ResourceUtils.getUrls("src/test/resources/dir-sample", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("src/test/resources/dir-sample", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void recursiveFilesByPatternWithPrefix() { - List urls = ResourceUtils.getUrls( - "file:src/test/resources/dir-sample/**/*.groovy", + List urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); @@ -123,8 +115,7 @@ public class ResourceUtilsTests { @Test public void recursiveFilesByPattern() { - List urls = ResourceUtils.getUrls( - "src/test/resources/dir-sample/**/*.groovy", + List urls = ResourceUtils.getUrls("src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); @@ -132,8 +123,7 @@ public class ResourceUtilsTests { @Test public void directoryOfFilesWithPrefix() { - List urls = ResourceUtils.getUrls( - "file:src/test/resources/dir-sample/code/*", + List urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/code/*", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java index 429e1a555dc..2e2b17349f5 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ public final class RemoteSpringApplication { private void run(String[] args) { Restarter.initialize(args, RestartInitializer.NONE); - SpringApplication application = new SpringApplication( - RemoteClientConfiguration.class); + SpringApplication application = new SpringApplication(RemoteClientConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); application.setBanner(getBanner()); application.setInitializers(getInitializers()); @@ -80,8 +79,7 @@ public final class RemoteSpringApplication { } private Banner getBanner() { - ClassPathResource banner = new ClassPathResource("remote-banner.txt", - RemoteSpringApplication.class); + ClassPathResource banner = new ClassPathResource("remote-banner.txt", RemoteSpringApplication.class); return new ResourceBanner(banner); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java index 1fe768f4d15..d93ac8e2ce9 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @author Andy Wilkinson */ -class RemoteUrlPropertyExtractor - implements ApplicationListener, Ordered { +class RemoteUrlPropertyExtractor implements ApplicationListener, Ordered { private static final String NON_OPTION_ARGS = CommandLinePropertySource.DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/ConditionEvaluationDeltaLoggingListener.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/ConditionEvaluationDeltaLoggingListener.java index 197b5b21853..cb6b2f96bba 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/ConditionEvaluationDeltaLoggingListener.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/ConditionEvaluationDeltaLoggingListener.java @@ -39,8 +39,7 @@ class ConditionEvaluationDeltaLoggingListener private static final ConcurrentHashMap previousReports = new ConcurrentHashMap<>(); - private static final Log logger = LogFactory - .getLog(ConditionEvaluationDeltaLoggingListener.class); + private static final Log logger = LogFactory.getLog(ConditionEvaluationDeltaLoggingListener.class); private volatile ApplicationContext context; @@ -49,19 +48,15 @@ class ConditionEvaluationDeltaLoggingListener if (!event.getApplicationContext().equals(this.context)) { return; } - ConditionEvaluationReport report = event.getApplicationContext() - .getBean(ConditionEvaluationReport.class); - ConditionEvaluationReport previousReport = previousReports - .get(event.getApplicationContext().getId()); + ConditionEvaluationReport report = event.getApplicationContext().getBean(ConditionEvaluationReport.class); + ConditionEvaluationReport previousReport = previousReports.get(event.getApplicationContext().getId()); if (previousReport != null) { ConditionEvaluationReport delta = report.getDelta(previousReport); - if (!delta.getConditionAndOutcomesBySource().isEmpty() - || !delta.getExclusions().isEmpty() + if (!delta.getConditionAndOutcomesBySource().isEmpty() || !delta.getExclusions().isEmpty() || !delta.getUnconditionalClasses().isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Condition evaluation delta:" - + new ConditionEvaluationReportMessage(delta, - "CONDITION EVALUATION DELTA")); + + new ConditionEvaluationReportMessage(delta, "CONDITION EVALUATION DELTA")); } } else { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java index 97d7280e49e..2d556e9cb59 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java @@ -60,10 +60,9 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; public class DevToolsDataSourceAutoConfiguration { @Bean - NonEmbeddedInMemoryDatabaseShutdownExecutor inMemoryDatabaseShutdownExecutor( - DataSource dataSource, DataSourceProperties dataSourceProperties) { - return new NonEmbeddedInMemoryDatabaseShutdownExecutor(dataSource, - dataSourceProperties); + NonEmbeddedInMemoryDatabaseShutdownExecutor inMemoryDatabaseShutdownExecutor(DataSource dataSource, + DataSourceProperties dataSourceProperties) { + return new NonEmbeddedInMemoryDatabaseShutdownExecutor(dataSource, dataSourceProperties); } /** @@ -74,8 +73,7 @@ public class DevToolsDataSourceAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - static class DatabaseShutdownExecutorJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + static class DatabaseShutdownExecutorJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { DatabaseShutdownExecutorJpaDependencyConfiguration() { super("inMemoryDatabaseShutdownExecutor"); @@ -83,15 +81,13 @@ public class DevToolsDataSourceAutoConfiguration { } - static final class NonEmbeddedInMemoryDatabaseShutdownExecutor - implements DisposableBean { + static final class NonEmbeddedInMemoryDatabaseShutdownExecutor implements DisposableBean { private final DataSource dataSource; private final DataSourceProperties dataSourceProperties; - NonEmbeddedInMemoryDatabaseShutdownExecutor(DataSource dataSource, - DataSourceProperties dataSourceProperties) { + NonEmbeddedInMemoryDatabaseShutdownExecutor(DataSource dataSource, DataSourceProperties dataSourceProperties) { this.dataSource = dataSource; this.dataSourceProperties = dataSourceProperties; } @@ -122,8 +118,7 @@ public class DevToolsDataSourceAutoConfiguration { H2("jdbc:h2:mem:", "org.h2.Driver", "org.h2.jdbcx.JdbcDataSource"), - HSQLDB("jdbc:hsqldb:mem:", "org.hsqldb.jdbcDriver", - "org.hsqldb.jdbc.JDBCDriver", + HSQLDB("jdbc:hsqldb:mem:", "org.hsqldb.jdbcDriver", "org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource"); private final String urlPrefix; @@ -137,18 +132,15 @@ public class DevToolsDataSourceAutoConfiguration { boolean matches(DataSourceProperties properties) { String url = properties.getUrl(); - return (url == null || this.urlPrefix == null - || url.startsWith(this.urlPrefix)) - && this.driverClassNames - .contains(properties.determineDriverClassName()); + return (url == null || this.urlPrefix == null || url.startsWith(this.urlPrefix)) + && this.driverClassNames.contains(properties.determineDriverClassName()); } } } - static class DevToolsDataSourceCondition extends SpringBootCondition - implements ConfigurationCondition { + static class DevToolsDataSourceCondition extends SpringBootCondition implements ConfigurationCondition { @Override public ConfigurationPhase getConfigurationPhase() { @@ -156,35 +148,24 @@ public class DevToolsDataSourceAutoConfiguration { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("DevTools DataSource Condition"); - String[] dataSourceBeanNames = context.getBeanFactory() - .getBeanNamesForType(DataSource.class); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("DevTools DataSource Condition"); + String[] dataSourceBeanNames = context.getBeanFactory().getBeanNamesForType(DataSource.class); if (dataSourceBeanNames.length != 1) { - return ConditionOutcome - .noMatch(message.didNotFind("a single DataSource bean").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("a single DataSource bean").atAll()); } - if (context.getBeanFactory() - .getBeanNamesForType(DataSourceProperties.class).length != 1) { - return ConditionOutcome.noMatch( - message.didNotFind("a single DataSourceProperties bean").atAll()); + if (context.getBeanFactory().getBeanNamesForType(DataSourceProperties.class).length != 1) { + return ConditionOutcome.noMatch(message.didNotFind("a single DataSourceProperties bean").atAll()); } - BeanDefinition dataSourceDefinition = context.getRegistry() - .getBeanDefinition(dataSourceBeanNames[0]); + BeanDefinition dataSourceDefinition = context.getRegistry().getBeanDefinition(dataSourceBeanNames[0]); if (dataSourceDefinition instanceof AnnotatedBeanDefinition - && ((AnnotatedBeanDefinition) dataSourceDefinition) - .getFactoryMethodMetadata() != null - && ((AnnotatedBeanDefinition) dataSourceDefinition) - .getFactoryMethodMetadata().getDeclaringClassName() - .startsWith(DataSourceAutoConfiguration.class.getPackage() - .getName() + ".DataSourceConfiguration$")) { - return ConditionOutcome - .match(message.foundExactly("auto-configured DataSource")); + && ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() != null + && ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() + .getDeclaringClassName().startsWith(DataSourceAutoConfiguration.class.getPackage().getName() + + ".DataSourceConfiguration$")) { + return ConditionOutcome.match(message.foundExactly("auto-configured DataSource")); } - return ConditionOutcome - .noMatch(message.didNotFind("an auto-configured DataSource").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("an auto-configured DataSource").atAll()); } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java index 67a6128f7aa..0cc22d32a86 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -119,8 +119,7 @@ public class DevToolsProperties { allExclude.addAll(StringUtils.commaDelimitedListToSet(this.exclude)); } if (StringUtils.hasText(this.additionalExclude)) { - allExclude.addAll( - StringUtils.commaDelimitedListToSet(this.additionalExclude)); + allExclude.addAll(StringUtils.commaDelimitedListToSet(this.additionalExclude)); } return StringUtils.toStringArray(allExclude); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java index 4436750b1c8..a8f604199da 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ class FileWatchingFailureHandler implements FailureHandler { public Outcome handle(Throwable failure) { CountDownLatch latch = new CountDownLatch(1); FileSystemWatcher watcher = this.fileSystemWatcherFactory.getFileSystemWatcher(); - watcher.addSourceFolders( - new ClassPathFolders(Restarter.getInstance().getInitialUrls())); + watcher.addSourceFolders(new ClassPathFolders(Restarter.getInstance().getInitialUrls())); watcher.addListener(new Listener(latch)); watcher.start(); try { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java index cf79b5abd1e..47ca0cbca44 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java @@ -62,8 +62,7 @@ public class LocalDevToolsAutoConfiguration { * Local LiveReload configuration. */ @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", matchIfMissing = true) static class LiveReloadConfiguration { @Bean @@ -75,14 +74,12 @@ public class LocalDevToolsAutoConfiguration { } @Bean - public OptionalLiveReloadServer optionalLiveReloadServer( - LiveReloadServer liveReloadServer) { + public OptionalLiveReloadServer optionalLiveReloadServer(LiveReloadServer liveReloadServer) { return new OptionalLiveReloadServer(liveReloadServer); } @Bean - public LiveReloadServerEventListener liveReloadServerEventListener( - OptionalLiveReloadServer liveReloadServer) { + public LiveReloadServerEventListener liveReloadServerEventListener(OptionalLiveReloadServer liveReloadServer) { return new LiveReloadServerEventListener(liveReloadServer); } @@ -93,8 +90,7 @@ public class LocalDevToolsAutoConfiguration { */ @Lazy(false) @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "spring.devtools.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.restart", name = "enabled", matchIfMissing = true) static class RestartConfiguration { private final DevToolsProperties properties; @@ -108,20 +104,18 @@ public class LocalDevToolsAutoConfiguration { FileSystemWatcherFactory fileSystemWatcherFactory) { return (event) -> { if (event.isRestartRequired()) { - Restarter.getInstance().restart( - new FileWatchingFailureHandler(fileSystemWatcherFactory)); + Restarter.getInstance().restart(new FileWatchingFailureHandler(fileSystemWatcherFactory)); } }; } @Bean @ConditionalOnMissingBean - public ClassPathFileSystemWatcher classPathFileSystemWatcher( - FileSystemWatcherFactory fileSystemWatcherFactory, + public ClassPathFileSystemWatcher classPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory, ClassPathRestartStrategy classPathRestartStrategy) { URL[] urls = Restarter.getInstance().getInitialUrls(); - ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher( - fileSystemWatcherFactory, classPathRestartStrategy, urls); + ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher(fileSystemWatcherFactory, + classPathRestartStrategy, urls); watcher.setStopWatcherOnRestart(true); return watcher; } @@ -129,8 +123,7 @@ public class LocalDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean public ClassPathRestartStrategy classPathRestartStrategy() { - return new PatternClassPathRestartStrategy( - this.properties.getRestart().getAllExclude()); + return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean @@ -139,16 +132,15 @@ public class LocalDevToolsAutoConfiguration { } @Bean - @ConditionalOnProperty(prefix = "spring.devtools.restart", - name = "log-condition-evaluation-delta", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.restart", name = "log-condition-evaluation-delta", + matchIfMissing = true) public ConditionEvaluationDeltaLoggingListener conditionEvaluationDeltaLoggingListener() { return new ConditionEvaluationDeltaLoggingListener(); } private FileSystemWatcher newFileSystemWatcher() { Restart restartProperties = this.properties.getRestart(); - FileSystemWatcher watcher = new FileSystemWatcher(true, - restartProperties.getPollInterval(), + FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(), restartProperties.getQuietPeriod()); String triggerFile = restartProperties.getTriggerFile(); if (StringUtils.hasLength(triggerFile)) { @@ -188,9 +180,8 @@ public class LocalDevToolsAutoConfiguration { @Override public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ContextRefreshedEvent - || (event instanceof ClassPathChangedEvent - && !((ClassPathChangedEvent) event).isRestartRequired())) { + if (event instanceof ContextRefreshedEvent || (event instanceof ClassPathChangedEvent + && !((ClassPathChangedEvent) event).isRestartRequired())) { this.liveReloadServer.triggerReload(); } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java index 9e6f2dadf87..71295b7e13f 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java @@ -32,14 +32,11 @@ import org.springframework.core.type.AnnotatedTypeMetadata; public class OnEnabledDevToolsCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("Devtools"); - boolean shouldEnable = DevToolsEnablementDeducer - .shouldEnable(Thread.currentThread()); + boolean shouldEnable = DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()); if (!shouldEnable) { - return ConditionOutcome.noMatch( - message.because("devtools is disabled for current context.")); + return ConditionOutcome.noMatch(message.because("devtools is disabled for current context.")); } return ConditionOutcome.match(message.because("devtools enabled.")); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java index 4532b93b747..a6363fe7677 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class OptionalLiveReloadServer implements InitializingBean { if (!this.server.isStarted()) { this.server.start(); } - logger.info( - "LiveReload server is running on port " + this.server.getPort()); + logger.info("LiveReload server is running on port " + this.server.getPort()); } catch (Exception ex) { logger.warn("Unable to start LiveReload server"); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java index a0af3469ed9..82dd9ee56c7 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java @@ -62,8 +62,7 @@ import org.springframework.http.server.ServerHttpRequest; @EnableConfigurationProperties({ ServerProperties.class, DevToolsProperties.class }) public class RemoteDevToolsAutoConfiguration { - private static final Log logger = LogFactory - .getLog(RemoteDevToolsAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(RemoteDevToolsAutoConfiguration.class); private final DevToolsProperties properties; @@ -75,20 +74,15 @@ public class RemoteDevToolsAutoConfiguration { @ConditionalOnMissingBean public AccessManager remoteDevToolsAccessManager() { RemoteDevToolsProperties remoteProperties = this.properties.getRemote(); - return new HttpHeaderAccessManager(remoteProperties.getSecretHeaderName(), - remoteProperties.getSecret()); + return new HttpHeaderAccessManager(remoteProperties.getSecretHeaderName(), remoteProperties.getSecret()); } @Bean - public HandlerMapper remoteDevToolsHealthCheckHandlerMapper( - ServerProperties serverProperties) { + public HandlerMapper remoteDevToolsHealthCheckHandlerMapper(ServerProperties serverProperties) { Handler handler = new HttpStatusHandler(); Servlet servlet = serverProperties.getServlet(); - String servletContextPath = (servlet.getContextPath() != null) - ? servlet.getContextPath() : ""; - return new UrlHandlerMapper( - servletContextPath + this.properties.getRemote().getContextPath(), - handler); + String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : ""; + return new UrlHandlerMapper(servletContextPath + this.properties.getRemote().getContextPath(), handler); } @Bean @@ -103,8 +97,7 @@ public class RemoteDevToolsAutoConfiguration { * Configuration for remote update and restarts. */ @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", matchIfMissing = true) static class RemoteRestartConfiguration { @Bean @@ -115,19 +108,17 @@ public class RemoteDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpRestartServer remoteRestartHttpRestartServer( - SourceFolderUrlFilter sourceFolderUrlFilter) { + public HttpRestartServer remoteRestartHttpRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter) { return new HttpRestartServer(sourceFolderUrlFilter); } @Bean @ConditionalOnMissingBean(name = "remoteRestartHandlerMapper") - public UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server, - ServerProperties serverProperties, DevToolsProperties properties) { + public UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server, ServerProperties serverProperties, + DevToolsProperties properties) { Servlet servlet = serverProperties.getServlet(); RemoteDevToolsProperties remote = properties.getRemote(); - String servletContextPath = (servlet.getContextPath() != null) - ? servlet.getContextPath() : ""; + String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : ""; String url = servletContextPath + remote.getContextPath() + "/restart"; logger.warn("Listening for remote restart updates on " + url); Handler handler = new HttpRestartServerHandler(server); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java index 0c0abb84206..d29cd1ade7a 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class ClassPathChangedEvent extends ApplicationEvent { * @param changeSet the changed files * @param restartRequired if a restart is required due to the change */ - public ClassPathChangedEvent(Object source, Set changeSet, - boolean restartRequired) { + public ClassPathChangedEvent(Object source, Set changeSet, boolean restartRequired) { super(source); Assert.notNull(changeSet, "ChangeSet must not be null"); this.changeSet = changeSet; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java index 184886eae59..4339bcbffe8 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ class ClassPathFileChangeListener implements FileChangeListener { * @param fileSystemWatcherToStop the file system watcher to stop on a restart (or * {@code null}) */ - ClassPathFileChangeListener(ApplicationEventPublisher eventPublisher, - ClassPathRestartStrategy restartStrategy, + ClassPathFileChangeListener(ApplicationEventPublisher eventPublisher, ClassPathRestartStrategy restartStrategy, FileSystemWatcher fileSystemWatcherToStop) { Assert.notNull(eventPublisher, "EventPublisher must not be null"); Assert.notNull(restartStrategy, "RestartStrategy must not be null"); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java index ee68bd31136..bdfba38931e 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ import org.springframework.util.Assert; * @since 1.3.0 * @see ClassPathFileChangeListener */ -public class ClassPathFileSystemWatcher - implements InitializingBean, DisposableBean, ApplicationContextAware { +public class ClassPathFileSystemWatcher implements InitializingBean, DisposableBean, ApplicationContextAware { private final FileSystemWatcher fileSystemWatcher; @@ -55,8 +54,7 @@ public class ClassPathFileSystemWatcher */ public ClassPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory, ClassPathRestartStrategy restartStrategy, URL[] urls) { - Assert.notNull(fileSystemWatcherFactory, - "FileSystemWatcherFactory must not be null"); + Assert.notNull(fileSystemWatcherFactory, "FileSystemWatcherFactory must not be null"); Assert.notNull(urls, "Urls must not be null"); this.fileSystemWatcher = fileSystemWatcherFactory.getFileSystemWatcher(); this.restartStrategy = restartStrategy; @@ -72,8 +70,7 @@ public class ClassPathFileSystemWatcher } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -84,8 +81,8 @@ public class ClassPathFileSystemWatcher if (this.stopWatcherOnRestart) { watcherToStop = this.fileSystemWatcher; } - this.fileSystemWatcher.addListener(new ClassPathFileChangeListener( - this.applicationContext, this.restartStrategy, watcherToStop)); + this.fileSystemWatcher.addListener( + new ClassPathFileChangeListener(this.applicationContext, this.restartStrategy, watcherToStop)); } this.fileSystemWatcher.start(); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java index 0d7a25944a2..aaa324f73a4 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java @@ -42,8 +42,7 @@ public class DevToolsHomePropertiesPostProcessor implements EnvironmentPostProce private static final String FILE_NAME = ".spring-boot-devtools.properties"; @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread())) { File home = getHomeFolder(); File propertyFile = (home != null) ? new File(home, FILE_NAME) : null; @@ -52,8 +51,8 @@ public class DevToolsHomePropertiesPostProcessor implements EnvironmentPostProce Properties properties; try { properties = PropertiesLoaderUtils.loadProperties(resource); - environment.getPropertySources().addFirst( - new PropertiesPropertySource("devtools-local", properties)); + environment.getPropertySources() + .addFirst(new PropertiesPropertySource("devtools-local", properties)); } catch (IOException ex) { throw new IllegalStateException("Unable to load " + FILE_NAME, ex); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java index 9d873565199..58fd893997d 100755 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java @@ -46,8 +46,7 @@ import org.springframework.util.ClassUtils; @Order(Ordered.LOWEST_PRECEDENCE) public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostProcessor { - private static final Log logger = DevToolsLogFactory - .getLog(DevToolsPropertyDefaultsPostProcessor.class); + private static final Log logger = DevToolsLogFactory.getLog(DevToolsPropertyDefaultsPostProcessor.class); private static final String ENABLED = "spring.devtools.add-properties"; @@ -78,20 +77,15 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { - if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) - && isLocalApplication(environment)) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) { if (canAddProperties(environment)) { - logger.info("Devtools property defaults active! Set '" + ENABLED - + "' to 'false' to disable"); - environment.getPropertySources() - .addLast(new MapPropertySource("devtools", PROPERTIES)); + logger.info("Devtools property defaults active! Set '" + ENABLED + "' to 'false' to disable"); + environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES)); } - if (isWebApplication(environment) - && !environment.containsProperty(WEB_LOGGING)) { - logger.info("For additional web related logging consider " - + "setting the '" + WEB_LOGGING + "' property to 'DEBUG'"); + if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) { + logger.info("For additional web related logging consider " + "setting the '" + WEB_LOGGING + + "' property to 'DEBUG'"); } } } @@ -123,8 +117,7 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro private boolean isWebApplication(Environment environment) { for (String candidate : WEB_ENVIRONMENT_CLASSES) { - Class environmentClass = resolveClassName(candidate, - environment.getClass().getClassLoader()); + Class environmentClass = resolveClassName(candidate, environment.getClass().getClassLoader()); if (environmentClass != null && environmentClass.isInstance(environment)) { return true; } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java index c0c1507de40..3abb14bdf9c 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,8 @@ public final class ChangedFile { File file = this.file.getAbsoluteFile(); String folderName = StringUtils.cleanPath(folder.getPath()); String fileName = StringUtils.cleanPath(file.getPath()); - Assert.state(fileName.startsWith(folderName), () -> "The file " + fileName - + " is not contained in the source folder " + folderName); + Assert.state(fileName.startsWith(folderName), + () -> "The file " + fileName + " is not contained in the source folder " + folderName); return fileName.substring(folderName.length() + 1); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java index b95ba5d3909..788d8ce0b7b 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,7 @@ public final class ChangedFiles implements Iterable { } if (obj instanceof ChangedFiles) { ChangedFiles other = (ChangedFiles) obj; - return this.sourceFolder.equals(other.sourceFolder) - && this.files.equals(other.files); + return this.sourceFolder.equals(other.sourceFolder) && this.files.equals(other.files); } return super.equals(obj); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java index 3425dcbc4df..a22fe696eba 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,8 +78,7 @@ public class FileSystemWatcher { * @param quietPeriod the amount of time required after a change has been detected to * ensure that updates have completed */ - public FileSystemWatcher(boolean daemon, Duration pollInterval, - Duration quietPeriod) { + public FileSystemWatcher(boolean daemon, Duration pollInterval, Duration quietPeriod) { Assert.notNull(pollInterval, "PollInterval must not be null"); Assert.notNull(quietPeriod, "QuietPeriod must not be null"); Assert.isTrue(pollInterval.toMillis() > 0, "PollInterval must be positive"); @@ -157,9 +156,8 @@ public class FileSystemWatcher { if (this.watchThread == null) { Map localFolders = new HashMap<>(); localFolders.putAll(this.folders); - this.watchThread = new Thread(new Watcher(this.remainingScans, - new ArrayList<>(this.listeners), this.triggerFilter, - this.pollInterval, this.quietPeriod, localFolders)); + this.watchThread = new Thread(new Watcher(this.remainingScans, new ArrayList<>(this.listeners), + this.triggerFilter, this.pollInterval, this.quietPeriod, localFolders)); this.watchThread.setName("File Watcher"); this.watchThread.setDaemon(this.daemon); this.watchThread.start(); @@ -220,9 +218,8 @@ public class FileSystemWatcher { private Map folders; - private Watcher(AtomicInteger remainingScans, List listeners, - FileFilter triggerFilter, long pollInterval, long quietPeriod, - Map folders) { + private Watcher(AtomicInteger remainingScans, List listeners, FileFilter triggerFilter, + long pollInterval, long quietPeriod, Map folders) { this.remainingScans = remainingScans; this.listeners = listeners; this.triggerFilter = triggerFilter; @@ -263,8 +260,7 @@ public class FileSystemWatcher { } } - private boolean isDifferent(Map previous, - Map current) { + private boolean isDifferent(Map previous, Map current) { if (!previous.keySet().equals(current.keySet())) { return true; } @@ -292,8 +288,7 @@ public class FileSystemWatcher { for (FolderSnapshot snapshot : snapshots) { FolderSnapshot previous = this.folders.get(snapshot.getFolder()); updated.put(snapshot.getFolder(), snapshot); - ChangedFiles changedFiles = previous.getChangedFiles(snapshot, - this.triggerFilter); + ChangedFiles changedFiles = previous.getChangedFiles(snapshot, this.triggerFilter); if (!changedFiles.getFiles().isEmpty()) { changeSet.add(changedFiles); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java index 1e266e671aa..6f75b42d71e 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.util.Assert; */ class FolderSnapshot { - private static final Set DOT_FOLDERS = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(".", ".."))); + private static final Set DOT_FOLDERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(".", ".."))); private final File folder; @@ -74,12 +73,10 @@ class FolderSnapshot { } } - public ChangedFiles getChangedFiles(FolderSnapshot snapshot, - FileFilter triggerFilter) { + public ChangedFiles getChangedFiles(FolderSnapshot snapshot, FileFilter triggerFilter) { Assert.notNull(snapshot, "Snapshot must not be null"); File folder = this.folder; - Assert.isTrue(snapshot.folder.equals(folder), - () -> "Snapshot source folder must be '" + folder + "'"); + Assert.isTrue(snapshot.folder.equals(folder), () -> "Snapshot source folder must be '" + folder + "'"); Set changes = new LinkedHashSet<>(); Map previousFiles = getFilesMap(); for (FileSnapshot currentFile : snapshot.files) { @@ -89,8 +86,7 @@ class FolderSnapshot { changes.add(new ChangedFile(folder, currentFile.getFile(), Type.ADD)); } else if (!previousFile.equals(currentFile)) { - changes.add( - new ChangedFile(folder, currentFile.getFile(), Type.MODIFY)); + changes.add(new ChangedFile(folder, currentFile.getFile(), Type.MODIFY)); } } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java index 64e5bf6b08b..480f4497ace 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ class Connection { private static final Log logger = LogFactory.getLog(Connection.class); - private static final Pattern WEBSOCKET_KEY_PATTERN = Pattern - .compile("^Sec-WebSocket-Key:(.*)$", Pattern.MULTILINE); + private static final Pattern WEBSOCKET_KEY_PATTERN = Pattern.compile("^Sec-WebSocket-Key:(.*)$", Pattern.MULTILINE); public static final String WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; @@ -64,8 +63,7 @@ class Connection { * @param outputStream the socket output stream * @throws IOException in case of I/O errors */ - Connection(Socket socket, InputStream inputStream, OutputStream outputStream) - throws IOException { + Connection(Socket socket, InputStream inputStream, OutputStream outputStream) throws IOException { this.socket = socket; this.inputStream = new ConnectionInputStream(inputStream); this.outputStream = new ConnectionOutputStream(outputStream); @@ -78,23 +76,19 @@ class Connection { * @throws Exception in case of errors */ public void run() throws Exception { - if (this.header.contains("Upgrade: websocket") - && this.header.contains("Sec-WebSocket-Version: 13")) { + if (this.header.contains("Upgrade: websocket") && this.header.contains("Sec-WebSocket-Version: 13")) { runWebSocket(); } if (this.header.contains("GET /livereload.js")) { - this.outputStream.writeHttp(getClass().getResourceAsStream("livereload.js"), - "text/javascript"); + this.outputStream.writeHttp(getClass().getResourceAsStream("livereload.js"), "text/javascript"); } } private void runWebSocket() throws Exception { String accept = getWebsocketAcceptResponse(); - this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", "Connection: Upgrade", + this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: " + accept); - new Frame("{\"command\":\"hello\",\"protocols\":" - + "[\"http://livereload.com/protocols/official-7\"]," + new Frame("{\"command\":\"hello\",\"protocols\":" + "[\"http://livereload.com/protocols/official-7\"]," + "\"serverName\":\"spring-boot\"}").write(this.outputStream); Thread.sleep(100); this.webSocket = true; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java index 850b4917de3..f0c657a0321 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ class ConnectionOutputStream extends FilterOutputStream { public void writeHttp(InputStream content, String contentType) throws IOException { byte[] bytes = FileCopyUtils.copyToByteArray(content); - writeHeaders("HTTP/1.1 200 OK", "Content-Type: " + contentType, - "Content-Length: " + bytes.length, "Connection: close"); + writeHeaders("HTTP/1.1 200 OK", "Content-Type: " + contentType, "Content-Length: " + bytes.length, + "Connection: close"); write(bytes); flush(); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java index 9b65417708f..643a9f51843 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ public class LiveReloadServer { private static final int READ_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(4); - private final ExecutorService executor = Executors - .newCachedThreadPool(new WorkerThreadFactory()); + private final ExecutorService executor = Executors.newCachedThreadPool(new WorkerThreadFactory()); private final List connections = new ArrayList<>(); @@ -232,8 +231,8 @@ public class LiveReloadServer { * @return a connection * @throws IOException in case of I/O errors */ - protected Connection createConnection(Socket socket, InputStream inputStream, - OutputStream outputStream) throws IOException { + protected Connection createConnection(Socket socket, InputStream inputStream, OutputStream outputStream) + throws IOException { return new Connection(socket, inputStream, outputStream); } @@ -271,8 +270,7 @@ public class LiveReloadServer { private void handle() throws Exception { try { try (OutputStream outputStream = this.socket.getOutputStream()) { - Connection connection = createConnection(this.socket, - this.inputStream, outputStream); + Connection connection = createConnection(this.socket, this.inputStream, outputStream); runConnection(connection); } finally { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java index 38b653e2508..fd2d8c27d59 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java @@ -55,14 +55,12 @@ import org.springframework.util.FileCopyUtils; * @author Andy Wilkinson * @since 1.3.0 */ -public class ClassPathChangeUploader - implements ApplicationListener { +public class ClassPathChangeUploader implements ApplicationListener { private static final Map TYPE_MAPPINGS; static { - Map map = new EnumMap<>( - ChangedFile.Type.class); + Map map = new EnumMap<>(ChangedFile.Type.class); map.put(ChangedFile.Type.ADD, ClassLoaderFile.Kind.ADDED); map.put(ChangedFile.Type.DELETE, ClassLoaderFile.Kind.DELETED); map.put(ChangedFile.Type.MODIFY, ClassLoaderFile.Kind.MODIFIED); @@ -99,21 +97,19 @@ public class ClassPathChangeUploader } } - private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) - throws IOException { + private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) throws IOException { try { while (true) { try { - ClientHttpRequest request = this.requestFactory - .createRequest(this.uri, HttpMethod.POST); + ClientHttpRequest request = this.requestFactory.createRequest(this.uri, HttpMethod.POST); HttpHeaders headers = request.getHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentLength(bytes.length); FileCopyUtils.copy(bytes, request.getBody()); ClientHttpResponse response = request.execute(); HttpStatus statusCode = response.getStatusCode(); - Assert.state(statusCode == HttpStatus.OK, () -> "Unexpected " - + statusCode + " response uploading class files"); + Assert.state(statusCode == HttpStatus.OK, + () -> "Unexpected " + statusCode + " response uploading class files"); logUpload(classLoaderFiles); return; } @@ -133,8 +129,7 @@ public class ClassPathChangeUploader private void logUpload(ClassLoaderFiles classLoaderFiles) { int size = classLoaderFiles.size(); - logger.info("Uploaded " + size + " class " - + ((size != 1) ? "resources" : "resource")); + logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource")); } private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException { @@ -145,26 +140,21 @@ public class ClassPathChangeUploader return outputStream.toByteArray(); } - private ClassLoaderFiles getClassLoaderFiles(ClassPathChangedEvent event) - throws IOException { + private ClassLoaderFiles getClassLoaderFiles(ClassPathChangedEvent event) throws IOException { ClassLoaderFiles files = new ClassLoaderFiles(); for (ChangedFiles changedFiles : event.getChangeSet()) { String sourceFolder = changedFiles.getSourceFolder().getAbsolutePath(); for (ChangedFile changedFile : changedFiles) { - files.addFile(sourceFolder, changedFile.getRelativeName(), - asClassLoaderFile(changedFile)); + files.addFile(sourceFolder, changedFile.getRelativeName(), asClassLoaderFile(changedFile)); } } return files; } - private ClassLoaderFile asClassLoaderFile(ChangedFile changedFile) - throws IOException { + private ClassLoaderFile asClassLoaderFile(ChangedFile changedFile) throws IOException { ClassLoaderFile.Kind kind = TYPE_MAPPINGS.get(changedFile.getType()); - byte[] bytes = (kind != Kind.DELETED) - ? FileCopyUtils.copyToByteArray(changedFile.getFile()) : null; - long lastModified = (kind != Kind.DELETED) ? changedFile.getFile().lastModified() - : System.currentTimeMillis(); + byte[] bytes = (kind != Kind.DELETED) ? FileCopyUtils.copyToByteArray(changedFile.getFile()) : null; + long lastModified = (kind != Kind.DELETED) ? changedFile.getFile().lastModified() : System.currentTimeMillis(); return new ClassLoaderFile(kind, lastModified, bytes); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java index de93d818618..231f0bb6074 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ class DelayedLiveReloadTrigger implements Runnable { private long timeout = TIMEOUT; - DelayedLiveReloadTrigger(OptionalLiveReloadServer liveReloadServer, - ClientHttpRequestFactory requestFactory, String url) { + DelayedLiveReloadTrigger(OptionalLiveReloadServer liveReloadServer, ClientHttpRequestFactory requestFactory, + String url) { Assert.notNull(liveReloadServer, "LiveReloadServer must not be null"); Assert.notNull(requestFactory, "RequestFactory must not be null"); Assert.hasLength(url, "URL must not be empty"); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java index 900a36e4ed1..a2e6bef311e 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,8 @@ public class HttpHeaderInterceptor implements ClientHttpRequestInterceptor { } @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { request.getHeaders().add(this.name, this.value); return execution.execute(request, body); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java index 775ec2f7e2c..131b00714a4 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java @@ -89,13 +89,12 @@ public class RemoteClientConfiguration implements InitializingBean { @Bean public ClientHttpRequestFactory clientHttpRequestFactory() { - List interceptors = Arrays - .asList(getSecurityInterceptor()); + List interceptors = Arrays.asList(getSecurityInterceptor()); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); Proxy proxy = this.properties.getRemote().getProxy(); if (proxy.getHost() != null && proxy.getPort() != null) { - requestFactory.setProxy(new java.net.Proxy(Type.HTTP, - new InetSocketAddress(proxy.getHost(), proxy.getPort()))); + requestFactory + .setProxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); } return new InterceptingClientHttpRequestFactory(requestFactory, interceptors); } @@ -105,8 +104,7 @@ public class RemoteClientConfiguration implements InitializingBean { String secretHeaderName = remoteProperties.getSecretHeaderName(); String secret = remoteProperties.getSecret(); Assert.state(secret != null, - "The environment value 'spring.devtools.remote.secret' " - + "is required to secure your connection."); + "The environment value 'spring.devtools.remote.secret' " + "is required to secure your connection."); return new HttpHeaderInterceptor(secretHeaderName, secret); } @@ -130,8 +128,7 @@ public class RemoteClientConfiguration implements InitializingBean { * LiveReload configuration. */ @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", matchIfMissing = true) static class LiveReloadConfiguration { @Autowired @@ -160,10 +157,9 @@ public class RemoteClientConfiguration implements InitializingBean { public ApplicationListener liveReloadTriggeringClassPathChangedEventListener( OptionalLiveReloadServer optionalLiveReloadServer) { return (event) -> { - String url = this.remoteUrl - + this.properties.getRemote().getContextPath(); - this.executor.execute(new DelayedLiveReloadTrigger( - optionalLiveReloadServer, this.clientHttpRequestFactory, url)); + String url = this.remoteUrl + this.properties.getRemote().getContextPath(); + this.executor.execute( + new DelayedLiveReloadTrigger(optionalLiveReloadServer, this.clientHttpRequestFactory, url)); }; } @@ -182,8 +178,7 @@ public class RemoteClientConfiguration implements InitializingBean { * Client configuration for remote update and restarts. */ @Configuration(proxyBeanMethods = false) - @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", matchIfMissing = true) static class RemoteRestartClientConfiguration { @Autowired @@ -193,16 +188,14 @@ public class RemoteClientConfiguration implements InitializingBean { private String remoteUrl; @Bean - public ClassPathFileSystemWatcher classPathFileSystemWatcher( - FileSystemWatcherFactory fileSystemWatcherFactory, + public ClassPathFileSystemWatcher classPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory, ClassPathRestartStrategy classPathRestartStrategy) { DefaultRestartInitializer restartInitializer = new DefaultRestartInitializer(); URL[] urls = restartInitializer.getInitialUrls(Thread.currentThread()); if (urls == null) { urls = new URL[0]; } - return new ClassPathFileSystemWatcher(fileSystemWatcherFactory, - classPathRestartStrategy, urls); + return new ClassPathFileSystemWatcher(fileSystemWatcherFactory, classPathRestartStrategy, urls); } @Bean @@ -212,8 +205,7 @@ public class RemoteClientConfiguration implements InitializingBean { private FileSystemWatcher newFileSystemWatcher() { Restart restartProperties = this.properties.getRestart(); - FileSystemWatcher watcher = new FileSystemWatcher(true, - restartProperties.getPollInterval(), + FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(), restartProperties.getQuietPeriod()); String triggerFile = restartProperties.getTriggerFile(); if (StringUtils.hasLength(triggerFile)) { @@ -224,15 +216,12 @@ public class RemoteClientConfiguration implements InitializingBean { @Bean public ClassPathRestartStrategy classPathRestartStrategy() { - return new PatternClassPathRestartStrategy( - this.properties.getRestart().getAllExclude()); + return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean - public ClassPathChangeUploader classPathChangeUploader( - ClientHttpRequestFactory requestFactory) { - String url = this.remoteUrl + this.properties.getRemote().getContextPath() - + "/restart"; + public ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory) { + String url = this.remoteUrl + this.properties.getRemote().getContextPath() + "/restart"; return new ClassPathChangeUploader(url, requestFactory); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java index a7f5298cabf..c3ce45de52c 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,7 @@ public class Dispatcher { * @return {@code true} if the request was dispatched * @throws IOException in case of I/O errors */ - public boolean handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public boolean handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { for (HandlerMapper mapper : this.mappers) { Handler handler = mapper.getHandler(request); if (handler != null) { @@ -69,8 +68,7 @@ public class Dispatcher { return false; } - private void handle(Handler handler, ServerHttpRequest request, - ServerHttpResponse response) throws IOException { + private void handle(Handler handler, ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (!this.accessManager.isAllowed(request)) { response.setStatusCode(HttpStatus.FORBIDDEN); return; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java index d4245581ff4..62ccf763071 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,10 +54,9 @@ public class DispatcherFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - if (request instanceof HttpServletRequest - && response instanceof HttpServletResponse) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } else { @@ -65,8 +64,8 @@ public class DispatcherFilter implements Filter { } } - private void doFilter(HttpServletRequest request, HttpServletResponse response, - FilterChain chain) throws IOException, ServletException { + private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { ServerHttpRequest serverRequest = new ServletServerHttpRequest(request); ServerHttpResponse serverResponse = new ServletServerHttpResponse(response); if (!this.dispatcher.handle(serverRequest, serverResponse)) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java index 46255745f84..cc87c9b6839 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,6 @@ public interface Handler { * @param response the response * @throws IOException in case of I/O errors */ - void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException; + void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException; } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java index 5a9f1b5966a..42d1ef88fd8 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ public class HttpStatusHandler implements Handler { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { response.setStatusCode(this.status); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java index 10b1ed96cd8..fc6fa8cc88f 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java @@ -54,8 +54,7 @@ final class ChangeableUrls implements Iterable { DevToolsSettings settings = DevToolsSettings.get(); List reloadableUrls = new ArrayList<>(urls.length); for (URL url : urls) { - if ((settings.isRestartInclude(url) || isFolderUrl(url.toString())) - && !settings.isRestartExclude(url)) { + if ((settings.isRestartInclude(url) || isFolderUrl(url.toString())) && !settings.isRestartExclude(url)) { reloadableUrls.add(url); } } @@ -104,9 +103,7 @@ final class ChangeableUrls implements Iterable { if (classLoader instanceof URLClassLoader) { return ((URLClassLoader) classLoader).getURLs(); } - return Stream - .of(ManagementFactory.getRuntimeMXBean().getClassPath() - .split(File.pathSeparator)) + return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) .map(ChangeableUrls::toURL).toArray(URL[]::new); } @@ -115,8 +112,7 @@ final class ChangeableUrls implements Iterable { return new File(classPathEntry).toURI().toURL(); } catch (MalformedURLException ex) { - throw new IllegalArgumentException( - "URL could not be created from '" + classPathEntry + "'", ex); + throw new IllegalArgumentException("URL could not be created from '" + classPathEntry + "'", ex); } } @@ -129,9 +125,7 @@ final class ChangeableUrls implements Iterable { return getUrlsFromManifestClassPathAttribute(url, jarFile); } catch (IOException ex) { - throw new IllegalStateException( - "Failed to read Class-Path attribute from manifest of jar " + url, - ex); + throw new IllegalStateException("Failed to read Class-Path attribute from manifest of jar " + url, ex); } } @@ -148,14 +142,12 @@ final class ChangeableUrls implements Iterable { return null; } - private static List getUrlsFromManifestClassPathAttribute(URL jarUrl, - JarFile jarFile) throws IOException { + private static List getUrlsFromManifestClassPathAttribute(URL jarUrl, JarFile jarFile) throws IOException { Manifest manifest = jarFile.getManifest(); if (manifest == null) { return Collections.emptyList(); } - String classPath = manifest.getMainAttributes() - .getValue(Attributes.Name.CLASS_PATH); + String classPath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (!StringUtils.hasText(classPath)) { return Collections.emptyList(); } @@ -173,8 +165,7 @@ final class ChangeableUrls implements Iterable { } } catch (MalformedURLException ex) { - throw new IllegalStateException( - "Class-Path attribute contains malformed URL", ex); + throw new IllegalStateException("Class-Path attribute contains malformed URL", ex); } } if (!nonExistentEntries.isEmpty()) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java index 5c44357a8a5..d915ac01ebc 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,11 +57,9 @@ import org.springframework.web.context.support.ServletContextResourcePatternReso */ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternResolver { - private static final String[] LOCATION_PATTERN_PREFIXES = { CLASSPATH_ALL_URL_PREFIX, - CLASSPATH_URL_PREFIX }; + private static final String[] LOCATION_PATTERN_PREFIXES = { CLASSPATH_ALL_URL_PREFIX, CLASSPATH_URL_PREFIX }; - private static final String WEB_CONTEXT_CLASS = "org.springframework.web.context." - + "WebApplicationContext"; + private static final String WEB_CONTEXT_CLASS = "org.springframework.web.context." + "WebApplicationContext"; private final ResourcePatternResolver patternResolverDelegate; @@ -69,17 +67,14 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe private final ClassLoaderFiles classLoaderFiles; - ClassLoaderFilesResourcePatternResolver(ApplicationContext applicationContext, - ClassLoaderFiles classLoaderFiles) { + ClassLoaderFilesResourcePatternResolver(ApplicationContext applicationContext, ClassLoaderFiles classLoaderFiles) { this.classLoaderFiles = classLoaderFiles; this.patternResolverDelegate = getResourcePatternResolverFactory() - .getResourcePatternResolver(applicationContext, - retrieveResourceLoader(applicationContext)); + .getResourcePatternResolver(applicationContext, retrieveResourceLoader(applicationContext)); } private ResourceLoader retrieveResourceLoader(ApplicationContext applicationContext) { - Field field = ReflectionUtils.findField(applicationContext.getClass(), - "resourceLoader", ResourceLoader.class); + Field field = ReflectionUtils.findField(applicationContext.getClass(), "resourceLoader", ResourceLoader.class); if (field == null) { return null; } @@ -111,8 +106,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe @Override public Resource[] getResources(String locationPattern) throws IOException { List resources = new ArrayList<>(); - Resource[] candidates = this.patternResolverDelegate - .getResources(locationPattern); + Resource[] candidates = this.patternResolverDelegate.getResources(locationPattern); for (Resource candidate : candidates) { if (!isDeleted(candidate)) { resources.add(candidate); @@ -122,18 +116,15 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe return resources.toArray(new Resource[0]); } - private List getAdditionalResources(String locationPattern) - throws MalformedURLException { + private List getAdditionalResources(String locationPattern) throws MalformedURLException { List additionalResources = new ArrayList<>(); String trimmedLocationPattern = trimLocationPattern(locationPattern); for (SourceFolder sourceFolder : this.classLoaderFiles.getSourceFolders()) { for (Entry entry : sourceFolder.getFilesEntrySet()) { String name = entry.getKey(); ClassLoaderFile file = entry.getValue(); - if (file.getKind() != Kind.DELETED - && this.antPathMatcher.match(trimmedLocationPattern, name)) { - URL url = new URL("reloaded", null, -1, "/" + name, - new ClassLoaderFileURLStreamHandler(file)); + if (file.getKind() != Kind.DELETED && this.antPathMatcher.match(trimmedLocationPattern, name)) { + URL url = new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); UrlResource resource = new UrlResource(url); additionalResources.add(resource); } @@ -163,8 +154,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe } } catch (IOException ex) { - throw new IllegalStateException( - "Failed to retrieve URI from '" + resource + "'", ex); + throw new IllegalStateException("Failed to retrieve URI from '" + resource + "'", ex); } } } @@ -205,8 +195,8 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe */ private static class ResourcePatternResolverFactory { - public ResourcePatternResolver getResourcePatternResolver( - ApplicationContext applicationContext, ResourceLoader resourceLoader) { + public ResourcePatternResolver getResourcePatternResolver(ApplicationContext applicationContext, + ResourceLoader resourceLoader) { if (resourceLoader == null) { resourceLoader = new DefaultResourceLoader(); copyProtocolResolvers(applicationContext, resourceLoader); @@ -223,8 +213,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe } } - protected final void copyProtocolResolvers(DefaultResourceLoader source, - DefaultResourceLoader destination) { + protected final void copyProtocolResolvers(DefaultResourceLoader source, DefaultResourceLoader destination) { for (ProtocolResolver resolver : source.getProtocolResolvers()) { destination.addProtocolResolver(resolver); } @@ -236,24 +225,21 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe * {@link ResourcePatternResolverFactory} to be used when the classloader can access * {@link WebApplicationContext}. */ - private static class WebResourcePatternResolverFactory - extends ResourcePatternResolverFactory { + private static class WebResourcePatternResolverFactory extends ResourcePatternResolverFactory { @Override - public ResourcePatternResolver getResourcePatternResolver( - ApplicationContext applicationContext, ResourceLoader resourceLoader) { + public ResourcePatternResolver getResourcePatternResolver(ApplicationContext applicationContext, + ResourceLoader resourceLoader) { if (applicationContext instanceof WebApplicationContext) { - return getResourcePatternResolver( - (WebApplicationContext) applicationContext, resourceLoader); + return getResourcePatternResolver((WebApplicationContext) applicationContext, resourceLoader); } return super.getResourcePatternResolver(applicationContext, resourceLoader); } - private ResourcePatternResolver getResourcePatternResolver( - WebApplicationContext applicationContext, ResourceLoader resourceLoader) { + private ResourcePatternResolver getResourcePatternResolver(WebApplicationContext applicationContext, + ResourceLoader resourceLoader) { if (resourceLoader == null) { - resourceLoader = new WebApplicationContextResourceLoader( - applicationContext); + resourceLoader = new WebApplicationContextResourceLoader(applicationContext); copyProtocolResolvers(applicationContext, resourceLoader); } return new ServletContextResourcePatternResolver(resourceLoader); @@ -266,8 +252,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe * {@link ResourceLoader} that optionally supports {@link ServletContextResource * ServletContextResources}. */ - private static class WebApplicationContextResourceLoader - extends DefaultResourceLoader { + private static class WebApplicationContextResourceLoader extends DefaultResourceLoader { private final WebApplicationContext applicationContext; @@ -278,8 +263,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe @Override protected Resource getResourceByPath(String path) { if (this.applicationContext.getServletContext() != null) { - return new ServletContextResource( - this.applicationContext.getServletContext(), path); + return new ServletContextResource(this.applicationContext.getServletContext(), path); } return super.getResourceByPath(path); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java index 4dad42f4807..1e27b7322d3 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java @@ -49,8 +49,8 @@ public class DefaultRestartInitializer implements RestartInitializer { * @return {@code true} if the thread is a main invocation */ protected boolean isMain(Thread thread) { - return thread.getName().equals("main") && thread.getContextClassLoader() - .getClass().getName().contains("AppClassLoader"); + return thread.getName().equals("main") + && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); } /** diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java index e84b22556ac..d6622076017 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,10 +32,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnInitializedRestarterCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Initialized Restarter Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Initialized Restarter Condition"); Restarter restarter = getRestarter(); if (restarter == null) { return ConditionOutcome.noMatch(message.because("unavailable")); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java index cd49ce40108..c4c4e15379b 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ import org.springframework.core.Ordered; * @since 1.3.0 * @see Restarter */ -public class RestartApplicationListener - implements ApplicationListener, Ordered { +public class RestartApplicationListener implements ApplicationListener, Ordered { private static final String ENABLED_PROPERTY = "spring.devtools.restart.enabled"; @@ -52,8 +51,7 @@ public class RestartApplicationListener if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } - if (event instanceof ApplicationReadyEvent - || event instanceof ApplicationFailedEvent) { + if (event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent) { Restarter.getInstance().finish(); } if (event instanceof ApplicationFailedEvent) { @@ -70,14 +68,12 @@ public class RestartApplicationListener DefaultRestartInitializer initializer = new DefaultRestartInitializer(); boolean restartOnInitialize = !AgentReloader.isActive(); if (!restartOnInitialize) { - logger.info( - "Restart disabled due to an agent-based reloader being active"); + logger.info("Restart disabled due to an agent-based reloader being active"); } Restarter.initialize(args, false, initializer, restartOnInitialize); } else { - logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY - + "' being set to false"); + logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY + "' being set to false"); Restarter.disable(); } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java index 3dd9345c296..3ea95cabb83 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import org.springframework.context.ConfigurableApplicationContext; * @author Phillip Webb * @since 1.3.0 */ -public class RestartScopeInitializer - implements ApplicationContextInitializer { +public class RestartScopeInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java index 0f552f6773c..0d430eefb82 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,8 +129,7 @@ public class Restarter { * @param initializer the restart initializer * @see #initialize(String[]) */ - protected Restarter(Thread thread, String[] args, boolean forceReferenceCleanup, - RestartInitializer initializer) { + protected Restarter(Thread thread, String[] args, boolean forceReferenceCleanup, RestartInitializer initializer) { Assert.notNull(thread, "Thread must not be null"); Assert.notNull(args, "Args must not be null"); Assert.notNull(initializer, "Initializer must not be null"); @@ -277,11 +276,9 @@ public class Restarter { Assert.notNull(this.mainClassName, "Unable to find the main class to restart"); URL[] urls = this.urls.toArray(new URL[0]); ClassLoaderFiles updatedFiles = new ClassLoaderFiles(this.classLoaderFiles); - ClassLoader classLoader = new RestartClassLoader(this.applicationClassLoader, - urls, updatedFiles, this.logger); + ClassLoader classLoader = new RestartClassLoader(this.applicationClassLoader, urls, updatedFiles, this.logger); if (this.logger.isDebugEnabled()) { - this.logger.debug("Starting application " + this.mainClassName + " with URLs " - + Arrays.asList(urls)); + this.logger.debug("Starting application " + this.mainClassName + " with URLs " + Arrays.asList(urls)); } return relaunch(classLoader); } @@ -293,8 +290,8 @@ public class Restarter { * @throws Exception in case of errors */ protected Throwable relaunch(ClassLoader classLoader) throws Exception { - RestartLauncher launcher = new RestartLauncher(classLoader, this.mainClassName, - this.args, this.exceptionHandler); + RestartLauncher launcher = new RestartLauncher(classLoader, this.mainClassName, this.args, + this.exceptionHandler); launcher.start(); launcher.join(); return launcher.getError(); @@ -363,8 +360,7 @@ public class Restarter { } catch (Exception ex) { if (this.logger.isDebugEnabled()) { - this.logger.debug("Unable to clear field " + className + " " + fieldName, - ex); + this.logger.debug("Unable to clear field " + className + " " + fieldName, ex); } } } @@ -389,8 +385,7 @@ public class Restarter { } private boolean isFromRestartClassLoader(Object object) { - return (object instanceof Class - && ((Class) object).getClassLoader() instanceof RestartClassLoader); + return (object instanceof Class && ((Class) object).getClassLoader() instanceof RestartClassLoader); } /** @@ -415,8 +410,7 @@ public class Restarter { void finish() { synchronized (this.monitor) { if (!isFinished()) { - this.logger = DeferredLog.replay(this.logger, - LogFactory.getLog(getClass())); + this.logger = DeferredLog.replay(this.logger, LogFactory.getLog(getClass())); this.finished = true; } } @@ -445,8 +439,8 @@ public class Restarter { } private void prepare(GenericApplicationContext applicationContext) { - ResourceLoader resourceLoader = new ClassLoaderFilesResourcePatternResolver( - applicationContext, this.classLoaderFiles); + ResourceLoader resourceLoader = new ClassLoaderFilesResourcePatternResolver(applicationContext, + this.classLoaderFiles); applicationContext.setResourceLoader(resourceLoader); } @@ -531,8 +525,7 @@ public class Restarter { * @param initializer the restart initializer * @see #initialize(String[], boolean, RestartInitializer) */ - public static void initialize(String[] args, boolean forceReferenceCleanup, - RestartInitializer initializer) { + public static void initialize(String[] args, boolean forceReferenceCleanup, RestartInitializer initializer) { initialize(args, forceReferenceCleanup, initializer, true); } @@ -548,13 +541,12 @@ public class Restarter { * @param restartOnInitialize if the restarter should be restarted immediately when * the {@link RestartInitializer} returns non {@code null} results */ - public static void initialize(String[] args, boolean forceReferenceCleanup, - RestartInitializer initializer, boolean restartOnInitialize) { + public static void initialize(String[] args, boolean forceReferenceCleanup, RestartInitializer initializer, + boolean restartOnInitialize) { Restarter localInstance = null; synchronized (INSTANCE_MONITOR) { if (instance == null) { - localInstance = new Restarter(Thread.currentThread(), args, - forceReferenceCleanup, initializer); + localInstance = new Restarter(Thread.currentThread(), args, forceReferenceCleanup, initializer); instance = localInstance; } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFile.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFile.java index fb65e7ab0da..d39c569e5eb 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFile.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ public class ClassLoaderFile implements Serializable { public ClassLoaderFile(Kind kind, long lastModified, byte[] contents) { Assert.notNull(kind, "Kind must not be null"); Assert.isTrue((kind != Kind.DELETED) ? contents != null : contents == null, - () -> "Contents must " + ((kind != Kind.DELETED) ? "not " : "") - + "be null"); + () -> "Contents must " + ((kind != Kind.DELETED) ? "not " : "") + "be null"); this.kind = kind; this.lastModified = lastModified; this.contents = contents; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java index c1645f047c1..e9f11078faf 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class ClassLoaderFileURLStreamHandler extends URLStreamHandler { @Override public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream( - ClassLoaderFileURLStreamHandler.this.file.getContents()); + return new ByteArrayInputStream(ClassLoaderFileURLStreamHandler.this.file.getContents()); } @Override diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java index 42fdf2aa5d1..e4bcf06041f 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad * URLs were created. * @param urls the urls managed by the classloader */ - public RestartClassLoader(ClassLoader parent, URL[] urls, - ClassLoaderFileRepository updatedFiles) { + public RestartClassLoader(ClassLoader parent, URL[] urls, ClassLoaderFileRepository updatedFiles) { this(parent, urls, updatedFiles, LogFactory.getLog(RestartClassLoader.class)); } @@ -74,8 +73,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad * @param urls the urls managed by the classloader * @param logger the logger used for messages */ - public RestartClassLoader(ClassLoader parent, URL[] urls, - ClassLoaderFileRepository updatedFiles, Log logger) { + public RestartClassLoader(ClassLoader parent, URL[] urls, ClassLoaderFileRepository updatedFiles, Log logger) { super(urls, parent); Assert.notNull(parent, "Parent must not be null"); Assert.notNull(updatedFiles, "UpdatedFiles must not be null"); @@ -126,13 +124,11 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad if (file.getKind() == Kind.DELETED) { return null; } - return AccessController - .doPrivileged((PrivilegedAction) () -> createFileUrl(name, file)); + return AccessController.doPrivileged((PrivilegedAction) () -> createFileUrl(name, file)); } @Override - public Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); ClassLoaderFile file = this.updatedFiles.getFile(path); if (file != null && file.getKind() == Kind.DELETED) { @@ -173,8 +169,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad private URL createFileUrl(String name, ClassLoaderFile file) { try { - return new URL("reloaded", null, -1, "/" + name, - new ClassLoaderFileURLStreamHandler(file)); + return new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); } catch (MalformedURLException ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java index b900c8d2ddd..55082bf78db 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,12 +38,10 @@ public class DefaultSourceFolderUrlFilter implements SourceFolderUrlFilter { private static final Pattern URL_MODULE_PATTERN = Pattern.compile(".*\\/(.+)\\.jar"); - private static final Pattern VERSION_PATTERN = Pattern - .compile("^-\\d+(?:\\.\\d+)*(?:[.-].+)?$"); + private static final Pattern VERSION_PATTERN = Pattern.compile("^-\\d+(?:\\.\\d+)*(?:[.-].+)?$"); - private static final Set SKIPPED_PROJECTS = new HashSet<>(Arrays.asList( - "spring-boot", "spring-boot-devtools", "spring-boot-autoconfigure", - "spring-boot-actuator", "spring-boot-starter")); + private static final Set SKIPPED_PROJECTS = new HashSet<>(Arrays.asList("spring-boot", + "spring-boot-devtools", "spring-boot-autoconfigure", "spring-boot-actuator", "spring-boot-starter")); @Override public boolean isMatch(String sourceFolder, URL url) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java index 9ecb5b1b517..cc560d9f143 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,12 +67,10 @@ public class HttpRestartServer { * @param response the response * @throws IOException in case of I/O errors */ - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { try { Assert.state(request.getHeaders().getContentLength() > 0, "No content"); - ObjectInputStream objectInputStream = new ObjectInputStream( - request.getBody()); + ObjectInputStream objectInputStream = new ObjectInputStream(request.getBody()); ClassLoaderFiles files = (ClassLoaderFiles) objectInputStream.readObject(); objectInputStream.close(); this.server.updateAndRestart(files); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java index bdb2058e947..66100c1f3df 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class HttpRestartServerHandler implements Handler { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { this.server.handle(request, response); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java index d9ad8f3f34f..6d05f985422 100755 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,8 +67,7 @@ public class RestartServer { * local classpath * @param classLoader the application classloader */ - public RestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, - ClassLoader classLoader) { + public RestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, ClassLoader classLoader) { Assert.notNull(sourceFolderUrlFilter, "SourceFolderUrlFilter must not be null"); Assert.notNull(classLoader, "ClassLoader must not be null"); this.sourceFolderUrlFilter = sourceFolderUrlFilter; @@ -97,8 +96,7 @@ public class RestartServer { restart(urls, files); } - private boolean updateFileSystem(URL url, String name, - ClassLoaderFile classLoaderFile) { + private boolean updateFileSystem(URL url, String name, ClassLoaderFile classLoaderFile) { if (!isFolderUrl(url.toString())) { return false; } @@ -128,8 +126,7 @@ public class RestartServer { for (URL url : urls) { if (this.sourceFolderUrlFilter.isMatch(sourceFolder, url)) { if (logger.isDebugEnabled()) { - logger.debug("URL " + url + " matched against source folder " - + sourceFolder); + logger.debug("URL " + url + " matched against source folder " + sourceFolder); } matchingUrls.add(url); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java index 7d389309056..ed7f6336c63 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,23 +104,19 @@ public class DevToolsSettings { static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); - Enumeration urls = Thread.currentThread().getContextClassLoader() - .getResources(location); + Enumeration urls = Thread.currentThread().getContextClassLoader().getResources(location); while (urls.hasMoreElements()) { - settings.add(PropertiesLoaderUtils - .loadProperties(new UrlResource(urls.nextElement()))); + settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { - logger.debug("Included patterns for restart : " - + settings.restartIncludePatterns); - logger.debug("Excluded patterns for restart : " - + settings.restartExcludePatterns); + logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); + logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { - throw new IllegalStateException("Unable to load devtools settings from " - + "location [" + location + "]", ex); + throw new IllegalStateException("Unable to load devtools settings from " + "location [" + location + "]", + ex); } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java index 549aca96e90..d17c06860ac 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,7 @@ public class HttpTunnelConnection implements TunnelConnection { * @param requestFactory the HTTP request factory * @param executor the executor used to handle connections */ - protected HttpTunnelConnection(String url, ClientHttpRequestFactory requestFactory, - Executor executor) { + protected HttpTunnelConnection(String url, ClientHttpRequestFactory requestFactory, Executor executor) { Assert.hasLength(url, "URL must not be empty"); Assert.notNull(requestFactory, "RequestFactory must not be null"); try { @@ -88,19 +87,16 @@ public class HttpTunnelConnection implements TunnelConnection { throw new IllegalArgumentException("Malformed URL '" + url + "'"); } this.requestFactory = requestFactory; - this.executor = (executor != null) ? executor - : Executors.newCachedThreadPool(new TunnelThreadFactory()); + this.executor = (executor != null) ? executor : Executors.newCachedThreadPool(new TunnelThreadFactory()); } @Override - public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) - throws Exception { + public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception { logger.trace("Opening HTTP tunnel to " + this.uri); return new TunnelChannel(incomingChannel, closeable); } - protected final ClientHttpRequest createRequest(boolean hasPayload) - throws IOException { + protected final ClientHttpRequest createRequest(boolean hasPayload) throws IOException { HttpMethod method = hasPayload ? HttpMethod.POST : HttpMethod.GET; return this.requestFactory.createRequest(this.uri, method); } @@ -141,8 +137,7 @@ public class HttpTunnelConnection implements TunnelConnection { public int write(ByteBuffer src) throws IOException { int size = src.remaining(); if (size > 0) { - openNewConnection( - new HttpTunnelPayload(this.requestSeq.incrementAndGet(), src)); + openNewConnection(new HttpTunnelPayload(this.requestSeq.incrementAndGet(), src)); } return size; } @@ -157,8 +152,7 @@ public class HttpTunnelConnection implements TunnelConnection { } catch (IOException ex) { if (ex instanceof ConnectException) { - logger.warn("Failed to connect to remote application at " - + HttpTunnelConnection.this.uri); + logger.warn("Failed to connect to remote application at " + HttpTunnelConnection.this.uri); } else { logger.trace("Unexpected connection error", ex); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java index 5a1da11c11f..0f340e3c53b 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -144,8 +144,7 @@ public class TunnelClient implements SmartInitializingSingleton { } public void close() throws IOException { - logger.trace("Closing tunnel client on port " - + this.serverSocketChannel.socket().getLocalPort()); + logger.trace("Closing tunnel client on port " + this.serverSocketChannel.socket().getLocalPort()); this.serverSocketChannel.close(); this.acceptConnections = false; interrupt(); @@ -171,10 +170,10 @@ public class TunnelClient implements SmartInitializingSingleton { private void handleConnection(SocketChannel socketChannel) throws Exception { Closeable closeable = new SocketCloseable(socketChannel); TunnelClient.this.listeners.fireOpenEvent(socketChannel); - try (WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection - .open(socketChannel, closeable)) { - logger.trace("Accepted connection to tunnel client from " - + socketChannel.socket().getRemoteSocketAddress()); + try (WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection.open(socketChannel, + closeable)) { + logger.trace( + "Accepted connection to tunnel client from " + socketChannel.socket().getRemoteSocketAddress()); while (true) { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); int amountRead = socketChannel.read(buffer); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java index 7edc97c3c2c..555ef4730bb 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,6 @@ public interface TunnelConnection { * destined for the remote server * @throws Exception in case of errors */ - WritableByteChannel open(WritableByteChannel incomingChannel, Closeable closeable) - throws Exception; + WritableByteChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception; } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java index 2e2d4c5afd4..68e0f8ea6e4 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -134,8 +134,7 @@ public class HttpTunnelPayload { * @return payload data or {@code null} * @throws IOException in case of I/O errors */ - public static ByteBuffer getPayloadData(ReadableByteChannel channel) - throws IOException { + public static ByteBuffer getPayloadData(ReadableByteChannel channel) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); try { int amountRead = channel.read(buffer); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java index 9b13bb21110..0bf486fcaa2 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,7 @@ public class HttpTunnelPayloadForwarder { synchronized (this.monitor) { long seq = payload.getSequence(); if (this.lastRequestSeq != seq - 1) { - Assert.state(this.queue.size() < MAXIMUM_QUEUE_SIZE, - "Too many messages queued"); + Assert.state(this.queue.size() < MAXIMUM_QUEUE_SIZE, "Too many messages queued"); this.queue.put(seq, payload); return; } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java index c47b459a055..d6b74e32852 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,8 +112,7 @@ public class HttpTunnelServer { private static final long DEFAULT_DISCONNECT_TIMEOUT = TimeUnit.SECONDS.toMillis(30); - private static final MediaType DISCONNECT_MEDIA_TYPE = new MediaType("application", - "x-disconnect"); + private static final MediaType DISCONNECT_MEDIA_TYPE = new MediaType("application", "x-disconnect"); private static final Log logger = LogFactory.getLog(HttpTunnelServer.class); @@ -140,8 +139,7 @@ public class HttpTunnelServer { * @param response the HTTP response * @throws IOException in case of I/O errors */ - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { handle(new HttpConnection(request, response)); } @@ -199,8 +197,7 @@ public class HttpTunnelServer { * @param disconnectTimeout the disconnect timeout in milliseconds */ public void setDisconnectTimeout(long disconnectTimeout) { - Assert.isTrue(disconnectTimeout > 0, - "DisconnectTimeout must be a positive value"); + Assert.isTrue(disconnectTimeout > 0, "DisconnectTimeout must be a positive value"); this.disconnectTimeout = disconnectTimeout; } @@ -252,8 +249,7 @@ public class HttpTunnelServer { ByteBuffer data = HttpTunnelPayload.getPayloadData(this.targetServer); synchronized (this.httpConnections) { if (data != null) { - HttpTunnelPayload payload = new HttpTunnelPayload( - this.responseSeq.incrementAndGet(), data); + HttpTunnelPayload payload = new HttpTunnelPayload(this.responseSeq.incrementAndGet(), data); payload.logIncoming(); HttpConnection connection = getOrWaitForHttpConnection(); connection.respond(payload); @@ -285,8 +281,7 @@ public class HttpTunnelServer { Iterator iterator = this.httpConnections.iterator(); while (iterator.hasNext()) { HttpConnection httpConnection = iterator.next(); - if (httpConnection - .isOlderThan(HttpTunnelServer.this.longPollTimeout)) { + if (httpConnection.isOlderThan(HttpTunnelServer.this.longPollTimeout)) { httpConnection.respond(HttpStatus.NO_CONTENT); iterator.remove(); } @@ -298,8 +293,7 @@ public class HttpTunnelServer { if (this.lastHttpRequestTime > 0) { long timeout = HttpTunnelServer.this.disconnectTimeout; long duration = System.currentTimeMillis() - this.lastHttpRequestTime; - Assert.state(duration < timeout, - () -> "Disconnect timeout: " + timeout + " " + duration); + Assert.state(duration < timeout, () -> "Disconnect timeout: " + timeout + " " + duration); } } @@ -336,8 +330,7 @@ public class HttpTunnelServer { } synchronized (this.httpConnections) { while (this.httpConnections.size() > 1) { - this.httpConnections.removeFirst() - .respond(HttpStatus.TOO_MANY_REQUESTS); + this.httpConnections.removeFirst().respond(HttpStatus.TOO_MANY_REQUESTS); } this.lastHttpRequestTime = System.currentTimeMillis(); this.httpConnections.addLast(httpConnection); @@ -346,8 +339,7 @@ public class HttpTunnelServer { forwardToTargetServer(httpConnection); } - private void forwardToTargetServer(HttpConnection httpConnection) - throws IOException { + private void forwardToTargetServer(HttpConnection httpConnection) throws IOException { if (httpConnection.isDisconnectRequest()) { this.targetServer.close(); interrupt(); @@ -391,8 +383,7 @@ public class HttpTunnelServer { protected ServerHttpAsyncRequestControl startAsync() { try { // Try to use async to save blocking - ServerHttpAsyncRequestControl async = this.request - .getAsyncRequestControl(this.response); + ServerHttpAsyncRequestControl async = this.request.getAsyncRequestControl(this.response); async.start(); return async; } @@ -451,8 +442,7 @@ public class HttpTunnelServer { * @return if the request is a signal to disconnect */ public boolean isDisconnectRequest() { - return DISCONNECT_MEDIA_TYPE - .equals(this.request.getHeaders().getContentType()); + return DISCONNECT_MEDIA_TYPE.equals(this.request.getHeaders().getContentType()); } /** diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java index 67007ebc805..1ca001a1410 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class HttpTunnelServerHandler implements Handler { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { this.server.handle(request, response); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java index 0544a281001..c70ffe362b2 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import org.springframework.util.Assert; */ public class SocketTargetServerConnection implements TargetServerConnection { - private static final Log logger = LogFactory - .getLog(SocketTargetServerConnection.class); + private static final Log logger = LogFactory.getLog(SocketTargetServerConnection.class); private final PortProvider portProvider; @@ -73,8 +72,7 @@ public class SocketTargetServerConnection implements TargetServerConnection { TimeoutAwareChannel(SocketChannel socketChannel) throws IOException { this.socketChannel = socketChannel; - this.readChannel = Channels - .newChannel(socketChannel.socket().getInputStream()); + this.readChannel = Channels.newChannel(socketChannel.socket().getInputStream()); } @Override diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index 1fd0ac4654a..de4bb1b8820 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -38,14 +38,13 @@ public class RemoteUrlPropertyExtractorTests { @After public void preventRunFailuresFromPollutingLoggerContext() { - ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)) - .getLoggerContext().getTurboFilterList().clear(); + ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() + .getTurboFilterList().clear(); } @Test public void missingUrl() { - assertThatIllegalStateException().isThrownBy(this::doTest) - .withMessageContaining("No remote URL specified"); + assertThatIllegalStateException().isThrownBy(this::doTest).withMessageContaining("No remote URL specified"); } @Test @@ -57,26 +56,21 @@ public class RemoteUrlPropertyExtractorTests { @Test public void multipleUrls() { - assertThatIllegalStateException() - .isThrownBy( - () -> doTest("http://localhost:8080", "http://localhost:9090")) + assertThatIllegalStateException().isThrownBy(() -> doTest("http://localhost:8080", "http://localhost:9090")) .withMessageContaining("Multiple URLs specified"); } @Test public void validUrl() { ApplicationContext context = doTest("http://localhost:8080"); - assertThat(context.getEnvironment().getProperty("remoteUrl")) - .isEqualTo("http://localhost:8080"); - assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")) - .isNull(); + assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); + assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")).isNull(); } @Test public void cleanValidUrl() { ApplicationContext context = doTest("http://localhost:8080/"); - assertThat(context.getEnvironment().getProperty("remoteUrl")) - .isEqualTo("http://localhost:8080"); + assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); } private ApplicationContext doTest(String... args) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java index c7355edc204..37f6b2ea79b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java @@ -52,8 +52,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void singleManuallyConfiguredDataSourceIsNotClosed() throws Exception { - ConfigurableApplicationContext context = getContext( - () -> createContext(SingleDataSourceConfiguration.class)); + ConfigurableApplicationContext context = getContext(() -> createContext(SingleDataSourceConfiguration.class)); DataSource dataSource = context.getBean(DataSource.class); Statement statement = configureDataSourceBehavior(dataSource); verify(statement, never()).execute("SHUTDOWN"); @@ -63,8 +62,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { public void multipleDataSourcesAreIgnored() throws Exception { ConfigurableApplicationContext context = getContext( () -> createContext(MultipleDataSourcesConfiguration.class)); - Collection dataSources = context.getBeansOfType(DataSource.class) - .values(); + Collection dataSources = context.getBeansOfType(DataSource.class).values(); for (DataSource dataSource : dataSources) { Statement statement = configureDataSourceBehavior(dataSource); verify(statement, never()).execute("SHUTDOWN"); @@ -75,16 +73,14 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { public void emptyFactoryMethodMetadataIgnored() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); DataSource dataSource = mock(DataSource.class); - AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition( - dataSource.getClass()); + AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(dataSource.getClass()); context.registerBeanDefinition("dataSource", beanDefinition); context.register(DevToolsDataSourceAutoConfiguration.class); context.refresh(); context.close(); } - protected final Statement configureDataSourceBehavior(DataSource dataSource) - throws SQLException { + protected final Statement configureDataSourceBehavior(DataSource dataSource) throws SQLException { Connection connection = mock(Connection.class); Statement statement = mock(Statement.class); doReturn(connection).when(dataSource).getConnection(); @@ -92,8 +88,8 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { return statement; } - protected ConfigurableApplicationContext getContext( - Supplier supplier) throws Exception { + protected ConfigurableApplicationContext getContext(Supplier supplier) + throws Exception { AtomicReference atomicReference = new AtomicReference<>(); Thread thread = new Thread(() -> { ConfigurableApplicationContext context = supplier.get(); @@ -108,20 +104,17 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { return this.createContext(null, classes); } - protected final ConfigurableApplicationContext createContext(String driverClassName, - Class... classes) { + protected final ConfigurableApplicationContext createContext(String driverClassName, Class... classes) { return this.createContext(driverClassName, null, classes); } - protected final ConfigurableApplicationContext createContext(String driverClassName, - String url, Class... classes) { + protected final ConfigurableApplicationContext createContext(String driverClassName, String url, + Class... classes) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(classes); context.register(DevToolsDataSourceAutoConfiguration.class); if (driverClassName != null) { - TestPropertyValues - .of("spring.datasource.driver-class-name:" + driverClassName) - .applyTo(context); + TestPropertyValues.of("spring.datasource.driver-class-name:" + driverClassName).applyTo(context); } if (url != null) { TestPropertyValues.of("spring.datasource.url:" + url).applyTo(context); @@ -168,8 +161,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { private static class DataSourceSpyBeanPostProcessor implements BeanPostProcessor { @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { bean = spy(bean); } @@ -177,8 +169,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java index c78395a927c..15d8a7b8956 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,15 +39,13 @@ import static org.mockito.Mockito.verify; */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions("HikariCP-*.jar") -public class DevToolsEmbeddedDataSourceAutoConfigurationTests - extends AbstractDevToolsDataSourceAutoConfigurationTests { +public class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void autoConfiguredDataSourceIsNotShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext( - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext(DataSourceAutoConfiguration.class, + DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, never()).execute("SHUTDOWN"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java index 45101362f30..150c49b1f04 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java @@ -39,16 +39,14 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class DevToolsPooledDataSourceAutoConfigurationTests - extends AbstractDevToolsDataSourceAutoConfigurationTests { +public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { @Rule public final TemporaryFolder temp = new TemporaryFolder(); @Before public void before() throws IOException { - System.setProperty("derby.stream.error.file", - this.temp.newFile("derby.log").getAbsolutePath()); + System.setProperty("derby.stream.error.file", this.temp.newFile("derby.log").getAbsolutePath()); } @After @@ -58,76 +56,63 @@ public class DevToolsPooledDataSourceAutoConfigurationTests @Test public void autoConfiguredInMemoryDataSourceIsShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext( + () -> createContext(DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement).execute("SHUTDOWN"); } @Test public void autoConfiguredExternalDataSourceIsNotShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - "org.postgresql.Driver", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext(() -> createContext("org.postgresql.Driver", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, never()).execute("SHUTDOWN"); } @Test public void h2ServerIsNotShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - "org.h2.Driver", "jdbc:h2:hsql://localhost", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext(() -> createContext("org.h2.Driver", + "jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, never()).execute("SHUTDOWN"); } @Test public void inMemoryH2IsShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - "org.h2.Driver", "jdbc:h2:mem:test", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext(() -> createContext("org.h2.Driver", "jdbc:h2:mem:test", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, times(1)).execute("SHUTDOWN"); } @Test public void hsqlServerIsNotShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - "org.hsqldb.jdbcDriver", "jdbc:hsqldb:hsql://localhost", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext(() -> createContext("org.hsqldb.jdbcDriver", + "jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, never()).execute("SHUTDOWN"); } @Test public void inMemoryHsqlIsShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:test", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext(() -> createContext("org.hsqldb.jdbcDriver", + "jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, times(1)).execute("SHUTDOWN"); } @Test public void derbyClientIsNotShutdown() throws Exception { - ConfigurableApplicationContext context = getContext(() -> createContext( - "org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = getContext(() -> createContext("org.apache.derby.jdbc.ClientDriver", + "jdbc:derby://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, never()).execute("SHUTDOWN"); } @@ -135,11 +120,9 @@ public class DevToolsPooledDataSourceAutoConfigurationTests @Test public void inMemoryDerbyIsShutdown() throws Exception { ConfigurableApplicationContext configurableApplicationContext = getContext( - () -> createContext("org.apache.derby.jdbc.EmbeddedDriver", - "jdbc:derby:memory:test", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class)); - Statement statement = configureDataSourceBehavior( - configurableApplicationContext.getBean(DataSource.class)); + () -> createContext("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:test", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); + Statement statement = configureDataSourceBehavior(configurableApplicationContext.getBean(DataSource.class)); configurableApplicationContext.close(); verify(statement, times(1)).execute("SHUTDOWN"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java index 0a335d68706..b7f0b054df6 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,9 +33,8 @@ public class DevToolsPropertiesTests { public void additionalExcludeKeepsDefaults() { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setAdditionalExclude("foo/**,bar/**"); - assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", - "META-INF/resources/**", "resources/**", "static/**", "public/**", - "templates/**", "**/*Test.class", "**/*Tests.class", "git.properties", + assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", "META-INF/resources/**", "resources/**", + "static/**", "public/**", "templates/**", "**/*Test.class", "**/*Tests.class", "git.properties", "META-INF/build-info.properties", "foo/**", "bar/**"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java index fd775f64d69..8ab5d61d3e4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -88,29 +88,24 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void thymeleafCacheIsFalse() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); - SpringResourceTemplateResolver resolver = this.context - .getBean(SpringResourceTemplateResolver.class); + SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isFalse(); } @Test public void defaultPropertyCanBeOverriddenFromCommandLine() throws Exception { - this.context = getContext( - () -> initializeAndRun(Config.class, "--spring.thymeleaf.cache=true")); - SpringResourceTemplateResolver resolver = this.context - .getBean(SpringResourceTemplateResolver.class); + this.context = getContext(() -> initializeAndRun(Config.class, "--spring.thymeleaf.cache=true")); + SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } @Test public void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception { String userHome = System.getProperty("user.home"); - System.setProperty("user.home", - new File("src/test/resources/user-home").getAbsolutePath()); + System.setProperty("user.home", new File("src/test/resources/user-home").getAbsolutePath()); try { this.context = getContext(() -> initializeAndRun(Config.class)); - SpringResourceTemplateResolver resolver = this.context - .getBean(SpringResourceTemplateResolver.class); + SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } finally { @@ -146,8 +141,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), false); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); this.context.publishEvent(event); verify(server).triggerReload(); } @@ -157,8 +151,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), true); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); this.context.publishEvent(event); verify(server, never()).triggerReload(); } @@ -175,8 +168,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartTriggeredOnClassPathChangeWithRestart() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), true); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); this.context.publishEvent(event); verify(this.mockRestarter.getMock()).restart(any(FailureHandler.class)); } @@ -184,8 +176,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartNotTriggeredOnClassPathChangeWithRestart() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), false); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); this.context.publishEvent(event); verify(this.mockRestarter.getMock(), never()).restart(); } @@ -193,8 +184,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartWatchingClassPath() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); - ClassPathFileSystemWatcher watcher = this.context - .getBean(ClassPathFileSystemWatcher.class); + ClassPathFileSystemWatcher watcher = this.context.getBean(ClassPathFileSystemWatcher.class); assertThat(watcher).isNotNull(); } @@ -212,10 +202,8 @@ public class LocalDevToolsAutoConfigurationTests { Map properties = new HashMap<>(); properties.put("spring.devtools.restart.trigger-file", "somefile.txt"); this.context = getContext(() -> initializeAndRun(Config.class, properties)); - ClassPathFileSystemWatcher classPathWatcher = this.context - .getBean(ClassPathFileSystemWatcher.class); - Object watcher = ReflectionTestUtils.getField(classPathWatcher, - "fileSystemWatcher"); + ClassPathFileSystemWatcher classPathWatcher = this.context.getBean(ClassPathFileSystemWatcher.class); + Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); Object filter = ReflectionTestUtils.getField(watcher, "triggerFilter"); assertThat(filter).isInstanceOf(TriggerFileFilter.class); } @@ -223,18 +211,13 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void watchingAdditionalPaths() throws Exception { Map properties = new HashMap<>(); - properties.put("spring.devtools.restart.additional-paths", - "src/main/java,src/test/java"); + properties.put("spring.devtools.restart.additional-paths", "src/main/java,src/test/java"); this.context = getContext(() -> initializeAndRun(Config.class, properties)); - ClassPathFileSystemWatcher classPathWatcher = this.context - .getBean(ClassPathFileSystemWatcher.class); - Object watcher = ReflectionTestUtils.getField(classPathWatcher, - "fileSystemWatcher"); + ClassPathFileSystemWatcher classPathWatcher = this.context.getBean(ClassPathFileSystemWatcher.class); + Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); @SuppressWarnings("unchecked") - Map folders = (Map) ReflectionTestUtils - .getField(watcher, "folders"); - assertThat(folders).hasSize(2) - .containsKey(new File("src/main/java").getAbsoluteFile()) + Map folders = (Map) ReflectionTestUtils.getField(watcher, "folders"); + assertThat(folders).hasSize(2).containsKey(new File("src/main/java").getAbsoluteFile()) .containsKey(new File("src/test/java").getAbsoluteFile()); } @@ -250,8 +233,8 @@ public class LocalDevToolsAutoConfigurationTests { assertThat(options.getDevelopment()).isTrue(); } - private ConfigurableApplicationContext getContext( - Supplier supplier) throws Exception { + private ConfigurableApplicationContext getContext(Supplier supplier) + throws Exception { AtomicReference atomicReference = new AtomicReference<>(); Thread thread = new Thread(() -> { ConfigurableApplicationContext context = supplier.get(); @@ -262,13 +245,12 @@ public class LocalDevToolsAutoConfigurationTests { return atomicReference.get(); } - private ConfigurableApplicationContext initializeAndRun(Class config, - String... args) { + private ConfigurableApplicationContext initializeAndRun(Class config, String... args) { return initializeAndRun(config, Collections.emptyMap(), args); } - private ConfigurableApplicationContext initializeAndRun(Class config, - Map properties, String... args) { + private ConfigurableApplicationContext initializeAndRun(Class config, Map properties, + String... args) { Restarter.initialize(new String[0], false, new MockRestartInitializer(), false); SpringApplication application = new SpringApplication(config); application.setDefaultProperties(getDefaultProperties(properties)); @@ -276,8 +258,7 @@ public class LocalDevToolsAutoConfigurationTests { return context; } - private Map getDefaultProperties( - Map specifiedProperties) { + private Map getDefaultProperties(Map specifiedProperties) { Map properties = new HashMap<>(); properties.put("spring.thymeleaf.check-template-location", false); properties.put("spring.devtools.livereload.port", 0); @@ -287,15 +268,15 @@ public class LocalDevToolsAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @Import({ ServletWebServerFactoryAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ThymeleafAutoConfiguration.class }) public static class Config { } @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) + @ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ThymeleafAutoConfiguration.class }) public static class ConfigWithMockLiveReload { @Bean @@ -306,8 +287,8 @@ public class LocalDevToolsAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @Import({ ServletWebServerFactoryAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ResourceProperties.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ResourceProperties.class }) public static class WebResourcesConfig { } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java index 0df8cb4ee6a..feed1538c8b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java @@ -48,8 +48,7 @@ public class OnEnabledDevToolsConditionTests { AtomicBoolean containsBean = new AtomicBoolean(); Thread thread = new Thread(() -> { OnEnabledDevToolsConditionTests.this.context.refresh(); - containsBean.set( - OnEnabledDevToolsConditionTests.this.context.containsBean("test")); + containsBean.set(OnEnabledDevToolsConditionTests.this.context.containsBean("test")); }); thread.start(); thread.join(); @@ -59,8 +58,7 @@ public class OnEnabledDevToolsConditionTests { @Test public void outcomeWhenDevtoolsShouldBeEnabledIsFalseShouldNotMatch() { OnEnabledDevToolsConditionTests.this.context.refresh(); - assertThat(OnEnabledDevToolsConditionTests.this.context.containsBean("test")) - .isFalse(); + assertThat(OnEnabledDevToolsConditionTests.this.context.containsBean("test")).isFalse(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index 7f037e5a043..199e8460af7 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -92,8 +92,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void ignoresUnmappedUrl() throws Exception { - this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret")); + this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/restart"); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -103,8 +102,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void ignoresIfMissingSecretFromRequest() throws Exception { - this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret")); + this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart"); filter.doFilter(this.request, this.response, this.chain); @@ -113,8 +111,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void ignoresInvalidSecretInRequest() throws Exception { - this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret")); + this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart"); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "invalid"); @@ -124,8 +121,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void invokeRestartWithDefaultSetup() throws Exception { - this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret")); + this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart"); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -136,8 +132,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void invokeRestartWithCustomServerContextPath() throws Exception { this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret", - "server.servlet.context-path:/test")); + () -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/test" + DEFAULT_CONTEXT_PATH + "/restart"); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -147,17 +142,15 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void disableRestart() throws Exception { - this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret", - "spring.devtools.remote.restart.enabled:false")); + this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret", + "spring.devtools.remote.restart.enabled:false")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean("remoteRestartHandlerMapper")); } @Test public void devToolsHealthReturns200() throws Exception { - this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret")); + this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -169,8 +162,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void devToolsHealthWithCustomServerContextPathReturns200() throws Exception { this.context = getContext( - () -> loadContext("spring.devtools.remote.secret:supersecret", - "server.servlet.context-path:/test")); + () -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/test" + DEFAULT_CONTEXT_PATH); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -180,8 +172,7 @@ public class RemoteDevToolsAutoConfigurationTests { } private AnnotationConfigServletWebApplicationContext getContext( - Supplier supplier) - throws Exception { + Supplier supplier) throws Exception { AtomicReference atomicReference = new AtomicReference<>(); Thread thread = new Thread(() -> { AnnotationConfigServletWebApplicationContext context = supplier.get(); @@ -193,12 +184,10 @@ public class RemoteDevToolsAutoConfigurationTests { } private void assertRestartInvoked(boolean value) { - assertThat(this.context.getBean(MockHttpRestartServer.class).invoked) - .isEqualTo(value); + assertThat(this.context.getBean(MockHttpRestartServer.class).invoked).isEqualTo(value); } - private AnnotationConfigServletWebApplicationContext loadContext( - String... properties) { + private AnnotationConfigServletWebApplicationContext loadContext(String... properties) { AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); context.setServletContext(new MockServletContext()); context.register(Config.class, PropertyPlaceholderAutoConfiguration.class); @@ -213,8 +202,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Bean public HttpRestartServer remoteRestartHttpRestartServer() { - SourceFolderUrlFilter sourceFolderUrlFilter = mock( - SourceFolderUrlFilter.class); + SourceFolderUrlFilter sourceFolderUrlFilter = mock(SourceFolderUrlFilter.class); return new MockHttpRestartServer(sourceFolderUrlFilter); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index 9d7870403e7..e9597941b37 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,16 +37,14 @@ public class ClassPathChangedEventTests { @Test public void changeSetMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) .withMessageContaining("ChangeSet must not be null"); } @Test public void getChangeSet() { Set changeSet = new LinkedHashSet<>(); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, - false); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, false); assertThat(event.getChangeSet()).isSameAs(changeSet); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index 73cb0b2048f..b6280d9d7f8 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,16 +67,14 @@ public class ClassPathFileChangeListenerTests { @Test public void eventPublisherMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileChangeListener(null, - this.restartStrategy, this.fileSystemWatcher)) + .isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher)) .withMessageContaining("EventPublisher must not be null"); } @Test public void restartStrategyMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, - null, this.fileSystemWatcher)) + .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher)) .withMessageContaining("RestartStrategy must not be null"); } @@ -93,8 +91,8 @@ public class ClassPathFileChangeListenerTests { } private void testSendsEvent(boolean restart) { - ClassPathFileChangeListener listener = new ClassPathFileChangeListener( - this.eventPublisher, this.restartStrategy, this.fileSystemWatcher); + ClassPathFileChangeListener listener = new ClassPathFileChangeListener(this.eventPublisher, + this.restartStrategy, this.fileSystemWatcher); File folder = new File("s1"); File file = new File("f1"); ChangedFile file1 = new ChangedFile(folder, file, ChangedFile.Type.ADD); @@ -109,8 +107,7 @@ public class ClassPathFileChangeListenerTests { } listener.onChange(changeSet); verify(this.eventPublisher).publishEvent(this.eventCaptor.capture()); - ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor - .getValue(); + ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor.getValue(); assertThat(actualEvent.getChangeSet()).isEqualTo(changeSet); assertThat(actualEvent.isRestartRequired()).isEqualTo(restart); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index a8156b38b34..7b24c9396be 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -55,8 +55,7 @@ public class ClassPathFileSystemWatcherTests { @Test public void urlsMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileSystemWatcher( - mock(FileSystemWatcherFactory.class), + .isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), mock(ClassPathRestartStrategy.class), (URL[]) null)) .withMessageContaining("Urls must not be null"); } @@ -86,8 +85,8 @@ public class ClassPathFileSystemWatcherTests { Thread.sleep(500); } assertThat(events.size()).isEqualTo(1); - assertThat(events.get(0).getChangeSet().iterator().next().getFiles().iterator() - .next().getFile()).isEqualTo(classFile); + assertThat(events.get(0).getChangeSet().iterator().next().getFiles().iterator().next().getFile()) + .isEqualTo(classFile); context.close(); } @@ -101,13 +100,10 @@ public class ClassPathFileSystemWatcherTests { } @Bean - public ClassPathFileSystemWatcher watcher( - ClassPathRestartStrategy restartStrategy) { - FileSystemWatcher watcher = new FileSystemWatcher(false, - Duration.ofMillis(100), Duration.ofMillis(10)); + public ClassPathFileSystemWatcher watcher(ClassPathRestartStrategy restartStrategy) { + FileSystemWatcher watcher = new FileSystemWatcher(false, Duration.ofMillis(100), Duration.ofMillis(10)); URL[] urls = this.environment.getProperty("urls", URL[].class); - return new ClassPathFileSystemWatcher( - new MockFileSystemWatcherFactory(watcher), restartStrategy, urls); + return new ClassPathFileSystemWatcher(new MockFileSystemWatcherFactory(watcher), restartStrategy, urls); } @Bean @@ -137,8 +133,7 @@ public class ClassPathFileSystemWatcherTests { } - private static class MockFileSystemWatcherFactory - implements FileSystemWatcherFactory { + private static class MockFileSystemWatcherFactory implements FileSystemWatcherFactory { private final FileSystemWatcher watcher; diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java index 13ade8c8733..bb397c40d37 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,7 @@ public class PatternClassPathRestartStrategyTests { @Test public void testChange() { - ClassPathRestartStrategy strategy = createStrategy( - "**/*Test.class,**/*Tests.class"); + ClassPathRestartStrategy strategy = createStrategy("**/*Test.class,**/*Tests.class"); assertRestartRequired(strategy, "com/example/ExampleTests.class", false); assertRestartRequired(strategy, "com/example/ExampleTest.class", false); assertRestartRequired(strategy, "com/example/Example.class", true); @@ -87,10 +86,8 @@ public class PatternClassPathRestartStrategyTests { return new PatternClassPathRestartStrategy(pattern); } - private void assertRestartRequired(ClassPathRestartStrategy strategy, - String relativeName, boolean expected) { - assertThat(strategy.isRestartRequired(mockFile(relativeName))) - .isEqualTo(expected); + private void assertRestartRequired(ClassPathRestartStrategy strategy, String relativeName, boolean expected) { + assertThat(strategy.isRestartRequired(mockFile(relativeName))).isEqualTo(expected); } private ChangedFile mockFile(String relativeName) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java index cbcf917163a..e994737793e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java @@ -64,30 +64,25 @@ public class DevToolPropertiesIntegrationTests { @Test public void classPropertyConditionIsAffectedByDevToolProperties() throws Exception { - SpringApplication application = new SpringApplication( - ClassConditionConfiguration.class); + SpringApplication application = new SpringApplication(ClassConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); this.context.getBean(ClassConditionConfiguration.class); } @Test - public void beanMethodPropertyConditionIsAffectedByDevToolProperties() - throws Exception { - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + public void beanMethodPropertyConditionIsAffectedByDevToolProperties() throws Exception { + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); this.context.getBean(MyBean.class); } @Test - public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() - throws Exception { + public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception { Restarter.clearInstance(); Restarter.disable(); - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) @@ -95,15 +90,12 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() - throws Exception { + public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception { Restarter.clearInstance(); Restarter.disable(); - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); - application.setDefaultProperties( - Collections.singletonMap("spring.devtools.remote.secret", "donttell")); + application.setDefaultProperties(Collections.singletonMap("spring.devtools.remote.secret", "donttell")); this.context = getContext(application::run); this.context.getBean(MyBean.class); } @@ -115,12 +107,11 @@ public class DevToolPropertiesIntegrationTests { this.context = getContext(application::run); ConfigurableEnvironment environment = this.context.getEnvironment(); String property = environment.getProperty("server.error.include-stacktrace"); - assertThat(property) - .isEqualTo(ErrorProperties.IncludeStacktrace.ALWAYS.toString()); + assertThat(property).isEqualTo(ErrorProperties.IncludeStacktrace.ALWAYS.toString()); } - protected ConfigurableApplicationContext getContext( - Supplier supplier) throws Exception { + protected ConfigurableApplicationContext getContext(Supplier supplier) + throws Exception { AtomicReference atomicReference = new AtomicReference<>(); Thread thread = new Thread(() -> { ConfigurableApplicationContext context = supplier.get(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java index cb2a71a99f8..ea98786c393 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java @@ -54,8 +54,7 @@ public class DevToolsHomePropertiesPostProcessorTests { public void loadsHomeProperties() throws Exception { Properties properties = new Properties(); properties.put("abc", "def"); - OutputStream out = new FileOutputStream( - new File(this.home, ".spring-boot-devtools.properties")); + OutputStream out = new FileOutputStream(new File(this.home, ".spring-boot-devtools.properties")); properties.store(out, null); out.close(); ConfigurableEnvironment environment = new MockEnvironment(); @@ -78,8 +77,7 @@ public class DevToolsHomePropertiesPostProcessorTests { thread.join(); } - private class MockDevToolHomePropertiesPostProcessor - extends DevToolsHomePropertiesPostProcessor { + private class MockDevToolHomePropertiesPostProcessor extends DevToolsHomePropertiesPostProcessor { @Override protected File getHomeFolder() { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index 39c9e8827b4..c772f9748d6 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,22 +39,20 @@ public class ChangedFileTests { @Test public void sourceFolderMustNotBeNull() throws Exception { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(null, this.temp.newFile(), Type.ADD)) + assertThatIllegalArgumentException().isThrownBy(() -> new ChangedFile(null, this.temp.newFile(), Type.ADD)) .withMessageContaining("SourceFolder must not be null"); } @Test public void fileMustNotBeNull() throws Exception { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(this.temp.newFolder(), null, Type.ADD)) + assertThatIllegalArgumentException().isThrownBy(() -> new ChangedFile(this.temp.newFolder(), null, Type.ADD)) .withMessageContaining("File must not be null"); } @Test public void typeMustNotBeNull() throws Exception { - assertThatIllegalArgumentException().isThrownBy( - () -> new ChangedFile(this.temp.newFile(), this.temp.newFolder(), null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new ChangedFile(this.temp.newFile(), this.temp.newFolder(), null)) .withMessageContaining("Type must not be null"); } @@ -67,8 +65,7 @@ public class ChangedFileTests { @Test public void getType() throws Exception { - ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), - this.temp.newFile(), Type.DELETE); + ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), this.temp.newFile(), Type.DELETE); assertThat(changedFile.getType()).isEqualTo(Type.DELETE); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index fe8cc67c788..0c427ed94ee 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public class FileSnapshotTests { private static final long TWO_MINS = TimeUnit.MINUTES.toMillis(2); - private static final long MODIFIED = new Date().getTime() - - TimeUnit.DAYS.toMillis(10); + private static final long MODIFIED = new Date().getTime() - TimeUnit.DAYS.toMillis(10); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -53,8 +52,7 @@ public class FileSnapshotTests { @Test public void fileMustNotBeAFolder() throws Exception { - assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSnapshot(this.temporaryFolder.newFolder())) + assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(this.temporaryFolder.newFolder())) .withMessageContaining("File must not be a folder"); } @@ -98,8 +96,7 @@ public class FileSnapshotTests { return file; } - private void setupFile(File file, String content, long lastModified) - throws IOException { + private void setupFile(File file, String content, long lastModified) throws IOException { FileCopyUtils.copy(content.getBytes(), file); file.setLastModified(lastModified); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index 3b9bfb4b972..c08bc9baf15 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class FileSystemWatcherTests { private FileSystemWatcher watcher; - private List> changes = Collections - .synchronizedList(new ArrayList<>()); + private List> changes = Collections.synchronizedList(new ArrayList<>()); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -63,47 +62,40 @@ public class FileSystemWatcherTests { @Test public void pollIntervalMustBePositive() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), - Duration.ofMillis(1))) + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1))) .withMessageContaining("PollInterval must be positive"); } @Test public void quietPeriodMustBePositive() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), - Duration.ofMillis(0))) + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0))) .withMessageContaining("QuietPeriod must be positive"); } @Test public void pollIntervalMustBeGreaterThanQuietPeriod() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), - Duration.ofMillis(1))) + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1))) .withMessageContaining("PollInterval must be greater than QuietPeriod"); } @Test public void listenerMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.watcher.addListener(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addListener(null)) .withMessageContaining("FileChangeListener must not be null"); } @Test public void cannotAddListenerToStartedListener() { this.watcher.start(); - assertThatIllegalStateException() - .isThrownBy( - () -> this.watcher.addListener(mock(FileChangeListener.class))) + assertThatIllegalStateException().isThrownBy(() -> this.watcher.addListener(mock(FileChangeListener.class))) .withMessageContaining("FileSystemWatcher already started"); } @Test public void sourceFolderMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.watcher.addSourceFolder(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceFolder(null)) .withMessageContaining("Folder must not be null"); } @@ -111,16 +103,14 @@ public class FileSystemWatcherTests { public void sourceFolderMustNotBeAFile() { File folder = new File("pom.xml"); assertThat(folder.isFile()).isTrue(); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.watcher.addSourceFolder(new File("pom.xml"))) + assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceFolder(new File("pom.xml"))) .withMessageContaining("Folder 'pom.xml' must not be a file"); } @Test public void cannotAddSourceFolderToStartedListener() throws Exception { this.watcher.start(); - assertThatIllegalStateException() - .isThrownBy(() -> this.watcher.addSourceFolder(this.temp.newFolder())) + assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceFolder(this.temp.newFolder())) .withMessageContaining("FileSystemWatcher already started"); } @@ -262,8 +252,7 @@ public class FileSystemWatcherTests { File file = touch(new File(folder, "file.txt")); File trigger = touch(new File(folder, "trigger.txt")); this.watcher.addSourceFolder(folder); - this.watcher.setTriggerFilter( - (candidate) -> candidate.getName().equals("trigger.txt")); + this.watcher.setTriggerFilter((candidate) -> candidate.getName().equals("trigger.txt")); this.watcher.start(); FileCopyUtils.copy("abc".getBytes(), file); Thread.sleep(100); @@ -278,10 +267,8 @@ public class FileSystemWatcherTests { } private void setupWatcher(long pollingInterval, long quietPeriod) { - this.watcher = new FileSystemWatcher(false, Duration.ofMillis(pollingInterval), - Duration.ofMillis(quietPeriod)); - this.watcher.addListener( - (changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet)); + this.watcher = new FileSystemWatcher(false, Duration.ofMillis(pollingInterval), Duration.ofMillis(quietPeriod)); + this.watcher.addListener((changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet)); } private File startWithNewFolder() throws IOException { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java index f10cb00eb95..d57afda693c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,18 +101,15 @@ public class FolderSnapshotTests { @Test public void getChangedFilesSnapshotMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) .withMessageContaining("Snapshot must not be null"); } @Test public void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.initialSnapshot.getChangedFiles( - new FolderSnapshot(createTestFolderStructure()), null)) - .withMessageContaining( - "Snapshot source folder must be '" + this.folder + "'"); + assertThatIllegalArgumentException().isThrownBy( + () -> this.initialSnapshot.getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null)) + .withMessageContaining("Snapshot source folder must be '" + this.folder + "'"); } @Test @@ -131,8 +128,7 @@ public class FolderSnapshotTests { file2.delete(); newFile.createNewFile(); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); - ChangedFiles changedFiles = this.initialSnapshot.getChangedFiles(updatedSnapshot, - null); + ChangedFiles changedFiles = this.initialSnapshot.getChangedFiles(updatedSnapshot, null); assertThat(changedFiles.getSourceFolder()).isEqualTo(this.folder); assertThat(getChangedFile(changedFiles, file1).getType()).isEqualTo(Type.MODIFY); assertThat(getChangedFile(changedFiles, file2).getType()).isEqualTo(Type.DELETE); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java index a22608457d5..586b0a611b9 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java @@ -67,8 +67,7 @@ public class HttpTunnelIntegrationTests { context.register(ServerConfiguration.class); context.refresh(); String url = "http://localhost:" + context.getWebServer().getPort() + "/hello"; - ResponseEntity entity = new TestRestTemplate().getForEntity(url, - String.class); + ResponseEntity entity = new TestRestTemplate().getForEntity(url, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); context.close(); @@ -80,14 +79,11 @@ public class HttpTunnelIntegrationTests { serverContext.register(ServerConfiguration.class); serverContext.refresh(); AnnotationConfigApplicationContext tunnelContext = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("server.port:" + serverContext.getWebServer().getPort()) - .applyTo(tunnelContext); + TestPropertyValues.of("server.port:" + serverContext.getWebServer().getPort()).applyTo(tunnelContext); tunnelContext.register(TunnelConfiguration.class); tunnelContext.refresh(); - String url = "http://localhost:" - + tunnelContext.getBean(TestTunnelClient.class).port + "/hello"; - ResponseEntity entity = new TestRestTemplate().getForEntity(url, - String.class); + String url = "http://localhost:" + tunnelContext.getBean(TestTunnelClient.class).port + "/hello"; + ResponseEntity entity = new TestRestTemplate().getForEntity(url, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); serverContext.close(); @@ -114,13 +110,11 @@ public class HttpTunnelIntegrationTests { } @Bean - public DispatcherFilter filter( - AnnotationConfigServletWebServerApplicationContext context) { + public DispatcherFilter filter(AnnotationConfigServletWebServerApplicationContext context) { TargetServerConnection connection = new SocketTargetServerConnection( () -> context.getWebServer().getPort()); HttpTunnelServer server = new HttpTunnelServer(connection); - HandlerMapper mapper = new UrlHandlerMapper("/httptunnel", - new HttpTunnelServerHandler(server)); + HandlerMapper mapper = new UrlHandlerMapper("/httptunnel", new HttpTunnelServerHandler(server)); Collection mappers = Collections.singleton(mapper); Dispatcher dispatcher = new Dispatcher(AccessManager.PERMIT_ALL, mappers); return new DispatcherFilter(dispatcher); @@ -134,8 +128,7 @@ public class HttpTunnelIntegrationTests { @Bean public TunnelClient tunnelClient(@Value("${server.port}") int serverPort) { String url = "http://localhost:" + serverPort + "/httptunnel"; - TunnelConnection connection = new HttpTunnelConnection(url, - new SimpleClientHttpRequestFactory()); + TunnelConnection connection = new HttpTunnelConnection(url, new SimpleClientHttpRequestFactory()); return new TestTunnelClient(0, connection); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index 9a72513024b..05bbd45422c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,20 +40,17 @@ public class ConnectionInputStreamTests { public void readHeader() throws Exception { String header = ""; for (int i = 0; i < 100; i++) { - header += "x-something-" + i - + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + header += "x-something-" + i + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; } String data = header + "\r\n\r\n" + "content\r\n"; - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(data.getBytes())); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(data.getBytes())); assertThat(inputStream.readHeader()).isEqualTo(header); } @Test public void readFully() throws Exception { byte[] bytes = "the data that we want to read fully".getBytes(); - LimitedInputStream source = new LimitedInputStream( - new ByteArrayInputStream(bytes), 2); + LimitedInputStream source = new LimitedInputStream(new ByteArrayInputStream(bytes), 2); ConnectionInputStream inputStream = new ConnectionInputStream(source); byte[] buffer = new byte[bytes.length]; inputStream.readFully(buffer, 0, buffer.length); @@ -62,19 +59,15 @@ public class ConnectionInputStreamTests { @Test public void checkedRead() throws Exception { - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(NO_BYTES)); - assertThatIOException().isThrownBy(inputStream::checkedRead) - .withMessageContaining("End of stream"); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); + assertThatIOException().isThrownBy(inputStream::checkedRead).withMessageContaining("End of stream"); } @Test public void checkedReadArray() throws Exception { byte[] buffer = new byte[100]; - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(NO_BYTES)); - assertThatIOException() - .isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length)) + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); + assertThatIOException().isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length)) .withMessageContaining("End of stream"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index 9f537fcea49..5a5b7f2ebca 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class FrameTests { @Test public void typeMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Frame((Frame.Type) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new Frame((Frame.Type) null)) .withMessageContaining("Type must not be null"); } @@ -88,16 +87,14 @@ public class FrameTests { @Test public void readFragmentedNotSupported() throws Exception { byte[] bytes = new byte[] { 0x0F }; - assertThatIllegalStateException() - .isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) + assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) .withMessageContaining("Fragmented frames are not supported"); } @Test public void readLargeFramesNotSupported() throws Exception { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0xFF }; - assertThatIllegalStateException() - .isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) + assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) .withMessageContaining("Large frames are not supported"); } @@ -111,8 +108,7 @@ public class FrameTests { @Test public void readMaskedTextFrame() throws Exception { - byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, - 0x4E, 0x4E }; + byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, 0x4E, 0x4E }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); assertThat(frame.getPayload()).isEqualTo(new byte[] { 0x41, 0x41 }); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java index e7800fc5f5c..eedb3b95432 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,7 @@ public class LiveReloadServerTests { this.server.triggerReload(); Thread.sleep(200); this.server.stop(); - assertThat(handler.getMessages().get(0)) - .contains("http://livereload.com/protocols/official-7"); + assertThat(handler.getMessages().get(0)).contains("http://livereload.com/protocols/official-7"); assertThat(handler.getMessages().get(1)).contains("command\":\"reload\""); } @@ -109,8 +108,7 @@ public class LiveReloadServerTests { private void awaitClosedException() throws InterruptedException { long startTime = System.currentTimeMillis(); - while (this.server.getClosedExceptions().isEmpty() - && System.currentTimeMillis() - startTime < 10000) { + while (this.server.getClosedExceptions().isEmpty() && System.currentTimeMillis() - startTime < 10000) { Thread.sleep(100); } } @@ -164,8 +162,8 @@ public class LiveReloadServerTests { } @Override - protected Connection createConnection(java.net.Socket socket, - InputStream inputStream, OutputStream outputStream) throws IOException { + protected Connection createConnection(java.net.Socket socket, InputStream inputStream, + OutputStream outputStream) throws IOException { return new MonitoredConnection(socket, inputStream, outputStream); } @@ -177,8 +175,8 @@ public class LiveReloadServerTests { private class MonitoredConnection extends Connection { - MonitoredConnection(java.net.Socket socket, InputStream inputStream, - OutputStream outputStream) throws IOException { + MonitoredConnection(java.net.Socket socket, InputStream inputStream, OutputStream outputStream) + throws IOException { super(socket, inputStream, outputStream); } @@ -212,8 +210,7 @@ public class LiveReloadServerTests { private CloseStatus closeStatus; @Override - public void afterConnectionEstablished(WebSocketSession session) - throws Exception { + public void afterConnectionEstablished(WebSocketSession session) throws Exception { this.session = session; session.sendMessage(new TextMessage(HANDSHAKE)); this.helloLatch.countDown(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index 1984cb14549..0432e74e8f0 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -65,37 +65,32 @@ public class ClassPathChangeUploaderTests { @Before public void setup() { this.requestFactory = new MockClientHttpRequestFactory(); - this.uploader = new ClassPathChangeUploader("http://localhost/upload", - this.requestFactory); + this.uploader = new ClassPathChangeUploader("http://localhost/upload", this.requestFactory); } @Test public void urlMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory)) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory)) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test public void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new ClassPathChangeUploader("http://localhost:8080", null)) + .isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null)) .withMessageContaining("RequestFactory must not be null"); } @Test public void urlMustNotBeMalformed() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", - this.requestFactory)) + .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory)) .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @@ -118,8 +113,7 @@ public class ClassPathChangeUploaderTests { this.requestFactory.willRespond(HttpStatus.OK); this.uploader.onApplicationEvent(event); assertThat(this.requestFactory.getExecutedRequests()).hasSize(2); - verifyUploadRequest(sourceFolder, - this.requestFactory.getExecutedRequests().get(1)); + verifyUploadRequest(sourceFolder, this.requestFactory.getExecutedRequests().get(1)); } private void verifyUploadRequest(File sourceFolder, MockClientHttpRequest request) @@ -137,13 +131,11 @@ public class ClassPathChangeUploaderTests { } private void assertClassFile(ClassLoaderFile file, String content, Kind kind) { - assertThat(file.getContents()) - .isEqualTo((content != null) ? content.getBytes() : null); + assertThat(file.getContents()).isEqualTo((content != null) ? content.getBytes() : null); assertThat(file.getKind()).isEqualTo(kind); } - private ClassPathChangedEvent createClassPathChangedEvent(File sourceFolder) - throws IOException { + private ClassPathChangedEvent createClassPathChangedEvent(File sourceFolder) throws IOException { Set files = new LinkedHashSet<>(); File file1 = createFile(sourceFolder, "File1"); File file2 = createFile(sourceFolder, "File2"); @@ -163,10 +155,8 @@ public class ClassPathChangeUploaderTests { return file; } - private ClassLoaderFiles deserialize(byte[] bytes) - throws IOException, ClassNotFoundException { - ObjectInputStream objectInputStream = new ObjectInputStream( - new ByteArrayInputStream(bytes)); + private ClassLoaderFiles deserialize(byte[] bytes) throws IOException, ClassNotFoundException { + ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); return (ClassLoaderFiles) objectInputStream.readObject(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index 5e9fde8b4b5..469b97b23bb 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,47 +71,42 @@ public class DelayedLiveReloadTriggerTests { MockitoAnnotations.initMocks(this); given(this.errorRequest.execute()).willReturn(this.errorResponse); given(this.okRequest.execute()).willReturn(this.okResponse); - given(this.errorResponse.getStatusCode()) - .willReturn(HttpStatus.INTERNAL_SERVER_ERROR); + given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK); - this.trigger = new DelayedLiveReloadTrigger(this.liveReloadServer, - this.requestFactory, URL); + this.trigger = new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, URL); } @Test public void liveReloadServerMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) .withMessageContaining("LiveReloadServer must not be null"); } @Test public void requestFactoryMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) .withMessageContaining("RequestFactory must not be null"); } @Test public void urlMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, - this.requestFactory, null)) + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)) .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeEmpty() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, - this.requestFactory, "")) + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")) .withMessageContaining("URL must not be empty"); } @Test public void triggerReloadOnStatus() throws Exception { - given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)) - .willThrow(new IOException()) + given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()) .willReturn(this.errorRequest, this.okRequest); long startTime = System.currentTimeMillis(); this.trigger.setTimings(10, 200, 30000); @@ -122,8 +117,7 @@ public class DelayedLiveReloadTriggerTests { @Test public void timeout() throws Exception { - given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)) - .willThrow(new IOException()); + given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()); this.trigger.setTimings(10, 0, 10); this.trigger.run(); verify(this.liveReloadServer, never()).triggerReload(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index 5efba2545fe..86c5e1c801f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,36 +73,31 @@ public class HttpHeaderInterceptorTests { @Test public void constructorNullHeaderName() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderInterceptor(null, this.value)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(null, this.value)) .withMessageContaining("Name must not be empty"); } @Test public void constructorEmptyHeaderName() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderInterceptor("", this.value)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor("", this.value)) .withMessageContaining("Name must not be empty"); } @Test public void constructorNullHeaderValue() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderInterceptor(this.name, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, null)) .withMessageContaining("Value must not be empty"); } @Test public void constructorEmptyHeaderValue() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderInterceptor(this.name, "")) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, "")) .withMessageContaining("Value must not be empty"); } @Test public void intercept() throws IOException { - ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, - this.execution); + ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, this.execution); assertThat(this.request.getHeaders().getFirst(this.name)).isEqualTo(this.value); assertThat(result).isEqualTo(this.response); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index cefe02f4576..e884fe5d0dd 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -101,8 +101,7 @@ public class RemoteClientConfigurationTests { @Test public void failIfNoSecret() { - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> configure("http://localhost", false)) + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> configure("http://localhost", false)) .withMessageContaining("required to secure your connection"); } @@ -112,8 +111,7 @@ public class RemoteClientConfigurationTests { Set changeSet = new HashSet<>(); ClassPathChangedEvent event = new ClassPathChangedEvent(this, changeSet, false); this.clientContext.publishEvent(event); - LiveReloadConfiguration configuration = this.clientContext - .getBean(LiveReloadConfiguration.class); + LiveReloadConfiguration configuration = this.clientContext.getBean(LiveReloadConfiguration.class); configuration.getExecutor().shutdown(); configuration.getExecutor().awaitTermination(2, TimeUnit.SECONDS); LiveReloadServer server = this.clientContext.getBean(LiveReloadServer.class); @@ -142,8 +140,7 @@ public class RemoteClientConfigurationTests { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(Config.class); if (setSecret) { - TestPropertyValues.of("spring.devtools.remote.secret:secret") - .applyTo(this.context); + TestPropertyValues.of("spring.devtools.remote.secret:secret").applyTo(this.context); } this.context.refresh(); this.clientContext = new AnnotationConfigApplicationContext(); @@ -151,11 +148,9 @@ public class RemoteClientConfigurationTests { new RestartScopeInitializer().initialize(this.clientContext); this.clientContext.register(ClientConfig.class, RemoteClientConfiguration.class); if (setSecret) { - TestPropertyValues.of("spring.devtools.remote.secret:secret") - .applyTo(this.clientContext); + TestPropertyValues.of("spring.devtools.remote.secret:secret").applyTo(this.clientContext); } - String remoteUrlProperty = "remoteUrl:" + remoteUrl + ":" - + this.context.getWebServer().getPort(); + String remoteUrlProperty = "remoteUrl:" + remoteUrl + ":" + this.context.getWebServer().getPort(); TestPropertyValues.of(remoteUrlProperty).applyTo(this.clientContext); this.clientContext.refresh(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index 54ff6f39827..7e2cf31db91 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,12 +98,10 @@ public class DispatcherFilterTests { public void handledByDispatcher() throws Exception { HttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); HttpServletResponse response = new MockHttpServletResponse(); - willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), - any(ServerHttpResponse.class)); + willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class)); this.filter.doFilter(request, response, this.chain); verifyZeroInteractions(this.chain); - verify(this.dispatcher).handle(this.serverRequestCaptor.capture(), - this.serverResponseCaptor.capture()); + verify(this.dispatcher).handle(this.serverRequestCaptor.capture(), this.serverResponseCaptor.capture()); ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue(); ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest; ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 5da6faa87fb..1f10d35be78 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,27 +73,23 @@ public class DispatcherTests { @Test public void accessManagerMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Dispatcher(null, Collections.emptyList())) + assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(null, Collections.emptyList())) .withMessageContaining("AccessManager must not be null"); } @Test public void mappersMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Dispatcher(this.accessManager, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(this.accessManager, null)) .withMessageContaining("Mappers must not be null"); } @Test public void accessManagerVetoRequest() throws Exception { - given(this.accessManager.isAllowed(any(ServerHttpRequest.class))) - .willReturn(false); + given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(false); HandlerMapper mapper = mock(HandlerMapper.class); Handler handler = mock(Handler.class); given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler); - Dispatcher dispatcher = new Dispatcher(this.accessManager, - Collections.singleton(mapper)); + Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper)); dispatcher.handle(this.serverRequest, this.serverResponse); verifyZeroInteractions(handler); assertThat(this.response.getStatus()).isEqualTo(403); @@ -101,23 +97,19 @@ public class DispatcherTests { @Test public void accessManagerAllowRequest() throws Exception { - given(this.accessManager.isAllowed(any(ServerHttpRequest.class))) - .willReturn(true); + given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(true); HandlerMapper mapper = mock(HandlerMapper.class); Handler handler = mock(Handler.class); given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler); - Dispatcher dispatcher = new Dispatcher(this.accessManager, - Collections.singleton(mapper)); + Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper)); dispatcher.handle(this.serverRequest, this.serverResponse); verify(handler).handle(this.serverRequest, this.serverResponse); } @Test public void ordersMappers() throws Exception { - HandlerMapper mapper1 = mock(HandlerMapper.class, - withSettings().extraInterfaces(Ordered.class)); - HandlerMapper mapper2 = mock(HandlerMapper.class, - withSettings().extraInterfaces(Ordered.class)); + HandlerMapper mapper1 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class)); + HandlerMapper mapper2 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) mapper1).getOrder()).willReturn(1); given(((Ordered) mapper2).getOrder()).willReturn(2); List mappers = Arrays.asList(mapper2, mapper1); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java index 63b61a3afd0..fd2eb4b55eb 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,29 +53,25 @@ public class HttpHeaderAccessManagerTests { @Test public void headerNameMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)) .withMessageContaining("HeaderName must not be empty"); } @Test public void headerNameMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)) .withMessageContaining("HeaderName must not be empty"); } @Test public void expectedSecretMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)) .withMessageContaining("ExpectedSecret must not be empty"); } @Test public void expectedSecretMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")) .withMessageContaining("ExpectedSecret must not be empty"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index d29e72d417c..c467dedb041 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,22 +40,19 @@ public class UrlHandlerMapperTests { @Test public void requestUriMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new UrlHandlerMapper(null, this.handler)) + assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper(null, this.handler)) .withMessageContaining("URL must not be empty"); } @Test public void requestUriMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new UrlHandlerMapper("", this.handler)) + assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("", this.handler)) .withMessageContaining("URL must not be empty"); } @Test public void requestUrlMustStartWithSlash() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler)) + assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler)) .withMessageContaining("URL must start with '/'"); } @@ -70,8 +67,7 @@ public class UrlHandlerMapperTests { @Test public void ignoresDifferentUrl() { UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler); - HttpServletRequest servletRequest = new MockHttpServletRequest("GET", - "/tunnel/other"); + HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel/other"); ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); assertThat(mapper.getHandler(request)).isNull(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java index 1bf089221d8..5328097fedc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java @@ -71,9 +71,8 @@ public class ChangeableUrlsTests { @Test public void skipsUrls() throws Exception { - ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), - makeUrl("spring-boot-autoconfigure"), makeUrl("spring-boot-actuator"), - makeUrl("spring-boot-starter"), + ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), makeUrl("spring-boot-autoconfigure"), + makeUrl("spring-boot-actuator"), makeUrl("spring-boot-starter"), makeUrl("spring-boot-starter-some-thing")); assertThat(urls).isEmpty(); } @@ -82,19 +81,16 @@ public class ChangeableUrlsTests { public void urlsFromJarClassPathAreConsidered() throws Exception { File relative = this.temporaryFolder.newFolder(); URL absoluteUrl = this.temporaryFolder.newFolder().toURI().toURL(); - File jarWithClassPath = makeJarFileWithUrlsInManifestClassPath( - "project-core/target/classes/", "project-web/target/classes/", - "does-not-exist/target/classes", relative.getName() + "/", absoluteUrl); - new File(jarWithClassPath.getParentFile(), "project-core/target/classes") - .mkdirs(); + File jarWithClassPath = makeJarFileWithUrlsInManifestClassPath("project-core/target/classes/", + "project-web/target/classes/", "does-not-exist/target/classes", relative.getName() + "/", absoluteUrl); + new File(jarWithClassPath.getParentFile(), "project-core/target/classes").mkdirs(); new File(jarWithClassPath.getParentFile(), "project-web/target/classes").mkdirs(); - ChangeableUrls urls = ChangeableUrls - .fromClassLoader(new URLClassLoader(new URL[] { - jarWithClassPath.toURI().toURL(), makeJarFileWithNoManifest() })); + ChangeableUrls urls = ChangeableUrls.fromClassLoader( + new URLClassLoader(new URL[] { jarWithClassPath.toURI().toURL(), makeJarFileWithNoManifest() })); assertThat(urls.toList()).containsExactly( new URL(jarWithClassPath.toURI().toURL(), "project-core/target/classes/"), - new URL(jarWithClassPath.toURI().toURL(), "project-web/target/classes/"), - relative.toURI().toURL(), absoluteUrl); + new URL(jarWithClassPath.toURI().toURL(), "project-web/target/classes/"), relative.toURI().toURL(), + absoluteUrl); } private URL makeUrl(String name) throws IOException { @@ -109,8 +105,7 @@ public class ChangeableUrlsTests { private File makeJarFileWithUrlsInManifestClassPath(Object... urls) throws Exception { File classpathJar = this.temporaryFolder.newFile("classpath.jar"); Manifest manifest = new Manifest(); - manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), - "1.0"); + manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); manifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), StringUtils.arrayToDelimitedString(urls, " ")); new JarOutputStream(new FileOutputStream(classpathJar), manifest).close(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java index 8828dbda417..7cdfcedc5f6 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Before public void setup() { this.files = new ClassLoaderFiles(); - this.resolver = new ClassLoaderFilesResourcePatternResolver( - new GenericApplicationContext(), this.files); + this.resolver = new ClassLoaderFilesResourcePatternResolver(new GenericApplicationContext(), this.files); } @Test @@ -81,8 +80,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Test public void getResourceWhenHasServletContextShouldReturnServletResource() { - GenericWebApplicationContext context = new GenericWebApplicationContext( - new MockServletContext()); + GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); Resource resource = this.resolver.getResource("index.html"); assertThat(resource).isNotNull().isInstanceOf(ServletContextResource.class); @@ -92,19 +90,16 @@ public class ClassLoaderFilesResourcePatternResolverTests { public void getResourceWhenDeletedShouldReturnDeletedResource() throws Exception { File folder = this.temp.newFolder(); File file = createFile(folder, "name.class"); - this.files.addFile(folder.getName(), "name.class", - new ClassLoaderFile(Kind.DELETED, null)); + this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null)); Resource resource = this.resolver.getResource("file:" + file.getAbsolutePath()); - assertThat(resource).isNotNull() - .isInstanceOf(DeletedClassLoaderFileResource.class); + assertThat(resource).isNotNull().isInstanceOf(DeletedClassLoaderFileResource.class); } @Test public void getResourcesShouldReturnResources() throws Exception { File folder = this.temp.newFolder(); createFile(folder, "name.class"); - Resource[] resources = this.resolver - .getResources("file:" + folder.getAbsolutePath() + "/**"); + Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**"); assertThat(resources).isNotEmpty(); } @@ -112,10 +107,8 @@ public class ClassLoaderFilesResourcePatternResolverTests { public void getResourcesWhenDeletedShouldFilterDeleted() throws Exception { File folder = this.temp.newFolder(); createFile(folder, "name.class"); - this.files.addFile(folder.getName(), "name.class", - new ClassLoaderFile(Kind.DELETED, null)); - Resource[] resources = this.resolver - .getResources("file:" + folder.getAbsolutePath() + "/**"); + this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null)); + Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**"); assertThat(resources).isEmpty(); } @@ -143,8 +136,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Test public void customResourceLoaderIsUsedInWebApplication() { - GenericWebApplicationContext context = new GenericWebApplicationContext( - new MockServletContext()); + GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); ResourceLoader resourceLoader = mock(ResourceLoader.class); context.setResourceLoader(resourceLoader); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); @@ -154,8 +146,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Test public void customProtocolResolverIsUsedInWebApplication() { - GenericWebApplicationContext context = new GenericWebApplicationContext( - new MockServletContext()); + GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); Resource resource = mock(Resource.class); ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource); context.addProtocolResolver(resolver); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java index e6c28ee14a0..f73fc5d9569 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,7 @@ public class DefaultRestartInitializerTests { @Test public void threadNotUsingAppClassLoader() { DefaultRestartInitializer initializer = new DefaultRestartInitializer(); - ClassLoader classLoader = new MockLauncherClassLoader( - getClass().getClassLoader()); + ClassLoader classLoader = new MockLauncherClassLoader(getClass().getClassLoader()); Thread thread = new Thread(); thread.setName("main"); thread.setContextClassLoader(classLoader); @@ -84,8 +83,7 @@ public class DefaultRestartInitializerTests { @Test public void urlsCanBeRetrieved() { - assertThat(new DefaultRestartInitializer().getUrls(Thread.currentThread())) - .isNotEmpty(); + assertThat(new DefaultRestartInitializer().getUrls(Thread.currentThread())).isNotEmpty(); } protected void testSkippedStacks(String s) { @@ -93,8 +91,7 @@ public class DefaultRestartInitializerTests { ClassLoader classLoader = new MockAppClassLoader(getClass().getClassLoader()); Thread thread = mock(Thread.class); thread.setName("main"); - StackTraceElement element = new StackTraceElement(s, "someMethod", "someFile", - 123); + StackTraceElement element = new StackTraceElement(s, "someMethod", "someFile", 123); given(thread.getStackTrace()).willReturn(new StackTraceElement[] { element }); given(thread.getContextClassLoader()).willReturn(classLoader); assertThat(initializer.getInitialUrls(thread)).isEqualTo(null); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 81ccc873d37..4ec8fd44dd2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,21 +53,18 @@ public class MainMethodTests { public void validMainMethod() throws Exception { MainMethod method = new TestThread(Valid::main).test(); assertThat(method.getMethod()).isEqualTo(this.actualMain); - assertThat(method.getDeclaringClassName()) - .isEqualTo(this.actualMain.getDeclaringClass().getName()); + assertThat(method.getDeclaringClassName()).isEqualTo(this.actualMain.getDeclaringClass().getName()); } @Test public void missingArgsMainMethod() throws Exception { - assertThatIllegalStateException() - .isThrownBy(() -> new TestThread(MissingArgs::main).test()) + assertThatIllegalStateException().isThrownBy(() -> new TestThread(MissingArgs::main).test()) .withMessageContaining("Unable to find main method"); } @Test public void nonStatic() throws Exception { - assertThatIllegalStateException() - .isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test()) + assertThatIllegalStateException().isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test()) .withMessageContaining("Unable to find main method"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java index b06d9988a91..3c13fe9f19c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,17 +60,16 @@ public class MockRestarter implements TestRule { private void setup() { Restarter.setInstance(this.mock); given(this.mock.getInitialUrls()).willReturn(new URL[] {}); - given(this.mock.getOrAddAttribute(anyString(), any(ObjectFactory.class))) - .willAnswer((invocation) -> { - String name = invocation.getArgument(0); - ObjectFactory factory = invocation.getArgument(1); - Object attribute = MockRestarter.this.attributes.get(name); - if (attribute == null) { - attribute = factory.getObject(); - MockRestarter.this.attributes.put(name, attribute); - } - return attribute; - }); + given(this.mock.getOrAddAttribute(anyString(), any(ObjectFactory.class))).willAnswer((invocation) -> { + String name = invocation.getArgument(0); + ObjectFactory factory = invocation.getArgument(1); + Object attribute = MockRestarter.this.attributes.get(name); + if (attribute == null) { + attribute = factory.getObject(); + MockRestarter.this.attributes.put(name, attribute); + } + return attribute; + }); given(this.mock.getThreadFactory()).willReturn(Thread::new); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java index 9725449c597..b3884f61cbc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java @@ -50,8 +50,7 @@ public class OnInitializedRestarterConditionTests { @Test public void noInstance() { Restarter.clearInstance(); - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isFalse(); context.close(); } @@ -59,8 +58,7 @@ public class OnInitializedRestarterConditionTests { @Test public void noInitialization() { Restarter.initialize(new String[0], false, RestartInitializer.NONE); - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isFalse(); context.close(); } @@ -80,8 +78,7 @@ public class OnInitializedRestarterConditionTests { RestartInitializer initializer = mock(RestartInitializer.class); given(initializer.getInitialUrls(any(Thread.class))).willReturn(new URL[0]); Restarter.initialize(new String[0], false, initializer); - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isTrue(); context.close(); synchronized (wait) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java index 3a75c3352b9..be36563c1cd 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java @@ -61,8 +61,7 @@ public class RestartApplicationListenerTests { @Test public void isHighestPriority() { - assertThat(new RestartApplicationListener().getOrder()) - .isEqualTo(Ordered.HIGHEST_PRECEDENCE); + assertThat(new RestartApplicationListener().getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test @@ -70,8 +69,7 @@ public class RestartApplicationListenerTests { testInitialize(false); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); - assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), - "rootContexts")).isNotEmpty(); + assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isNotEmpty(); } @Test @@ -79,8 +77,7 @@ public class RestartApplicationListenerTests { testInitialize(true); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); - assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), - "rootContexts")).isEmpty(); + assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isEmpty(); } @Test @@ -88,28 +85,23 @@ public class RestartApplicationListenerTests { System.setProperty(ENABLED_PROPERTY, "false"); testInitialize(false); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false); - assertThat(this.output.toString()) - .contains("Restart disabled due to System property"); + assertThat(this.output.toString()).contains("Restart disabled due to System property"); } private void testInitialize(boolean failed) { Restarter.clearInstance(); RestartApplicationListener listener = new RestartApplicationListener(); SpringApplication application = new SpringApplication(); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); listener.onApplicationEvent(new ApplicationStartingEvent(application, ARGS)); assertThat(Restarter.getInstance()).isNotEqualTo(nullValue()); assertThat(Restarter.getInstance().isFinished()).isFalse(); - listener.onApplicationEvent( - new ApplicationPreparedEvent(application, ARGS, context)); + listener.onApplicationEvent(new ApplicationPreparedEvent(application, ARGS, context)); if (failed) { - listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, - context, new RuntimeException())); + listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, context, new RuntimeException())); } else { - listener.onApplicationEvent( - new ApplicationReadyEvent(application, ARGS, context)); + listener.onApplicationEvent(new ApplicationReadyEvent(application, ARGS, context)); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java index 0ad953edc46..ac967a63871 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java @@ -70,8 +70,7 @@ public class RestartScopeInitializerTests { } - public static class ScopeTestBean - implements ApplicationListener { + public static class ScopeTestBean implements ApplicationListener { public ScopeTestBean() { createCount.incrementAndGet(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index c1dfa7bcbfb..e29f890a911 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -99,8 +99,7 @@ public class RestarterTests { @Test public void addUrlsMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> Restarter.getInstance().addUrls(null)) + assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addUrls(null)) .withMessageContaining("Urls must not be null"); } @@ -111,15 +110,13 @@ public class RestarterTests { Restarter restarter = Restarter.getInstance(); restarter.addUrls(urls); restarter.restart(); - ClassLoader classLoader = ((TestableRestarter) restarter) - .getRelaunchClassLoader(); + ClassLoader classLoader = ((TestableRestarter) restarter).getRelaunchClassLoader(); assertThat(((URLClassLoader) classLoader).getURLs()[0]).isEqualTo(url); } @Test public void addClassLoaderFilesMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null)) + assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null)) .withMessageContaining("ClassLoaderFiles must not be null"); } @@ -130,8 +127,7 @@ public class RestarterTests { Restarter restarter = Restarter.getInstance(); restarter.addClassLoaderFiles(classLoaderFiles); restarter.restart(); - ClassLoader classLoader = ((TestableRestarter) restarter) - .getRelaunchClassLoader(); + ClassLoader classLoader = ((TestableRestarter) restarter).getRelaunchClassLoader(); assertThat(classLoader.getResourceAsStream("f")).hasContent("abc"); } @@ -217,8 +213,7 @@ public class RestarterTests { } - private static class CloseCountingApplicationListener - implements ApplicationListener { + private static class CloseCountingApplicationListener implements ApplicationListener { static int closed = 0; @@ -234,12 +229,11 @@ public class RestarterTests { private ClassLoader relaunchClassLoader; TestableRestarter() { - this(Thread.currentThread(), new String[] {}, false, - new MockRestartInitializer()); + this(Thread.currentThread(), new String[] {}, false, new MockRestartInitializer()); } - protected TestableRestarter(Thread thread, String[] args, - boolean forceReferenceCleanup, RestartInitializer initializer) { + protected TestableRestarter(Thread thread, String[] args, boolean forceReferenceCleanup, + RestartInitializer initializer) { super(thread, args, forceReferenceCleanup, initializer); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java index f5767346479..75cae415fff 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,8 +81,7 @@ public class SilentExitExceptionHandlerTests { private Throwable thrown; TestThread() { - setUncaughtExceptionHandler( - (thread, exception) -> TestThread.this.thrown = exception); + setUncaughtExceptionHandler((thread, exception) -> TestThread.this.thrown = exception); } public Throwable getThrown() { @@ -96,8 +95,7 @@ public class SilentExitExceptionHandlerTests { } - private static class TestSilentExitExceptionHandler - extends SilentExitExceptionHandler { + private static class TestSilentExitExceptionHandler extends SilentExitExceptionHandler { private boolean nonZeroExitCodePrevented; diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java index 9586f4d3f3d..92efe43758d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,29 +34,25 @@ public class ClassLoaderFileTests { @Test public void kindMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassLoaderFile(null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(null, null)) .withMessageContaining("Kind must not be null"); } @Test public void addedContentsMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) .withMessageContaining("Contents must not be null"); } @Test public void modifiedContentsMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) .withMessageContaining("Contents must not be null"); } @Test public void deletedContentsMustBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) + assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) .withMessageContaining("Contents must be null"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index f294a2ad394..41f36677645 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,15 +42,13 @@ public class ClassLoaderFilesTests { @Test public void addFileNameMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class))) + assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class))) .withMessageContaining("Name must not be null"); } @Test public void addFileFileMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.files.addFile("test", null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile("test", null)) .withMessageContaining("File must not be null"); } @@ -87,10 +85,8 @@ public class ClassLoaderFilesTests { this.files.addFile("a", "myfile", file1); this.files.addFile("b", "myfile", file2); assertThat(this.files.getFile("myfile")).isEqualTo(file2); - assertThat(this.files.getOrCreateSourceFolder("a").getFiles().size()) - .isEqualTo(0); - assertThat(this.files.getOrCreateSourceFolder("b").getFiles().size()) - .isEqualTo(1); + assertThat(this.files.getOrCreateSourceFolder("a").getFiles().size()).isEqualTo(0); + assertThat(this.files.getOrCreateSourceFolder("b").getFiles().size()).isEqualTo(1); } @Test @@ -121,8 +117,7 @@ public class ClassLoaderFilesTests { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this.files); oos.close(); - ObjectInputStream ois = new ObjectInputStream( - new ByteArrayInputStream(bos.toByteArray())); + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); ClassLoaderFiles readObject = (ClassLoaderFiles) ois.readObject(); assertThat(readObject.getFile("myfile")).isNotNull(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 9d133d77535..4adb545d2e2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException @SuppressWarnings("resource") public class RestartClassLoaderTests { - private static final String PACKAGE = RestartClassLoaderTests.class.getPackage() - .getName(); + private static final String PACKAGE = RestartClassLoaderTests.class.getPackage().getName(); private static final String PACKAGE_PATH = PACKAGE.replace('.', '/'); @@ -74,8 +73,7 @@ public class RestartClassLoaderTests { URL[] urls = new URL[] { url }; this.parentClassLoader = new URLClassLoader(urls, classLoader); this.updatedFiles = new ClassLoaderFiles(); - this.reloadClassLoader = new RestartClassLoader(this.parentClassLoader, urls, - this.updatedFiles); + this.reloadClassLoader = new RestartClassLoader(this.parentClassLoader, urls, this.updatedFiles); } private File createSampleJarFile() throws IOException { @@ -93,36 +91,32 @@ public class RestartClassLoaderTests { @Test public void parentMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RestartClassLoader(null, new URL[] {})) + assertThatIllegalArgumentException().isThrownBy(() -> new RestartClassLoader(null, new URL[] {})) .withMessageContaining("Parent must not be null"); } @Test public void updatedFilesMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) .withMessageContaining("UpdatedFiles must not be null"); } @Test public void getResourceFromReloadableUrl() throws Exception { - String content = readString( - this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt")); + String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt")); assertThat(content).startsWith("fromchild"); } @Test public void getResourceFromParent() throws Exception { - String content = readString( - this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt")); + String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt")); assertThat(content).startsWith("fromparent"); } @Test public void getResourcesFiltersDuplicates() throws Exception { - List resources = toList( - this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt")); + List resources = toList(this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt")); assertThat(resources.size()).isEqualTo(1); } @@ -175,8 +169,7 @@ public class RestartClassLoaderTests { byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); List resources = toList(this.reloadClassLoader.getResources(name)); - assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream())) - .isEqualTo(bytes); + assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream())).isEqualTo(bytes); } @Test @@ -198,8 +191,7 @@ public class RestartClassLoaderTests { @Test public void getAddedClass() throws Exception { String name = PACKAGE_PATH + "/SampleParent.class"; - byte[] bytes = FileCopyUtils - .copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); + byte[] bytes = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.ADDED, bytes)); Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent"); assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader); @@ -210,8 +202,7 @@ public class RestartClassLoaderTests { } private List toList(Enumeration enumeration) { - return (enumeration != null) ? Collections.list(enumeration) - : Collections.emptyList(); + return (enumeration != null) ? Collections.list(enumeration) : Collections.emptyList(); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java index a4b54c3e7fa..b22001a2a3f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,17 +71,13 @@ public class DefaultSourceFolderUrlFilterTests { @Test public void skippedProjects() throws Exception { - String sourceFolder = "/Users/me/code/spring-boot-samples/" - + "spring-boot-sample-devtools"; - URL jarUrl = new URL("jar:file:/Users/me/tmp/" - + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/"); + String sourceFolder = "/Users/me/code/spring-boot-samples/" + "spring-boot-sample-devtools"; + URL jarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/"); assertThat(this.filter.isMatch(sourceFolder, jarUrl)).isTrue(); - URL nestedJarUrl = new URL("jar:file:/Users/me/tmp/" - + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/" + URL nestedJarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/" + "lib/spring-boot-1.3.0.BUILD-SNAPSHOT.jar!/"); assertThat(this.filter.isMatch(sourceFolder, nestedJarUrl)).isFalse(); - URL fileUrl = new URL("file:/Users/me/tmp/" - + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar"); + URL fileUrl = new URL("file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar"); assertThat(this.filter.isMatch(sourceFolder, fileUrl)).isTrue(); } @@ -92,14 +88,12 @@ public class DefaultSourceFolderUrlFilterTests { doTest(sourcePostfix, "my-module.other", false); } - private void doTest(String sourcePostfix, String moduleRoot, boolean expected) - throws MalformedURLException { + private void doTest(String sourcePostfix, String moduleRoot, boolean expected) throws MalformedURLException { String sourceFolder = SOURCE_ROOT + sourcePostfix; for (String postfix : COMMON_POSTFIXES) { for (URL url : getUrls(moduleRoot + postfix)) { boolean match = this.filter.isMatch(sourceFolder, url); - assertThat(match).as(url + " against " + sourceFolder) - .isEqualTo(expected); + assertThat(match).as(url + " against " + sourceFolder).isEqualTo(expected); } } } @@ -109,10 +103,8 @@ public class DefaultSourceFolderUrlFilterTests { urls.add(new URL("file:/some/path/" + name)); urls.add(new URL("file:/some/path/" + name + "!/")); for (String postfix : COMMON_POSTFIXES) { - urls.add(new URL( - "jar:file:/some/path/lib-module" + postfix + "!/lib/" + name)); - urls.add(new URL( - "jar:file:/some/path/lib-module" + postfix + "!/lib/" + name + "!/")); + urls.add(new URL("jar:file:/some/path/lib-module" + postfix + "!/lib/" + name)); + urls.add(new URL("jar:file:/some/path/lib-module" + postfix + "!/lib/" + name + "!/")); } return urls; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java index 18db9469c34..af490979a1b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ public class HttpRestartServerHandlerTests { @Test public void serverMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpRestartServerHandler(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServerHandler(null)) .withMessageContaining("Server must not be null"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index e632b2987a7..52988b8d60e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,15 +63,13 @@ public class HttpRestartServerTests { @Test public void sourceFolderUrlFilterMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpRestartServer((SourceFolderUrlFilter) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((SourceFolderUrlFilter) null)) .withMessageContaining("SourceFolderUrlFilter must not be null"); } @Test public void restartServerMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpRestartServer((RestartServer) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((RestartServer) null)) .withMessageContaining("RestartServer must not be null"); } @@ -83,8 +81,7 @@ public class HttpRestartServerTests { files.addFile("name", new ClassLoaderFile(Kind.ADDED, new byte[0])); byte[] bytes = serialize(files); request.setContent(bytes); - this.server.handle(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response)); + this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verify(this.delegate).updateAndRestart(this.filesCaptor.capture()); assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull(); assertThat(response.getStatus()).isEqualTo(200); @@ -94,8 +91,7 @@ public class HttpRestartServerTests { public void sendNoContent() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - this.server.handle(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response)); + this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verifyZeroInteractions(this.delegate); assertThat(response.getStatus()).isEqualTo(500); @@ -106,8 +102,7 @@ public class HttpRestartServerTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(new byte[] { 0, 0, 0 }); - this.server.handle(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response)); + this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verifyZeroInteractions(this.delegate); assertThat(response.getStatus()).isEqualTo(500); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index 399ade2990c..c53ffd1aea8 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class RestartServerTests { @Test public void sourceFolderUrlFilterMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RestartServer((SourceFolderUrlFilter) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RestartServer((SourceFolderUrlFilter) null)) .withMessageContaining("SourceFolderUrlFilter must not be null"); } @@ -60,8 +59,7 @@ public class RestartServerTests { URL url3 = new URL("file:/proj/module-c.jar!/"); URL url4 = new URL("file:/proj/module-d.jar!/"); URLClassLoader classLoaderA = new URLClassLoader(new URL[] { url1, url2 }); - URLClassLoader classLoaderB = new URLClassLoader(new URL[] { url3, url4 }, - classLoaderA); + URLClassLoader classLoaderB = new URLClassLoader(new URL[] { url3, url4 }, classLoaderA); SourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter(); MockRestartServer server = new MockRestartServer(filter, classLoaderB); ClassLoaderFiles files = new ClassLoaderFiles(); @@ -114,8 +112,7 @@ public class RestartServerTests { private static class MockRestartServer extends RestartServer { - MockRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, - ClassLoader classLoader) { + MockRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, ClassLoader classLoader) { super(sourceFolderUrlFilter, classLoader); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java index 4d248018d5f..d9840ab3786 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,13 +36,11 @@ public class DevToolsSettingsTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private static final String ROOT = DevToolsSettingsTests.class.getPackage().getName() - .replace('.', '/') + "/"; + private static final String ROOT = DevToolsSettingsTests.class.getPackage().getName().replace('.', '/') + "/"; @Test public void includePatterns() throws Exception { - DevToolsSettings settings = DevToolsSettings - .load(ROOT + "spring-devtools-include.properties"); + DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-include.properties"); assertThat(settings.isRestartInclude(new URL("file://test/a"))).isTrue(); assertThat(settings.isRestartInclude(new URL("file://test/b"))).isTrue(); assertThat(settings.isRestartInclude(new URL("file://test/c"))).isFalse(); @@ -50,8 +48,7 @@ public class DevToolsSettingsTests { @Test public void excludePatterns() throws Exception { - DevToolsSettings settings = DevToolsSettings - .load(ROOT + "spring-devtools-exclude.properties"); + DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-exclude.properties"); assertThat(settings.isRestartExclude(new URL("file://test/a"))).isTrue(); assertThat(settings.isRestartExclude(new URL("file://test/b"))).isTrue(); assertThat(settings.isRestartExclude(new URL("file://test/c"))).isFalse(); @@ -61,12 +58,10 @@ public class DevToolsSettingsTests { public void defaultIncludePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings.get(); assertThat(settings.isRestartExclude(makeUrl("spring-boot"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))) - .isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))).isTrue(); assertThat(settings.isRestartExclude(makeUrl("spring-boot-actuator"))).isTrue(); assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))) - .isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))).isTrue(); } private URL makeUrl(String name) throws IOException { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java index fe2017215c9..f2ce9e8b458 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { private List executedRequests = new ArrayList<>(); @Override - public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) - throws IOException { + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { return new MockRequest(uri, httpMethod); } @@ -97,8 +96,7 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { if (response == null) { response = new Response(0, null, HttpStatus.GONE); } - return ((Response) response) - .asHttpResponse(MockClientHttpRequestFactory.this.seq); + return ((Response) response).asHttpResponse(MockClientHttpRequestFactory.this.seq); } } @@ -123,10 +121,8 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { waitForDelay(); if (this.payload != null) { httpResponse.getHeaders().setContentLength(this.payload.length); - httpResponse.getHeaders() - .setContentType(MediaType.APPLICATION_OCTET_STREAM); - httpResponse.getHeaders().add("x-seq", - Long.toString(seq.incrementAndGet())); + httpResponse.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM); + httpResponse.getHeaders().add("x-seq", Long.toString(seq.incrementAndGet())); } return httpResponse; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index 9b3b4604512..d045629df29 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -76,29 +76,26 @@ public class HttpTunnelConnectionTests { @Test public void urlMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeMalformed() { - assertThatIllegalArgumentException().isThrownBy( - () -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test public void requestFactoryMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelConnection(this.url, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(this.url, null)) .withMessageContaining("RequestFactory must not be null"); } @@ -148,8 +145,7 @@ public class HttpTunnelConnectionTests { this.requestFactory.willRespond(new ConnectException()); TunnelChannel tunnel = openTunnel(true); assertThat(tunnel.isOpen()).isFalse(); - this.outputCapture.expect(containsString( - "Failed to connect to remote application at http://localhost:12345")); + this.outputCapture.expect(containsString("Failed to connect to remote application at http://localhost:12345")); } private void write(TunnelChannel channel, String string) throws IOException { @@ -157,8 +153,8 @@ public class HttpTunnelConnectionTests { } private TunnelChannel openTunnel(boolean singleThreaded) throws Exception { - HttpTunnelConnection connection = new HttpTunnelConnection(this.url, - this.requestFactory, singleThreaded ? new CurrentThreadExecutor() : null); + HttpTunnelConnection connection = new HttpTunnelConnection(this.url, this.requestFactory, + singleThreaded ? new CurrentThreadExecutor() : null); return connection.open(this.incomingChannel, this.closeable); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index 4a8f4a2cfd3..d953df5d14c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ public class TunnelClientTests { @Test public void listenPortMustNotBeNegative() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection)) + assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection)) .withMessageContaining("ListenPort must be greater than or equal to 0"); } @@ -117,8 +116,7 @@ public class TunnelClientTests { private int openedTimes; @Override - public WritableByteChannel open(WritableByteChannel incomingChannel, - Closeable closeable) { + public WritableByteChannel open(WritableByteChannel incomingChannel, Closeable closeable) { this.openedTimes++; this.open = true; return new TunnelChannel(incomingChannel, closeable); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java index 5f77f9f17d1..3b104b08bca 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class HttpTunnelPayloadForwarderTests { @Test public void targetChannelMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelPayloadForwarder(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayloadForwarder(null)) .withMessageContaining("TargetChannel must not be null"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index 8340d01bac4..436f9f970e5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,15 +50,13 @@ public class HttpTunnelPayloadTests { @Test public void sequenceMustBePositive() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1))) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1))) .withMessageContaining("Sequence must be positive"); } @Test public void dataMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelPayload(1, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(1, null)) .withMessageContaining("Data must not be null"); } @@ -116,8 +114,7 @@ public class HttpTunnelPayloadTests { @Test public void getPayloadData() throws Exception { - ReadableByteChannel channel = Channels - .newChannel(new ByteArrayInputStream("hello".getBytes())); + ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream("hello".getBytes())); ByteBuffer payloadData = HttpTunnelPayload.getPayloadData(channel); ByteArrayOutputStream out = new ByteArrayOutputStream(); WritableByteChannel writeChannel = Channels.newChannel(out); @@ -130,8 +127,7 @@ public class HttpTunnelPayloadTests { @Test public void getPayloadDataWithTimeout() throws Exception { ReadableByteChannel channel = mock(ReadableByteChannel.class); - given(channel.read(any(ByteBuffer.class))) - .willThrow(new SocketTimeoutException()); + given(channel.read(any(ByteBuffer.class))).willThrow(new SocketTimeoutException()); ByteBuffer payload = HttpTunnelPayload.getPayloadData(channel); assertThat(payload).isNull(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java index 77b95a6177f..fba704a402f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ public class HttpTunnelServerHandlerTests { @Test public void serverMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelServerHandler(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServerHandler(null)) .withMessageContaining("Server must not be null"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index d8cf315ddcf..f7ee4d6cb48 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -119,8 +119,7 @@ public class HttpTunnelServerTests { @Test public void longPollTimeoutMustBePositiveValue() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.server.setLongPollTimeout(0)) + assertThatIllegalArgumentException().isThrownBy(() -> this.server.setLongPollTimeout(0)) .withMessageContaining("LongPollTimeout must be a positive value"); } @@ -252,8 +251,7 @@ public class HttpTunnelServerTests { @Test public void disconnectTimeoutMustBePositive() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.server.setDisconnectTimeout(0)) + assertThatIllegalArgumentException().isThrownBy(() -> this.server.setDisconnectTimeout(0)) .withMessageContaining("DisconnectTimeout must be a positive value"); } @@ -294,11 +292,9 @@ public class HttpTunnelServerTests { testHttpConnectionNonAsync(100); } - private void testHttpConnectionNonAsync(long sleepBeforeResponse) - throws IOException, InterruptedException { + private void testHttpConnectionNonAsync(long sleepBeforeResponse) throws IOException, InterruptedException { ServerHttpRequest request = mock(ServerHttpRequest.class); - given(request.getAsyncRequestControl(this.response)) - .willThrow(new IllegalArgumentException()); + given(request.getAsyncRequestControl(this.response)).willThrow(new IllegalArgumentException()); final HttpConnection connection = new HttpConnection(request, this.response); final AtomicBoolean responded = new AtomicBoolean(); Thread connectionThread = new Thread(() -> { @@ -366,8 +362,7 @@ public class HttpTunnelServerTests { @Override public int read(ByteBuffer dst) throws IOException { try { - ByteBuffer bytes = this.outgoing.pollFirst(this.timeout, - TimeUnit.MILLISECONDS); + ByteBuffer bytes = this.outgoing.pollFirst(this.timeout, TimeUnit.MILLISECONDS); if (bytes == null) { throw new SocketTimeoutException(); } @@ -437,17 +432,14 @@ public class HttpTunnelServerTests { } public MockHttpServletRequest getServletRequest() { - return (MockHttpServletRequest) ((ServletServerHttpRequest) getRequest()) - .getServletRequest(); + return (MockHttpServletRequest) ((ServletServerHttpRequest) getRequest()).getServletRequest(); } public MockHttpServletResponse getServletResponse() { - return (MockHttpServletResponse) ((ServletServerHttpResponse) getResponse()) - .getServletResponse(); + return (MockHttpServletResponse) ((ServletServerHttpResponse) getResponse()).getServletResponse(); } - public void verifyReceived(String expectedContent, int expectedSeq) - throws Exception { + public void verifyReceived(String expectedContent, int expectedSeq) throws Exception { waitForServletResponse(); MockHttpServletResponse resp = getServletResponse(); assertThat(resp.getContentAsString()).isEqualTo(expectedContent); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index 64c4dc6c029..47c4eb0953d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -75,8 +75,7 @@ public class SocketTargetServerConnectionTests { this.server.start(); ByteChannel channel = this.connection.open(10); long startTime = System.currentTimeMillis(); - assertThatExceptionOfType(SocketTimeoutException.class) - .isThrownBy(() -> channel.read(ByteBuffer.allocate(5))) + assertThatExceptionOfType(SocketTimeoutException.class).isThrownBy(() -> channel.read(ByteBuffer.allocate(5))) .satisfies((ex) -> { long runTime = System.currentTimeMillis() - startTime; assertThat(runTime).isGreaterThanOrEqualTo(10L); @@ -149,8 +148,7 @@ public class SocketTargetServerConnectionTests { } } if (MockServer.this.expect != null) { - ByteBuffer buffer = ByteBuffer - .allocate(MockServer.this.expect.length); + ByteBuffer buffer = ByteBuffer.allocate(MockServer.this.expect.length); while (buffer.hasRemaining()) { channel.read(buffer); } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/ExitCodeApplication.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/ExitCodeApplication.java index 2b8a47415d1..813c6ed0928 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/ExitCodeApplication.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/ExitCodeApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class ExitCodeApplication { } public static void main(String[] args) { - System.exit(SpringApplication - .exit(SpringApplication.run(ExitCodeApplication.class, args))); + System.exit(SpringApplication.exit(SpringApplication.run(ExitCodeApplication.class, args))); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/cloudfoundry/CloudFoundryCustomContextPathExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/cloudfoundry/CloudFoundryCustomContextPathExample.java index 4be703c6878..d1cbc15d5e4 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/cloudfoundry/CloudFoundryCustomContextPathExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/cloudfoundry/CloudFoundryCustomContextPathExample.java @@ -50,14 +50,12 @@ public class CloudFoundryCustomContextPathExample { return new TomcatServletWebServerFactory() { @Override - protected void prepareContext(Host host, - ServletContextInitializer[] initializers) { + protected void prepareContext(Host host, ServletContextInitializer[] initializers) { super.prepareContext(host, initializers); StandardContext child = new StandardContext(); child.addLifecycleListener(new Tomcat.FixContextListener()); child.setPath("/cloudfoundryapplication"); - ServletContainerInitializer initializer = getServletContextInitializer( - getContextPath()); + ServletContainerInitializer initializer = getServletContextInitializer(getContextPath()); child.addServletContainerInitializer(initializer, Collections.emptySet()); child.setCrossContext(true); host.addChild(child); @@ -71,12 +69,9 @@ public class CloudFoundryCustomContextPathExample { Servlet servlet = new GenericServlet() { @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { - ServletContext context = req.getServletContext() - .getContext(contextPath); - context.getRequestDispatcher("/cloudfoundryapplication").forward(req, - res); + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { + ServletContext context = req.getServletContext().getContext(contextPath); + context.getRequestDispatcher("/cloudfoundryapplication").forward(req, res); } }; diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExample.java index f28dc5f24bd..2bfef078e9e 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { Resource path = new ClassPathResource("com/example/myapp/config.yml"); PropertySource propertySource = loadYaml(path); environment.getPropertySources().addLast(propertySource); @@ -52,8 +51,7 @@ public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor return this.loader.load("custom-resource", path).get(0); } catch (IOException ex) { - throw new IllegalStateException( - "Failed to load yaml configuration from " + path, ex); + throw new IllegalStateException("Failed to load yaml configuration from " + path, ex); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExample.java index 6d5a07313ac..2e2b5a5ed6f 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExample.java @@ -39,8 +39,8 @@ public class TomcatLegacyCookieProcessorExample { // tag::customizer[] @Bean public WebServerFactoryCustomizer cookieProcessorCustomizer() { - return (factory) -> factory.addContextCustomizers( - (context) -> context.setCookieProcessor(new LegacyCookieProcessor())); + return (factory) -> factory + .addContextCustomizers((context) -> context.setCookieProcessor(new LegacyCookieProcessor())); } // end::customizer[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/elasticsearch/HibernateSearchElasticsearchExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/elasticsearch/HibernateSearchElasticsearchExample.java index fdabab872c3..f216a1d9e53 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/elasticsearch/HibernateSearchElasticsearchExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/elasticsearch/HibernateSearchElasticsearchExample.java @@ -35,8 +35,7 @@ public class HibernateSearchElasticsearchExample { * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean. */ @Configuration(proxyBeanMethods = false) - static class ElasticsearchJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + static class ElasticsearchJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { ElasticsearchJpaDependencyConfiguration() { super("elasticsearchClient"); diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExample.java index 3a943558ab5..3342b0b72f5 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExample.java @@ -51,8 +51,7 @@ public class CompleteTwoDataSourcesExample { @Primary @ConfigurationProperties("app.datasource.first.configuration") public HikariDataSource firstDataSource() { - return firstDataSourceProperties().initializeDataSourceBuilder() - .type(HikariDataSource.class).build(); + return firstDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean @@ -64,8 +63,7 @@ public class CompleteTwoDataSourcesExample { @Bean @ConfigurationProperties("app.datasource.second.configuration") public BasicDataSource secondDataSource() { - return secondDataSourceProperties().initializeDataSourceBuilder() - .type(BasicDataSource.class).build(); + return secondDataSourceProperties().initializeDataSourceBuilder().type(BasicDataSource.class).build(); } // end::configuration[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExample.java index 88a8a7a74ed..6630a0160d5 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExample.java @@ -51,8 +51,7 @@ public class ConfigurableDataSourceExample { @Bean @ConfigurationProperties("app.datasource.configuration") public HikariDataSource dataSource(DataSourceProperties properties) { - return properties.initializeDataSourceBuilder().type(HikariDataSource.class) - .build(); + return properties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } // end::configuration[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExample.java index 19f075b5da7..a56f34f2653 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExample.java @@ -54,8 +54,7 @@ public class SimpleTwoDataSourcesExample { @Primary @ConfigurationProperties("app.datasource.first.configuration") public HikariDataSource firstDataSource() { - return firstDataSourceProperties().initializeDataSourceBuilder() - .type(HikariDataSource.class).build(); + return firstDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jersey/JerseySetStatusOverSendErrorExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jersey/JerseySetStatusOverSendErrorExample.java index b8d1c18dd5f..0874f9f0e7c 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jersey/JerseySetStatusOverSendErrorExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jersey/JerseySetStatusOverSendErrorExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public class JerseySetStatusOverSendErrorExample { public JerseyConfig() { register(Endpoint.class); - setProperties(Collections.singletonMap( - "jersey.config.server.response.setStatusOverSendError", true)); + setProperties(Collections.singletonMap("jersey.config.server.response.setStatusOverSendError", true)); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jpa/HibernateSecondLevelCacheExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jpa/HibernateSecondLevelCacheExample.java index 2a45308abf1..5420a1f71b9 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jpa/HibernateSecondLevelCacheExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/jpa/HibernateSecondLevelCacheExample.java @@ -33,10 +33,8 @@ import org.springframework.context.annotation.Configuration; public class HibernateSecondLevelCacheExample { @Bean - public HibernatePropertiesCustomizer hibernateSecondLevelCacheCustomizer( - JCacheCacheManager cacheManager) { - return (properties) -> properties.put(ConfigSettings.CACHE_MANAGER, - cacheManager.getCacheManager()); + public HibernatePropertiesCustomizer hibernateSecondLevelCacheCustomizer(JCacheCacheManager cacheManager) { + return (properties) -> properties.put(ConfigSettings.CACHE_MANAGER, cacheManager.getCacheManager()); } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/AdvancedConfigurationExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/AdvancedConfigurationExample.java index 5e9c12ca440..cc89f3a3d5e 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/AdvancedConfigurationExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/AdvancedConfigurationExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ public class AdvancedConfigurationExample { // tag::configuration[] @TestConfiguration - public static class CustomizationConfiguration - implements RestDocsRestAssuredConfigurationCustomizer { + public static class CustomizationConfiguration implements RestDocsRestAssuredConfigurationCustomizer { @Override public void customize(RestAssuredRestDocumentationConfigurer configurer) { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java index 1362e867023..8bd79db7d25 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java @@ -45,8 +45,8 @@ public class UserDocumentationTests { @Test public void listUsers() { - given(this.documentationSpec).filter(document("list-users")).when() - .port(this.port).get("/").then().assertThat().statusCode(is(200)); + given(this.documentationSpec).filter(document("list-users")).when().port(this.port).get("/").then().assertThat() + .statusCode(is(200)); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/AdvancedConfigurationExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/AdvancedConfigurationExample.java index 9ba19539f88..3491726cb27 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/AdvancedConfigurationExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/AdvancedConfigurationExample.java @@ -24,8 +24,7 @@ public class AdvancedConfigurationExample { // tag::configuration[] @TestConfiguration - public static class CustomizationConfiguration - implements RestDocsWebTestClientConfigurationCustomizer { + public static class CustomizationConfiguration implements RestDocsWebTestClientConfigurationCustomizer { @Override public void customize(WebTestClientRestDocumentationConfigurer configurer) { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java index 25d1ee9db98..c5eb5333e7f 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class MockMvcExampleTests { @Test public void exampleTest() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Hello World")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World")); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java index 90314b89a03..52c21abf449 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,8 @@ public class MockWebTestClientExampleTests { @Test public void exampleTest() { - this.webClient.get().uri("/").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("Hello World"); + this.webClient.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) + .isEqualTo("Hello World"); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java index 8a0376cf919..f24b46815ef 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ public class RandomPortWebTestClientExampleTests { @Test public void exampleTest() { - this.webClient.get().uri("/").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("Hello World"); + this.webClient.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) + .isEqualTo("Hello World"); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/client/RestTemplateProxyCustomizationExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/client/RestTemplateProxyCustomizationExample.java index cfcecde2276..ae9a13c66f5 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/client/RestTemplateProxyCustomizationExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/client/RestTemplateProxyCustomizationExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,22 +45,19 @@ public class RestTemplateProxyCustomizationExample { @Override public void customize(RestTemplate restTemplate) { HttpHost proxy = new HttpHost("proxy.example.com"); - HttpClient httpClient = HttpClientBuilder.create() - .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { + HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { - @Override - public HttpHost determineProxy(HttpHost target, - HttpRequest request, HttpContext context) - throws HttpException { - if (target.getHostName().equals("192.168.0.5")) { - return null; - } - return super.determineProxy(target, request, context); - } + @Override + public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) + throws HttpException { + if (target.getHostName().equals("192.168.0.5")) { + return null; + } + return super.determineProxy(target, request, context); + } - }).build(); - restTemplate.setRequestFactory( - new HttpComponentsClientHttpRequestFactory(httpClient)); + }).build(); + restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java index 2502c83d5cf..f56982b2d4a 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java @@ -60,12 +60,10 @@ public class UserServiceAutoConfigurationTests { // tag::test-user-config[] @Test public void defaultServiceBacksOff() { - this.contextRunner.withUserConfiguration(UserConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(UserService.class); - assertThat(context).getBean("myUserService") - .isSameAs(context.getBean(UserService.class)); - }); + this.contextRunner.withUserConfiguration(UserConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(UserService.class); + assertThat(context).getBean("myUserService").isSameAs(context.getBean(UserService.class)); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java index 809d886d531..f948ce9d947 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class EnvironmentPostProcessorExampleTests { @Test public void applyEnvironmentPostProcessor() { assertThat(this.environment.containsProperty("test.foo.bar")).isFalse(); - new EnvironmentPostProcessorExample().postProcessEnvironment(this.environment, - new SpringApplication()); + new EnvironmentPostProcessorExample().postProcessEnvironment(this.environment, new SpringApplication()); assertThat(this.environment.containsProperty("test.foo.bar")).isTrue(); assertThat(this.environment.getProperty("test.foo.bar")).isEqualTo("value"); } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java index 361f5af1d3e..4f0345d39eb 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java @@ -42,10 +42,9 @@ public class TomcatLegacyCookieProcessorExampleTests { public void cookieProcessorIsCustomized() { ServletWebServerApplicationContext applicationContext = (ServletWebServerApplicationContext) new SpringApplication( TestConfiguration.class, LegacyCookieProcessorConfiguration.class).run(); - Context context = (Context) ((TomcatWebServer) applicationContext.getWebServer()) - .getTomcat().getHost().findChildren()[0]; - assertThat(context.getCookieProcessor()) - .isInstanceOf(LegacyCookieProcessor.class); + Context context = (Context) ((TomcatWebServer) applicationContext.getWebServer()).getTomcat().getHost() + .findChildren()[0]; + assertThat(context.getCookieProcessor()).isInstanceOf(LegacyCookieProcessor.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java index 8bcad2d9281..50f892f3494 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java @@ -41,43 +41,32 @@ public class AppSystemPropertiesTests { @Test public void bindWithDefaultUnit() { - this.contextRunner - .withPropertyValues("app.system.session-timeout=40", - "app.system.read-timeout=5000") + this.contextRunner.withPropertyValues("app.system.session-timeout=40", "app.system.read-timeout=5000") .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()) - .isEqualTo(Duration.ofSeconds(40)); - assertThat(properties.getReadTimeout()) - .isEqualTo(Duration.ofMillis(5000)); + assertThat(properties.getSessionTimeout()).isEqualTo(Duration.ofSeconds(40)); + assertThat(properties.getReadTimeout()).isEqualTo(Duration.ofMillis(5000)); })); } @Test public void bindWithExplicitUnit() { - this.contextRunner.withPropertyValues("app.system.session-timeout=1h", - "app.system.read-timeout=5s").run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()) - .isEqualTo(Duration.ofMinutes(60)); - assertThat(properties.getReadTimeout()) - .isEqualTo(Duration.ofMillis(5000)); + this.contextRunner.withPropertyValues("app.system.session-timeout=1h", "app.system.read-timeout=5s") + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).isEqualTo(Duration.ofMinutes(60)); + assertThat(properties.getReadTimeout()).isEqualTo(Duration.ofMillis(5000)); })); } @Test public void bindWithIso8601Format() { - this.contextRunner - .withPropertyValues("app.system.session-timeout=PT15S", - "app.system.read-timeout=PT0.5S") + this.contextRunner.withPropertyValues("app.system.session-timeout=PT15S", "app.system.read-timeout=PT0.5S") .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()) - .isEqualTo(Duration.ofSeconds(15)); - assertThat(properties.getReadTimeout()) - .isEqualTo(Duration.ofMillis(500)); + assertThat(properties.getSessionTimeout()).isEqualTo(Duration.ofSeconds(15)); + assertThat(properties.getReadTimeout()).isEqualTo(Duration.ofMillis(500)); })); } - private ContextConsumer assertBinding( - Consumer properties) { + private ContextConsumer assertBinding(Consumer properties) { return (context) -> { assertThat(context).hasSingleBean(AppSystemProperties.class); properties.accept(context.getBean(AppSystemProperties.class)); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java index 824bae2674d..94ad315c8e8 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class BasicDataSourceExampleTests { public void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); DataSource dataSource = this.context.getBean(DataSource.class); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:h2:mem:basic"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:basic"); } } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java index 7749e1c8d28..dc7f034ba01 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,12 +49,9 @@ public class CompleteTwoDataSourcesExampleTests { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(this.context.getBean("firstDataSource")).isSameAs(dataSource); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .startsWith("jdbc:h2:mem:"); - DataSource secondDataSource = this.context.getBean("secondDataSource", - DataSource.class); - assertThat(secondDataSource.getConnection().getMetaData().getURL()) - .startsWith("jdbc:h2:mem:"); + assertThat(dataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:"); + DataSource secondDataSource = this.context.getBean("secondDataSource", DataSource.class); + assertThat(secondDataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:"); } } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java index c31e4dac037..ecfeff3a3f7 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java @@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest( - properties = { "app.datasource.url=jdbc:h2:mem:configurable;DB_CLOSE_DELAY=-1", - "app.datasource.configuration.maximum-pool-size=42" }) +@SpringBootTest(properties = { "app.datasource.url=jdbc:h2:mem:configurable;DB_CLOSE_DELAY=-1", + "app.datasource.configuration.maximum-pool-size=42" }) @Import(ConfigurableDataSourceExample.ConfigurableDataSourceConfiguration.class) public class ConfigurableDataSourceExampleTests { @@ -51,8 +50,7 @@ public class ConfigurableDataSourceExampleTests { public void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); HikariDataSource dataSource = this.context.getBean(HikariDataSource.class); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:h2:mem:configurable"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:configurable"); assertThat(dataSource.getMaximumPoolSize()).isEqualTo(42); } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java index 725bb9ab1f7..0ab15c3b2a1 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java @@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest( - properties = { "app.datasource.jdbc-url=jdbc:h2:mem:simple;DB_CLOSE_DELAY=-1", - "app.datasource.maximum-pool-size=42" }) +@SpringBootTest(properties = { "app.datasource.jdbc-url=jdbc:h2:mem:simple;DB_CLOSE_DELAY=-1", + "app.datasource.maximum-pool-size=42" }) @Import(SimpleDataSourceExample.SimpleDataSourceConfiguration.class) public class SimpleDataSourceExampleTests { @@ -51,8 +50,7 @@ public class SimpleDataSourceExampleTests { public void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); HikariDataSource dataSource = this.context.getBean(HikariDataSource.class); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:h2:mem:simple"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:simple"); assertThat(dataSource.getMaximumPoolSize()).isEqualTo(42); } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java index eb9dd66f473..efd7e4039d9 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java @@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest( - properties = { "app.datasource.second.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1", - "app.datasource.second.max-total=42" }) +@SpringBootTest(properties = { "app.datasource.second.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1", + "app.datasource.second.max-total=42" }) @Import(SimpleTwoDataSourcesExample.SimpleDataSourcesConfiguration.class) public class SimpleTwoDataSourcesExampleTests { @@ -52,12 +51,9 @@ public class SimpleTwoDataSourcesExampleTests { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(this.context.getBean("firstDataSource")).isSameAs(dataSource); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .startsWith("jdbc:h2:mem:"); - BasicDataSource secondDataSource = this.context.getBean("secondDataSource", - BasicDataSource.class); - assertThat(secondDataSource.getUrl()) - .isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1"); + assertThat(dataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:"); + BasicDataSource secondDataSource = this.context.getBean("secondDataSource", BasicDataSource.class); + assertThat(secondDataSource.getUrl()).isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1"); assertThat(secondDataSource.getMaxTotal()).isEqualTo(42); } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientConfiguration.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientConfiguration.java index 1fe61e20976..aa8d4559426 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientConfiguration.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientConfiguration.java @@ -35,9 +35,8 @@ import org.springframework.web.bind.annotation.RestController; * @author Stephane Nicoll */ @SpringBootConfiguration -@ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class }) +@ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class }) class SampleWebClientConfiguration { @RestController @@ -45,9 +44,7 @@ class SampleWebClientConfiguration { @RequestMapping("/example") public ResponseEntity example() { - return ResponseEntity.ok() - .location(URI.create("https://other.example.com/example")) - .body("test"); + return ResponseEntity.ok().location(URI.create("https://other.example.com/example")).body("test"); } } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java index ba876ba0d33..c321f0d82f9 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class SampleWebClientTests { @Test public void testRequest() { - HttpHeaders headers = this.template.getForEntity("/example", String.class) - .getHeaders(); + HttpHeaders headers = this.template.getForEntity("/example", String.class).getHeaders(); assertThat(headers.getLocation()).hasHost("other.example.com"); } diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java index d4fbab7d29f..c659610747f 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,11 +41,9 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; * @author Stephane Nicoll * @since 2.0.0 */ -public class PropertiesMigrationListener - implements ApplicationListener { +public class PropertiesMigrationListener implements ApplicationListener { - private static final Log logger = LogFactory - .getLog(PropertiesMigrationListener.class); + private static final Log logger = LogFactory.getLog(PropertiesMigrationListener.class); private PropertiesMigrationReport report; @@ -56,8 +54,7 @@ public class PropertiesMigrationListener if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } - if (event instanceof ApplicationReadyEvent - || event instanceof ApplicationFailedEvent) { + if (event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent) { logLegacyPropertiesReport(); } } @@ -78,8 +75,8 @@ public class PropertiesMigrationListener } } - private ConfigurationMetadataRepository loadRepository( - ConfigurationMetadataRepositoryJsonBuilder builder) throws IOException { + private ConfigurationMetadataRepository loadRepository(ConfigurationMetadataRepositoryJsonBuilder builder) + throws IOException { Resource[] resources = new PathMatchingResourcePatternResolver() .getResources("classpath*:/META-INF/spring-configuration-metadata.json"); for (Resource resource : resources) { diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReport.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReport.java index cbac2ed8b30..0ae02f888f5 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReport.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,14 +40,13 @@ class PropertiesMigrationReport { * @return a report with the configurations keys that should be renamed */ public String getWarningReport() { - Map> content = getContent( - LegacyProperties::getRenamed); + Map> content = getContent(LegacyProperties::getRenamed); if (content.isEmpty()) { return null; } StringBuilder report = new StringBuilder(); - report.append(String.format("%nThe use of configuration keys that have been " - + "renamed was found in the environment:%n%n")); + report.append(String.format( + "%nThe use of configuration keys that have been " + "renamed was found in the environment:%n%n")); append(report, content); report.append(String.format("%n")); report.append("Each configuration key has been temporarily mapped to its " @@ -63,32 +62,27 @@ class PropertiesMigrationReport { * @return a report with the configurations keys that are no longer supported */ public String getErrorReport() { - Map> content = getContent( - LegacyProperties::getUnsupported); + Map> content = getContent(LegacyProperties::getUnsupported); if (content.isEmpty()) { return null; } StringBuilder report = new StringBuilder(); - report.append(String.format("%nThe use of configuration keys that are no longer " - + "supported was found in the environment:%n%n")); + report.append(String.format( + "%nThe use of configuration keys that are no longer " + "supported was found in the environment:%n%n")); append(report, content); report.append(String.format("%n")); - report.append("Please refer to the migration guide or reference guide for " - + "potential alternatives."); + report.append("Please refer to the migration guide or reference guide for " + "potential alternatives."); report.append(String.format("%n")); return report.toString(); } private Map> getContent( Function> extractor) { - return this.content.entrySet().stream() - .filter((entry) -> !extractor.apply(entry.getValue()).isEmpty()) - .collect(Collectors.toMap(Map.Entry::getKey, - (entry) -> new ArrayList<>(extractor.apply(entry.getValue())))); + return this.content.entrySet().stream().filter((entry) -> !extractor.apply(entry.getValue()).isEmpty()).collect( + Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue())))); } - private void append(StringBuilder report, - Map> content) { + private void append(StringBuilder report, Map> content) { content.forEach((name, properties) -> { report.append(String.format("Property source '%s':%n", name)); properties.sort(PropertyMigration.COMPARATOR); @@ -96,8 +90,7 @@ class PropertiesMigrationReport { ConfigurationMetadataProperty metadata = property.getMetadata(); report.append(String.format("\tKey: %s%n", metadata.getId())); if (property.getLineNumber() != null) { - report.append( - String.format("\t\tLine: %d%n", property.getLineNumber())); + report.append(String.format("\t\tLine: %d%n", property.getLineNumber())); } report.append(String.format("\t\t%s%n", property.determineReason())); }); @@ -123,13 +116,11 @@ class PropertiesMigrationReport { } public List getRenamed() { - return this.properties.stream().filter(PropertyMigration::isCompatibleType) - .collect(Collectors.toList()); + return this.properties.stream().filter(PropertyMigration::isCompatibleType).collect(Collectors.toList()); } public List getUnsupported() { - return this.properties.stream() - .filter((property) -> !property.isCompatibleType()) + return this.properties.stream().filter((property) -> !property.isCompatibleType()) .collect(Collectors.toList()); } diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java index e08017e06ec..3adf6d6c471 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ class PropertiesMigrationReporter { PropertiesMigrationReporter(ConfigurationMetadataRepository metadataRepository, ConfigurableEnvironment environment) { - this.allProperties = Collections - .unmodifiableMap(metadataRepository.getAllProperties()); + this.allProperties = Collections.unmodifiableMap(metadataRepository.getAllProperties()); this.environment = environment; } @@ -63,14 +62,12 @@ class PropertiesMigrationReporter { */ public PropertiesMigrationReport getReport() { PropertiesMigrationReport report = new PropertiesMigrationReport(); - Map> properties = getMatchingProperties( - deprecatedFilter()); + Map> properties = getMatchingProperties(deprecatedFilter()); if (properties.isEmpty()) { return report; } properties.forEach((name, candidates) -> { - PropertySource propertySource = mapPropertiesWithReplacement(report, name, - candidates); + PropertySource propertySource = mapPropertiesWithReplacement(report, name, candidates); if (propertySource != null) { this.environment.getPropertySources().addBefore(name, propertySource); } @@ -78,20 +75,18 @@ class PropertiesMigrationReporter { return report; } - private PropertySource mapPropertiesWithReplacement( - PropertiesMigrationReport report, String name, + private PropertySource mapPropertiesWithReplacement(PropertiesMigrationReport report, String name, List properties) { report.add(name, properties); - List renamed = properties.stream() - .filter(PropertyMigration::isCompatibleType).collect(Collectors.toList()); + List renamed = properties.stream().filter(PropertyMigration::isCompatibleType) + .collect(Collectors.toList()); if (renamed.isEmpty()) { return null; } String target = "migrate-" + name; Map content = new LinkedHashMap<>(); for (PropertyMigration candidate : renamed) { - OriginTrackedValue value = OriginTrackedValue.of( - candidate.getProperty().getValue(), + OriginTrackedValue value = OriginTrackedValue.of(candidate.getProperty().getValue(), candidate.getProperty().getOrigin()); content.put(candidate.getMetadata().getDeprecation().getReplacement(), value); } @@ -101,28 +96,25 @@ class PropertiesMigrationReporter { private Map> getMatchingProperties( Predicate filter) { MultiValueMap result = new LinkedMultiValueMap<>(); - List candidates = this.allProperties.values() - .stream().filter(filter).collect(Collectors.toList()); + List candidates = this.allProperties.values().stream().filter(filter) + .collect(Collectors.toList()); getPropertySourcesAsMap().forEach((name, source) -> { candidates.forEach((metadata) -> { ConfigurationProperty configurationProperty = source - .getConfigurationProperty( - ConfigurationPropertyName.of(metadata.getId())); + .getConfigurationProperty(ConfigurationPropertyName.of(metadata.getId())); if (configurationProperty != null) { - result.add(name, new PropertyMigration(configurationProperty, - metadata, determineReplacementMetadata(metadata))); + result.add(name, new PropertyMigration(configurationProperty, metadata, + determineReplacementMetadata(metadata))); } }); }); return result; } - private ConfigurationMetadataProperty determineReplacementMetadata( - ConfigurationMetadataProperty metadata) { + private ConfigurationMetadataProperty determineReplacementMetadata(ConfigurationMetadataProperty metadata) { String replacementId = metadata.getDeprecation().getReplacement(); if (StringUtils.hasText(replacementId)) { - ConfigurationMetadataProperty replacement = this.allProperties - .get(replacementId); + ConfigurationMetadataProperty replacement = this.allProperties.get(replacementId); if (replacement != null) { return replacement; } @@ -146,8 +138,7 @@ class PropertiesMigrationReporter { private Map getPropertySourcesAsMap() { Map map = new LinkedHashMap<>(); - for (ConfigurationPropertySource source : ConfigurationPropertySources - .get(this.environment)) { + for (ConfigurationPropertySource source : ConfigurationPropertySources.get(this.environment)) { map.put(determinePropertySourceName(source), source); } return map; diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java index a613c7b33b6..77640ae4b73 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ class PropertyMigration { private final boolean compatibleType; - PropertyMigration(ConfigurationProperty property, - ConfigurationMetadataProperty metadata, + PropertyMigration(ConfigurationProperty property, ConfigurationMetadataProperty metadata, ConfigurationMetadataProperty replacementMetadata) { this.property = property; this.lineNumber = determineLineNumber(property); @@ -79,15 +78,13 @@ class PropertyMigration { return true; } if (replacementType.equals(Duration.class.getName()) - && (currentType.equals(Long.class.getName()) - || currentType.equals(Integer.class.getName()))) { + && (currentType.equals(Long.class.getName()) || currentType.equals(Integer.class.getName()))) { return true; } return false; } - private static String determineReplacementType( - ConfigurationMetadataProperty replacementMetadata) { + private static String determineReplacementType(ConfigurationMetadataProperty replacementMetadata) { if (replacementMetadata == null || replacementMetadata.getType() == null) { return null; } @@ -127,8 +124,7 @@ class PropertyMigration { } if (StringUtils.hasText(deprecation.getReplacement())) { if (this.replacementMetadata != null) { - return String.format( - "Reason: Replacement key '%s' uses an incompatible target type", + return String.format("Reason: Replacement key '%s' uses an incompatible target type", deprecation.getReplacement()); } else { diff --git a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java index 944378487ea..825d0f307fe 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java @@ -49,8 +49,7 @@ public class PropertiesMigrationListenerTests { @Test public void sampleReport() { this.context = createSampleApplication().run("--banner.charset=UTF8"); - assertThat(this.output.toString()).contains("commandLineArgs") - .contains("spring.banner.charset") + assertThat(this.output.toString()).contains("commandLineArgs").contains("spring.banner.charset") .contains("Each configuration key has been temporarily mapped") .doesNotContain("Please refer to the migration guide"); } diff --git a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java index 724263674f7..ef22fa4a5d0 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,63 +59,49 @@ public class PropertiesMigrationReporterTests { @Test public void replacementKeysAreRemapped() throws IOException { MutablePropertySources propertySources = this.environment.getPropertySources(); - PropertySource one = loadPropertySource("one", - "config/config-error.properties"); - PropertySource two = loadPropertySource("two", - "config/config-warnings.properties"); + PropertySource one = loadPropertySource("one", "config/config-error.properties"); + PropertySource two = loadPropertySource("two", "config/config-warnings.properties"); propertySources.addFirst(one); propertySources.addAfter("one", two); assertThat(propertySources).hasSize(3); createAnalyzer(loadRepository("metadata/sample-metadata.json")).getReport(); - assertThat(mapToNames(propertySources)).containsExactly("one", "migrate-two", - "two", "mockProperties"); - assertMappedProperty(propertySources.get("migrate-two"), "test.two", "another", - getOrigin(two, "wrong.two")); + assertThat(mapToNames(propertySources)).containsExactly("one", "migrate-two", "two", "mockProperties"); + assertMappedProperty(propertySources.get("migrate-two"), "test.two", "another", getOrigin(two, "wrong.two")); } @Test public void warningReport() throws IOException { - this.environment.getPropertySources().addFirst( - loadPropertySource("test", "config/config-warnings.properties")); - this.environment.getPropertySources() - .addFirst(loadPropertySource("ignore", "config/config-error.properties")); - String report = createWarningReport( - loadRepository("metadata/sample-metadata.json")); + this.environment.getPropertySources().addFirst(loadPropertySource("test", "config/config-warnings.properties")); + this.environment.getPropertySources().addFirst(loadPropertySource("ignore", "config/config-error.properties")); + String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); - assertThat(report).containsSubsequence("Property source 'test'", - "wrong.four.test", "Line: 5", "test.four.test", "wrong.two", "Line: 2", - "test.two"); + assertThat(report).containsSubsequence("Property source 'test'", "wrong.four.test", "Line: 5", "test.four.test", + "wrong.two", "Line: 2", "test.two"); assertThat(report).doesNotContain("wrong.one"); } @Test public void errorReport() throws IOException { - this.environment.getPropertySources().addFirst( - loadPropertySource("test1", "config/config-warnings.properties")); this.environment.getPropertySources() - .addFirst(loadPropertySource("test2", "config/config-error.properties")); - String report = createErrorReport( - loadRepository("metadata/sample-metadata.json")); + .addFirst(loadPropertySource("test1", "config/config-warnings.properties")); + this.environment.getPropertySources().addFirst(loadPropertySource("test2", "config/config-error.properties")); + String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); - assertThat(report).containsSubsequence("Property source 'test2'", "wrong.one", - "Line: 2", "This is no longer supported."); + assertThat(report).containsSubsequence("Property source 'test2'", "wrong.one", "Line: 2", + "This is no longer supported."); assertThat(report).doesNotContain("wrong.four.test").doesNotContain("wrong.two"); } @Test public void errorReportNoReplacement() throws IOException { - this.environment.getPropertySources().addFirst(loadPropertySource("first", - "config/config-error-no-replacement.properties")); this.environment.getPropertySources() - .addFirst(loadPropertySource("second", "config/config-error.properties")); - String report = createErrorReport( - loadRepository("metadata/sample-metadata.json")); + .addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties")); + this.environment.getPropertySources().addFirst(loadPropertySource("second", "config/config-error.properties")); + String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); - assertThat(report).containsSubsequence("Property source 'first'", "wrong.three", - "Line: 6", "none", "Property source 'second'", "wrong.one", "Line: 2", - "This is no longer supported."); - assertThat(report).doesNotContain("null").doesNotContain("server.port") - .doesNotContain("debug"); + assertThat(report).containsSubsequence("Property source 'first'", "wrong.three", "Line: 6", "none", + "Property source 'second'", "wrong.one", "Line: 2", "This is no longer supported."); + assertThat(report).doesNotContain("null").doesNotContain("server.port").doesNotContain("debug"); } @Test @@ -127,13 +113,10 @@ public class PropertiesMigrationReporterTests { content.put("test.ttl", 5678L); propertySources.addFirst(new MapPropertySource("test", content)); assertThat(propertySources).hasSize(2); - String report = createWarningReport( - loadRepository("metadata/type-conversion-metadata.json")); - assertThat(report).contains("Property source 'test'", "test.cache-seconds", - "test.cache", "test.time-to-live-ms", "test.time-to-live", "test.ttl", - "test.mapped.ttl"); - assertThat(mapToNames(propertySources)).containsExactly("migrate-test", "test", - "mockProperties"); + String report = createWarningReport(loadRepository("metadata/type-conversion-metadata.json")); + assertThat(report).contains("Property source 'test'", "test.cache-seconds", "test.cache", + "test.time-to-live-ms", "test.time-to-live", "test.ttl", "test.mapped.ttl"); + assertThat(mapToNames(propertySources)).containsExactly("migrate-test", "test", "mockProperties"); PropertySource propertySource = propertySources.get("migrate-test"); assertMappedProperty(propertySource, "test.cache", 50, null); assertMappedProperty(propertySource, "test.time-to-live", 1234L, null); @@ -142,25 +125,21 @@ public class PropertiesMigrationReporterTests { @Test public void reasonIsProvidedIfPropertyCouldNotBeRenamed() throws IOException { - this.environment.getPropertySources().addFirst(loadPropertySource("test", - "config/config-error-no-compatible-type.properties")); - String report = createErrorReport( - loadRepository("metadata/type-conversion-metadata.json")); + this.environment.getPropertySources() + .addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties")); + String report = createErrorReport(loadRepository("metadata/type-conversion-metadata.json")); assertThat(report).isNotNull(); - assertThat(report).containsSubsequence("Property source 'test'", - "wrong.inconvertible", "Line: 1", "Reason: Replacement key " - + "'test.inconvertible' uses an incompatible target type"); + assertThat(report).containsSubsequence("Property source 'test'", "wrong.inconvertible", "Line: 1", + "Reason: Replacement key " + "'test.inconvertible' uses an incompatible target type"); } @Test public void invalidReplacementHandled() throws IOException { - this.environment.getPropertySources().addFirst(loadPropertySource("first", - "config/config-error-invalid-replacement.properties")); - String report = createErrorReport( - loadRepository("metadata/sample-metadata-invalid-replacement.json")); + this.environment.getPropertySources() + .addFirst(loadPropertySource("first", "config/config-error-invalid-replacement.properties")); + String report = createErrorReport(loadRepository("metadata/sample-metadata-invalid-replacement.json")); assertThat(report).isNotNull(); - assertThat(report).containsSubsequence("Property source 'first'", - "deprecated.six.test", "Line: 1", "Reason", + assertThat(report).containsSubsequence("Property source 'first'", "deprecated.six.test", "Line: 1", "Reason", "No metadata found for replacement key 'does.not.exist'"); assertThat(report).doesNotContain("null"); } @@ -179,30 +158,25 @@ public class PropertiesMigrationReporterTests { } @SuppressWarnings("unchecked") - private void assertMappedProperty(PropertySource propertySource, String name, - Object value, Origin origin) { + private void assertMappedProperty(PropertySource propertySource, String name, Object value, Origin origin) { assertThat(propertySource.containsProperty(name)).isTrue(); assertThat(propertySource.getProperty(name)).isEqualTo(value); if (origin != null) { assertThat(propertySource).isInstanceOf(OriginLookup.class); - assertThat(((OriginLookup) propertySource).getOrigin(name)) - .isEqualTo(origin); + assertThat(((OriginLookup) propertySource).getOrigin(name)).isEqualTo(origin); } } - private PropertySource loadPropertySource(String name, String path) - throws IOException { + private PropertySource loadPropertySource(String name, String path) throws IOException { ClassPathResource resource = new ClassPathResource(path); - List> propertySources = new PropertiesPropertySourceLoader() - .load(name, resource); + List> propertySources = new PropertiesPropertySourceLoader().load(name, resource); assertThat(propertySources).isNotEmpty(); return propertySources.get(0); } private ConfigurationMetadataRepository loadRepository(String... content) { try { - ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder - .create(); + ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create(); for (String path : content) { Resource resource = new ClassPathResource(path); builder.withJsonResource(resource.getInputStream()); @@ -222,8 +196,7 @@ public class PropertiesMigrationReporterTests { return createAnalyzer(repository).getReport().getErrorReport(); } - private PropertiesMigrationReporter createAnalyzer( - ConfigurationMetadataRepository repository) { + private PropertiesMigrationReporter createAnalyzer(ConfigurationMetadataRepository repository) { return new PropertiesMigrationReporter(repository, this.environment); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java index 1b16518b999..bf68074418b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java @@ -34,30 +34,24 @@ import org.springframework.test.context.MergedContextConfiguration; * * @author Phillip Webb */ -class OverrideAutoConfigurationContextCustomizerFactory - implements ContextCustomizerFactory { +class OverrideAutoConfigurationContextCustomizerFactory implements ContextCustomizerFactory { @Override public ContextCustomizer createContextCustomizer(Class testClass, List configurationAttributes) { boolean enabled = MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE) - .get(OverrideAutoConfiguration.class).getValue("enabled", Boolean.class) - .orElse(true); + .get(OverrideAutoConfiguration.class).getValue("enabled", Boolean.class).orElse(true); return !enabled ? new DisableAutoConfigurationContextCustomizer() : null; } /** * {@link ContextCustomizer} to disable full auto-configuration. */ - private static class DisableAutoConfigurationContextCustomizer - implements ContextCustomizer { + private static class DisableAutoConfigurationContextCustomizer implements ContextCustomizer { @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { - TestPropertyValues - .of(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY + "=false") - .applyTo(context); + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { + TestPropertyValues.of(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY + "=false").applyTo(context); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java index 70cda5f7156..84fc4397fe2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution * @author Phillip Webb * @since 1.4.1 */ -public class SpringBootDependencyInjectionTestExecutionListener - extends DependencyInjectionTestExecutionListener { +public class SpringBootDependencyInjectionTestExecutionListener extends DependencyInjectionTestExecutionListener { @Override public void prepareTestInstance(TestContext testContext) throws Exception { @@ -68,13 +67,10 @@ public class SpringBootDependencyInjectionTestExecutionListener @Override public Set> postProcessDefaultTestExecutionListeners( Set> listeners) { - Set> updated = new LinkedHashSet<>( - listeners.size()); + Set> updated = new LinkedHashSet<>(listeners.size()); for (Class listener : listeners) { - updated.add( - listener.equals(DependencyInjectionTestExecutionListener.class) - ? SpringBootDependencyInjectionTestExecutionListener.class - : listener); + updated.add(listener.equals(DependencyInjectionTestExecutionListener.class) + ? SpringBootDependencyInjectionTestExecutionListener.class : listener); } return updated; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java index daca83fbf8b..691403e1cb8 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java @@ -30,9 +30,8 @@ class DataJdbcTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(DataJdbcTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataJdbcTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTypeExcludeFilter.java index b4b9dea056a..165e0b36f1f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Andy Wilkinson */ -class DataJdbcTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class DataJdbcTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { DataJdbcTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java index 88bd87608af..66a74aaf8b6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java @@ -30,9 +30,8 @@ class DataLdapTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(DataLdapTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataLdapTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTypeExcludeFilter.java index b0a0bbc7715..4abf0b54604 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Eddú Meléndez */ -class DataLdapTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class DataLdapTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { DataLdapTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java index e4fe8c8a594..1c63e98ba1a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java @@ -30,9 +30,8 @@ class DataMongoTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(DataMongoTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataMongoTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java index e3c36a06b79..ad9fe6c776b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Michael Simons */ -class DataMongoTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class DataMongoTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { DataMongoTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java index 8af130d51ef..0a958a75862 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java @@ -30,9 +30,8 @@ class DataNeo4jTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(DataNeo4jTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataNeo4jTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTypeExcludeFilter.java index ca56bb7d129..41698c7a60e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Eddú Meléndez */ -class DataNeo4jTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class DataNeo4jTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { DataNeo4jTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java index 69e82a5da6f..98a9dec1004 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java @@ -30,9 +30,8 @@ class DataRedisTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(DataRedisTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataRedisTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTypeExcludeFilter.java index 9308d54d27e..22ced6b21ac 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Jayaram Pradhan */ -class DataRedisTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class DataRedisTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { DataRedisTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java index d86bd03c86f..d9670c1ce02 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,30 +47,28 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud } @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { if (hasAnnotation()) { - return !(include(metadataReader, metadataReaderFactory) - && !exclude(metadataReader, metadataReaderFactory)); + return !(include(metadataReader, metadataReaderFactory) && !exclude(metadataReader, metadataReaderFactory)); } return false; } - protected boolean include(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - if (new FilterAnnotations(this.classLoader, getFilters(FilterType.INCLUDE)) - .anyMatches(metadataReader, metadataReaderFactory)) { + protected boolean include(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + if (new FilterAnnotations(this.classLoader, getFilters(FilterType.INCLUDE)).anyMatches(metadataReader, + metadataReaderFactory)) { return true; } - if (isUseDefaultFilters() - && defaultInclude(metadataReader, metadataReaderFactory)) { + if (isUseDefaultFilters() && defaultInclude(metadataReader, metadataReaderFactory)) { return true; } return false; } - protected boolean defaultInclude(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + protected boolean defaultInclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { for (Class include : getDefaultIncludes()) { if (isTypeOrAnnotated(metadataReader, metadataReaderFactory, include)) { return true; @@ -84,18 +82,16 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud return false; } - protected boolean exclude(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - return new FilterAnnotations(this.classLoader, getFilters(FilterType.EXCLUDE)) - .anyMatches(metadataReader, metadataReaderFactory); + protected boolean exclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + return new FilterAnnotations(this.classLoader, getFilters(FilterType.EXCLUDE)).anyMatches(metadataReader, + metadataReaderFactory); } @SuppressWarnings("unchecked") protected final boolean isTypeOrAnnotated(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory, Class type) - throws IOException { - AnnotationTypeFilter annotationFilter = new AnnotationTypeFilter( - (Class) type); + MetadataReaderFactory metadataReaderFactory, Class type) throws IOException { + AnnotationTypeFilter annotationFilter = new AnnotationTypeFilter((Class) type); AssignableTypeFilter typeFilter = new AssignableTypeFilter(type); return annotationFilter.match(metadataReader, metadataReaderFactory) || typeFilter.match(metadataReader, metadataReaderFactory); @@ -129,14 +125,11 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud boolean result = true; result = result && hasAnnotation() == other.hasAnnotation(); for (FilterType filterType : FilterType.values()) { - result &= ObjectUtils.nullSafeEquals(getFilters(filterType), - other.getFilters(filterType)); + result &= ObjectUtils.nullSafeEquals(getFilters(filterType), other.getFilters(filterType)); } result = result && isUseDefaultFilters() == other.isUseDefaultFilters(); - result = result && ObjectUtils.nullSafeEquals(getDefaultIncludes(), - other.getDefaultIncludes()); - result = result && ObjectUtils.nullSafeEquals(getComponentIncludes(), - other.getComponentIncludes()); + result = result && ObjectUtils.nullSafeEquals(getDefaultIncludes(), other.getDefaultIncludes()); + result = result && ObjectUtils.nullSafeEquals(getComponentIncludes(), other.getComponentIncludes()); return result; } @@ -146,8 +139,7 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud int result = 0; result = prime * result + Boolean.hashCode(hasAnnotation()); for (FilterType filterType : FilterType.values()) { - result = prime * result - + ObjectUtils.nullSafeHashCode(getFilters(filterType)); + result = prime * result + ObjectUtils.nullSafeHashCode(getFilters(filterType)); } result = prime * result + Boolean.hashCode(isUseDefaultFilters()); result = prime * result + ObjectUtils.nullSafeHashCode(getDefaultIncludes()); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java index 5d556316556..5bcd2468869 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,8 +81,7 @@ public class FilterAnnotations implements Iterable { "An error occurred while processing a CUSTOM type filter: "); return BeanUtils.instantiateClass(filterClass, TypeFilter.class); } - throw new IllegalArgumentException( - "Filter type not supported with Class value: " + filterType); + throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType); } private TypeFilter createTypeFilter(FilterType filterType, String pattern) { @@ -92,8 +91,7 @@ public class FilterAnnotations implements Iterable { case REGEX: return new RegexPatternTypeFilter(Pattern.compile(pattern)); } - throw new IllegalArgumentException( - "Filter type not supported with String pattern: " + filterType); + throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType); } @Override @@ -101,8 +99,8 @@ public class FilterAnnotations implements Iterable { return this.filters.iterator(); } - public boolean anyMatches(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean anyMatches(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { for (TypeFilter filter : this) { if (filter.match(metadataReader, metadataReaderFactory)) { return true; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java index 0a354d14032..9ada5057cc5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java @@ -52,8 +52,7 @@ public abstract class StandardAnnotationCustomizableTypeExcludeFilter annotation; protected StandardAnnotationCustomizableTypeExcludeFilter(Class testClass) { - this.annotation = MergedAnnotations - .from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + this.annotation = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) .get(getAnnotationType()); } @@ -68,9 +67,7 @@ public abstract class StandardAnnotationCustomizableTypeExcludeFilter getAnnotationType() { - ResolvableType type = ResolvableType.forClass( - StandardAnnotationCustomizableTypeExcludeFilter.class, getClass()); + ResolvableType type = ResolvableType.forClass(StandardAnnotationCustomizableTypeExcludeFilter.class, + getClass()); return (Class) type.resolveGeneric(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java index 90d58db379a..5872a7b9127 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,11 @@ import org.springframework.util.ReflectionUtils; */ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { - private static final String EXCLUDE_FILTER_BEAN_NAME = TypeExcludeFilters.class - .getName(); + private static final String EXCLUDE_FILTER_BEAN_NAME = TypeExcludeFilters.class.getName(); private final Set filters; - TypeExcludeFiltersContextCustomizer(Class testClass, - Set> filterClasses) { + TypeExcludeFiltersContextCustomizer(Class testClass, Set> filterClasses) { this.filters = instantiateTypeExcludeFilters(testClass, filterClasses); } @@ -57,8 +55,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { return Collections.unmodifiableSet(filters); } - private TypeExcludeFilter instantiateTypeExcludeFilter(Class testClass, - Class filterClass) { + private TypeExcludeFilter instantiateTypeExcludeFilter(Class testClass, Class filterClass) { try { Constructor constructor = getTypeExcludeFilterConstructor(filterClass); ReflectionUtils.makeAccessible(constructor); @@ -68,15 +65,14 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { return (TypeExcludeFilter) constructor.newInstance(); } catch (Exception ex) { - throw new IllegalStateException("Unable to create filter for " + filterClass, - ex); + throw new IllegalStateException("Unable to create filter for " + filterClass, ex); } } @Override public boolean equals(Object obj) { - return (obj != null && getClass() == obj.getClass() && this.filters - .equals(((TypeExcludeFiltersContextCustomizer) obj).filters)); + return (obj != null && getClass() == obj.getClass() + && this.filters.equals(((TypeExcludeFiltersContextCustomizer) obj).filters)); } @Override @@ -88,8 +84,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { if (!this.filters.isEmpty()) { - context.getBeanFactory().registerSingleton(EXCLUDE_FILTER_BEAN_NAME, - createDelegatingTypeExcludeFilter()); + context.getBeanFactory().registerSingleton(EXCLUDE_FILTER_BEAN_NAME, createDelegatingTypeExcludeFilter()); } } @@ -97,8 +92,8 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { return new TypeExcludeFilter() { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { for (TypeExcludeFilter filter : TypeExcludeFiltersContextCustomizer.this.filters) { if (filter.match(metadataReader, metadataReaderFactory)) { return true; @@ -110,8 +105,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { }; } - private Constructor getTypeExcludeFilterConstructor(Class type) - throws NoSuchMethodException { + private Constructor getTypeExcludeFilterConstructor(Class type) throws NoSuchMethodException { try { return type.getDeclaredConstructor(Class.class); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java index 05f5f221cdb..b93afdcfc47 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java @@ -43,10 +43,8 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac @Override public ContextCustomizer createContextCustomizer(Class testClass, List configurationAttributes) { - Class[] filterClasses = MergedAnnotations - .from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(TypeExcludeFilters.class) - .getValue(MergedAnnotation.VALUE, Class[].class).orElse(NO_FILTERS); + Class[] filterClasses = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(TypeExcludeFilters.class).getValue(MergedAnnotation.VALUE, Class[].class).orElse(NO_FILTERS); if (ObjectUtils.isEmpty(filterClasses)) { return null; } @@ -54,10 +52,9 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac } @SuppressWarnings("unchecked") - private ContextCustomizer createContextCustomizer(Class testClass, - Class[] filterClasses) { - return new TypeExcludeFiltersContextCustomizer(testClass, new LinkedHashSet<>( - Arrays.asList((Class[]) filterClasses))); + private ContextCustomizer createContextCustomizer(Class testClass, Class[] filterClasses) { + return new TypeExcludeFiltersContextCustomizer(testClass, + new LinkedHashSet<>(Arrays.asList((Class[]) filterClasses))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java index ddec9486bfc..d91547ab4ee 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java @@ -30,8 +30,8 @@ class JdbcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(JdbcTest.class).getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JdbcTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java index acaabc09da2..c5f47c03bc1 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Stephane Nicoll */ -class JdbcTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class JdbcTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { JdbcTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java index 1ca1234d5ac..353af7cce2b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java @@ -58,68 +58,57 @@ import org.springframework.util.ObjectUtils; public class TestDatabaseAutoConfiguration { @Bean - @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", - havingValue = "AUTO_CONFIGURED") + @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "AUTO_CONFIGURED") @ConditionalOnMissingBean public DataSource dataSource(Environment environment) { return new EmbeddedDataSourceFactory(environment).getEmbeddedDatabase(); } @Bean - @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", - havingValue = "ANY", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "ANY", + matchIfMissing = true) public static EmbeddedDataSourceBeanFactoryPostProcessor embeddedDataSourceBeanFactoryPostProcessor() { return new EmbeddedDataSourceBeanFactoryPostProcessor(); } @Order(Ordered.LOWEST_PRECEDENCE) - private static class EmbeddedDataSourceBeanFactoryPostProcessor - implements BeanDefinitionRegistryPostProcessor { + private static class EmbeddedDataSourceBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor { - private static final Log logger = LogFactory - .getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class); + private static final Log logger = LogFactory.getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class); @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, registry, - "Test Database Auto-configuration can only be " - + "used with a ConfigurableListableBeanFactory"); + "Test Database Auto-configuration can only be " + "used with a ConfigurableListableBeanFactory"); process(registry, (ConfigurableListableBeanFactory) registry); } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } - private void process(BeanDefinitionRegistry registry, - ConfigurableListableBeanFactory beanFactory) { + private void process(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) { BeanDefinitionHolder holder = getDataSourceBeanDefinition(beanFactory); if (holder != null) { String beanName = holder.getBeanName(); boolean primary = holder.getBeanDefinition().isPrimary(); - logger.info("Replacing '" + beanName + "' DataSource bean with " - + (primary ? "primary " : "") + "embedded version"); + logger.info("Replacing '" + beanName + "' DataSource bean with " + (primary ? "primary " : "") + + "embedded version"); registry.removeBeanDefinition(beanName); - registry.registerBeanDefinition(beanName, - createEmbeddedBeanDefinition(primary)); + registry.registerBeanDefinition(beanName, createEmbeddedBeanDefinition(primary)); } } private BeanDefinition createEmbeddedBeanDefinition(boolean primary) { - BeanDefinition beanDefinition = new RootBeanDefinition( - EmbeddedDataSourceFactoryBean.class); + BeanDefinition beanDefinition = new RootBeanDefinition(EmbeddedDataSourceFactoryBean.class); beanDefinition.setPrimary(primary); return beanDefinition; } - private BeanDefinitionHolder getDataSourceBeanDefinition( - ConfigurableListableBeanFactory beanFactory) { + private BeanDefinitionHolder getDataSourceBeanDefinition(ConfigurableListableBeanFactory beanFactory) { String[] beanNames = beanFactory.getBeanNamesForType(DataSource.class); if (ObjectUtils.isEmpty(beanNames)) { - logger.warn("No DataSource beans found, " - + "embedded version will not be used"); + logger.warn("No DataSource beans found, " + "embedded version will not be used"); return null; } if (beanNames.length == 1) { @@ -133,8 +122,7 @@ public class TestDatabaseAutoConfiguration { return new BeanDefinitionHolder(beanDefinition, beanName); } } - logger.warn("No primary DataSource found, " - + "embedded version will not be used"); + logger.warn("No primary DataSource found, " + "embedded version will not be used"); return null; } @@ -183,19 +171,16 @@ public class TestDatabaseAutoConfiguration { } public EmbeddedDatabase getEmbeddedDatabase() { - EmbeddedDatabaseConnection connection = this.environment.getProperty( - "spring.test.database.connection", EmbeddedDatabaseConnection.class, - EmbeddedDatabaseConnection.NONE); + EmbeddedDatabaseConnection connection = this.environment.getProperty("spring.test.database.connection", + EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " - + "on the classpath or tune the replace attribute of " - + "@AutoConfigureTestDatabase."); - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(connection.getType()).build(); + + "on the classpath or tune the replace attribute of " + "@AutoConfigureTestDatabase."); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(connection.getType()).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java index ae356cd33d5..24b9849500c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java @@ -30,8 +30,8 @@ class JooqTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(JooqTest.class).getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JooqTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTypeExcludeFilter.java index 333f6ad4d0e..2572ec66e33 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Michael Simons */ -class JooqTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class JooqTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { JooqTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java index adf980e9a3a..1a3aaea11d4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java @@ -30,8 +30,7 @@ import org.springframework.util.ClassUtils; * * @author Phillip Webb */ -class JsonExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class JsonExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { private static final String JACKSON_MODULE = "com.fasterxml.jackson.databind.Module"; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java index b75b96306cc..6dc84ac874b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java @@ -30,8 +30,8 @@ class JsonTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(JsonTest.class).getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JsonTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java index e8be570532f..4197f923d50 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java @@ -59,8 +59,7 @@ import org.springframework.util.ReflectionUtils; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = "org.assertj.core.api.Assert") @ConditionalOnProperty("spring.test.jsontesters.enabled") -@AutoConfigureAfter({ JacksonAutoConfiguration.class, GsonAutoConfiguration.class, - JsonbAutoConfiguration.class }) +@AutoConfigureAfter({ JacksonAutoConfiguration.class, GsonAutoConfiguration.class, JsonbAutoConfiguration.class }) public class JsonTestersAutoConfiguration { @Bean @@ -71,8 +70,7 @@ public class JsonTestersAutoConfiguration { @Bean @Scope("prototype") public FactoryBean basicJsonTesterFactoryBean() { - return new JsonTesterFactoryBean(BasicJsonTester.class, - null); + return new JsonTesterFactoryBean(BasicJsonTester.class, null); } @Configuration(proxyBeanMethods = false) @@ -82,8 +80,7 @@ public class JsonTestersAutoConfiguration { @Bean @Scope("prototype") @ConditionalOnBean(ObjectMapper.class) - public FactoryBean> jacksonTesterFactoryBean( - ObjectMapper mapper) { + public FactoryBean> jacksonTesterFactoryBean(ObjectMapper mapper) { return new JsonTesterFactoryBean<>(JacksonTester.class, mapper); } @@ -148,14 +145,12 @@ public class JsonTestersAutoConfiguration { Constructor[] constructors = this.objectType.getDeclaredConstructors(); for (Constructor constructor : constructors) { if (constructor.getParameterCount() == 1 - && constructor.getParameterTypes()[0] - .isInstance(this.marshaller)) { + && constructor.getParameterTypes()[0].isInstance(this.marshaller)) { ReflectionUtils.makeAccessible(constructor); return (T) BeanUtils.instantiateClass(constructor, this.marshaller); } } - throw new IllegalStateException( - this.objectType + " does not have a usable constructor"); + throw new IllegalStateException(this.objectType + " does not have a usable constructor"); } @Override @@ -168,21 +163,17 @@ public class JsonTestersAutoConfiguration { /** * {@link BeanPostProcessor} used to initialize JSON testers. */ - static class JsonMarshalTestersBeanPostProcessor - extends InstantiationAwareBeanPostProcessorAdapter { + static class JsonMarshalTestersBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { - ReflectionUtils.doWithFields(bean.getClass(), - (field) -> processField(bean, field)); + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + ReflectionUtils.doWithFields(bean.getClass(), (field) -> processField(bean, field)); return bean; } private void processField(Object bean, Field field) { if (AbstractJsonMarshalTester.class.isAssignableFrom(field.getType())) { - initializeTester(bean, field, bean.getClass(), - ResolvableType.forField(field).getGeneric()); + initializeTester(bean, field, bean.getClass(), ResolvableType.forField(field).getGeneric()); } else if (BasicJsonTester.class.isAssignableFrom(field.getType())) { initializeTester(bean, field, bean.getClass()); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java index 5f460507e95..3d30008d75c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java @@ -30,9 +30,8 @@ class DataJpaTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(DataJpaTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataJpaTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java index bd0085c6763..14762cadab4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.autoconfigure.filter.StandardAnnotationCust * * @author Phillip Webb */ -class DataJpaTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class DataJpaTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { DataJpaTypeExcludeFilter(Class testClass) { super(testClass); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java index 5e347e38ec5..2fc1c9005b6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -234,8 +234,7 @@ public class TestEntityManager { * @return the entity manager */ public final EntityManager getEntityManager() { - EntityManager manager = EntityManagerFactoryUtils - .getTransactionalEntityManager(this.entityManagerFactory); + EntityManager manager = EntityManagerFactoryUtils.getTransactionalEntityManager(this.entityManagerFactory); Assert.state(manager != null, "No transactional EntityManager found"); return manager; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java index c6ed926f567..a1a1691a702 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java @@ -39,8 +39,7 @@ public class TestEntityManagerAutoConfiguration { @Bean @ConditionalOnMissingBean - public TestEntityManager testEntityManager( - EntityManagerFactory entityManagerFactory) { + public TestEntityManager testEntityManager(EntityManagerFactory entityManagerFactory) { return new TestEntityManager(entityManagerFactory); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java index 3bb2ecf4ede..9e7d4dfee43 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java @@ -59,31 +59,24 @@ public class AnnotationsPropertySource extends EnumerablePropertySource private Map getProperties(Class source) { Map properties = new LinkedHashMap<>(); MergedAnnotations.from(source, SearchStrategy.SUPERCLASS).stream() - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getType)) - .forEach((annotation) -> { + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getType)).forEach((annotation) -> { Class type = annotation.getType(); - MergedAnnotation typeMapping = MergedAnnotations.from(type).get( - PropertyMapping.class, MergedAnnotation::isDirectlyPresent); - String prefix = typeMapping - .getValue(MergedAnnotation.VALUE, String.class).orElse(""); - SkipPropertyMapping defaultSkip = typeMapping - .getValue("skip", SkipPropertyMapping.class) + MergedAnnotation typeMapping = MergedAnnotations.from(type).get(PropertyMapping.class, + MergedAnnotation::isDirectlyPresent); + String prefix = typeMapping.getValue(MergedAnnotation.VALUE, String.class).orElse(""); + SkipPropertyMapping defaultSkip = typeMapping.getValue("skip", SkipPropertyMapping.class) .orElse(SkipPropertyMapping.YES); for (Method attribute : type.getDeclaredMethods()) { - collectProperties(prefix, defaultSkip, annotation, attribute, - properties); + collectProperties(prefix, defaultSkip, annotation, attribute, properties); } }); return properties; } - private void collectProperties(String prefix, SkipPropertyMapping defaultSkip, - MergedAnnotation annotation, Method attribute, - Map properties) { - MergedAnnotation attributeMapping = MergedAnnotations.from(attribute) - .get(PropertyMapping.class); - SkipPropertyMapping skip = attributeMapping - .getValue("skip", SkipPropertyMapping.class).orElse(defaultSkip); + private void collectProperties(String prefix, SkipPropertyMapping defaultSkip, MergedAnnotation annotation, + Method attribute, Map properties) { + MergedAnnotation attributeMapping = MergedAnnotations.from(attribute).get(PropertyMapping.class); + SkipPropertyMapping skip = attributeMapping.getValue("skip", SkipPropertyMapping.class).orElse(defaultSkip); if (skip == SkipPropertyMapping.YES) { return; } @@ -92,8 +85,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource return; } if (skip == SkipPropertyMapping.ON_DEFAULT_VALUE) { - if (ObjectUtils.nullSafeEquals(value.get(), - annotation.getDefaultValue(attribute.getName()).orElse(null))) { + if (ObjectUtils.nullSafeEquals(value.get(), annotation.getDefaultValue(attribute.getName()).orElse(null))) { return; } } @@ -101,10 +93,8 @@ public class AnnotationsPropertySource extends EnumerablePropertySource putProperties(name, value.get(), properties); } - private String getName(String prefix, MergedAnnotation attributeMapping, - Method attribute) { - String name = attributeMapping.getValue(MergedAnnotation.VALUE, String.class) - .orElse(""); + private String getName(String prefix, MergedAnnotation attributeMapping, Method attribute) { + String name = attributeMapping.getValue(MergedAnnotation.VALUE, String.class).orElse(""); if (!StringUtils.hasText(name)) { name = toKebabCase(attribute.getName()); } @@ -115,8 +105,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource Matcher matcher = CAMEL_CASE_PATTERN.matcher(name); StringBuffer result = new StringBuffer(); while (matcher.find()) { - matcher.appendReplacement(result, - matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2))); + matcher.appendReplacement(result, matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2))); } matcher.appendTail(result); return result.toString().toLowerCase(Locale.ENGLISH); @@ -129,8 +118,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource return postfix; } - private void putProperties(String name, Object value, - Map properties) { + private void putProperties(String name, Object value, Map properties) { if (ObjectUtils.isArray(value)) { Object[] array = ObjectUtils.toObjectArray(value); for (int i = 0; i < array.length; i++) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java index 15fe7124023..ac62c80a80a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java @@ -51,15 +51,14 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { if (!this.propertySource.isEmpty()) { context.getEnvironment().getPropertySources().addFirst(this.propertySource); } - context.getBeanFactory().registerSingleton( - PropertyMappingCheckBeanPostProcessor.class.getName(), + context.getBeanFactory().registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(), new PropertyMappingCheckBeanPostProcessor()); } @Override public boolean equals(Object obj) { - return (obj != null && getClass() == obj.getClass() && this.propertySource - .equals(((PropertyMappingContextCustomizer) obj).propertySource)); + return (obj != null && getClass() == obj.getClass() + && this.propertySource.equals(((PropertyMappingContextCustomizer) obj).propertySource)); } @Override @@ -74,18 +73,15 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { static class PropertyMappingCheckBeanPostProcessor implements BeanPostProcessor { @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class beanClass = bean.getClass(); - MergedAnnotations annotations = MergedAnnotations.from(beanClass, - SearchStrategy.SUPERCLASS); - Set> components = annotations.stream(Component.class) - .map(this::getRoot).collect(Collectors.toSet()); - Set> propertyMappings = annotations.stream(PropertyMapping.class) - .map(this::getRoot).collect(Collectors.toSet()); + MergedAnnotations annotations = MergedAnnotations.from(beanClass, SearchStrategy.SUPERCLASS); + Set> components = annotations.stream(Component.class).map(this::getRoot) + .collect(Collectors.toSet()); + Set> propertyMappings = annotations.stream(PropertyMapping.class).map(this::getRoot) + .collect(Collectors.toSet()); if (!components.isEmpty() && !propertyMappings.isEmpty()) { - throw new IllegalStateException("The @PropertyMapping " - + getAnnotationsDescription(propertyMappings) + throw new IllegalStateException("The @PropertyMapping " + getAnnotationsDescription(propertyMappings) + " cannot be used in combination with the @Component " + getAnnotationsDescription(components)); } @@ -109,8 +105,7 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java index 24978c00481..8aa307bffad 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ class PropertyMappingContextCustomizerFactory implements ContextCustomizerFactor @Override public ContextCustomizer createContextCustomizer(Class testClass, List configurationAttributes) { - AnnotationsPropertySource propertySource = new AnnotationsPropertySource( - testClass); + AnnotationsPropertySource propertySource = new AnnotationsPropertySource(testClass); return new PropertyMappingContextCustomizer(propertySource); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java index 6802612fd3b..4a72165377b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java @@ -63,25 +63,21 @@ public class RestDocsAutoConfiguration { MockMvcRestDocumentationConfigurer configurer = MockMvcRestDocumentation .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer - .customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return configurer; } @Bean - public RestDocsMockMvcBuilderCustomizer restDocumentationConfigurer( - RestDocsProperties properties, + public RestDocsMockMvcBuilderCustomizer restDocumentationConfigurer(RestDocsProperties properties, MockMvcRestDocumentationConfigurer configurer, ObjectProvider resultHandler) { - return new RestDocsMockMvcBuilderCustomizer(properties, configurer, - resultHandler.getIfAvailable()); + return new RestDocsMockMvcBuilderCustomizer(properties, configurer, resultHandler.getIfAvailable()); } } @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ RequestSpecification.class, - RestAssuredRestDocumentation.class }) + @ConditionalOnClass({ RequestSpecification.class, RestAssuredRestDocumentation.class }) @EnableConfigurationProperties(RestDocsProperties.class) static class RestDocsRestAssuredConfiguration { @@ -93,14 +89,13 @@ public class RestDocsAutoConfiguration { RestAssuredRestDocumentationConfigurer configurer = RestAssuredRestDocumentation .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer - .customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return new RequestSpecBuilder().addFilter(configurer).build(); } @Bean - public RestDocsRestAssuredBuilderCustomizer restAssuredBuilderCustomizer( - RestDocsProperties properties, RequestSpecification configurer) { + public RestDocsRestAssuredBuilderCustomizer restAssuredBuilderCustomizer(RestDocsProperties properties, + RequestSpecification configurer) { return new RestDocsRestAssuredBuilderCustomizer(properties, configurer); } @@ -120,14 +115,12 @@ public class RestDocsAutoConfiguration { WebTestClientRestDocumentationConfigurer configurer = WebTestClientRestDocumentation .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer - .customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return configurer; } @Bean - public RestDocsWebTestClientBuilderCustomizer restDocumentationConfigurer( - RestDocsProperties properties, + public RestDocsWebTestClientBuilderCustomizer restDocumentationConfigurer(RestDocsProperties properties, WebTestClientRestDocumentationConfigurer configurer) { return new RestDocsWebTestClientBuilderCustomizer(properties, configurer); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java index 4047071f29f..15a941958fc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder; * * @author Andy Wilkinson */ -class RestDocsMockMvcBuilderCustomizer - implements InitializingBean, MockMvcBuilderCustomizer { +class RestDocsMockMvcBuilderCustomizer implements InitializingBean, MockMvcBuilderCustomizer { private final RestDocsProperties properties; @@ -38,8 +37,7 @@ class RestDocsMockMvcBuilderCustomizer private final RestDocumentationResultHandler resultHandler; - RestDocsMockMvcBuilderCustomizer(RestDocsProperties properties, - MockMvcRestDocumentationConfigurer delegate, + RestDocsMockMvcBuilderCustomizer(RestDocsProperties properties, MockMvcRestDocumentationConfigurer delegate, RestDocumentationResultHandler resultHandler) { this.properties = properties; this.delegate = delegate; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java index baba687daee..b87dbdf3450 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ class RestDocsRestAssuredBuilderCustomizer implements InitializingBean { private final RequestSpecification delegate; - RestDocsRestAssuredBuilderCustomizer(RestDocsProperties properties, - RequestSpecification delegate) { + RestDocsRestAssuredBuilderCustomizer(RestDocsProperties properties, RequestSpecification delegate) { this.properties = properties; this.delegate = delegate; } @@ -43,8 +42,8 @@ class RestDocsRestAssuredBuilderCustomizer implements InitializingBean { public void afterPropertiesSet() throws Exception { PropertyMapper map = PropertyMapper.get(); String host = this.properties.getUriHost(); - map.from(this.properties::getUriScheme).when( - (scheme) -> StringUtils.hasText(scheme) && StringUtils.hasText(host)) + map.from(this.properties::getUriScheme) + .when((scheme) -> StringUtils.hasText(scheme) && StringUtils.hasText(host)) .to((scheme) -> this.delegate.baseUri(scheme + "://" + host)); map.from(this.properties::getUriPort).whenNonNull().to(this.delegate::port); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java index ca519ba5476..aca959aa393 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,27 +61,22 @@ public class RestDocsTestExecutionListener extends AbstractTestExecutionListener private static class DocumentationHandler { private void beforeTestMethod(TestContext testContext) throws Exception { - ManualRestDocumentation restDocumentation = findManualRestDocumentation( - testContext); + ManualRestDocumentation restDocumentation = findManualRestDocumentation(testContext); if (restDocumentation != null) { - restDocumentation.beforeTest(testContext.getTestClass(), - testContext.getTestMethod().getName()); + restDocumentation.beforeTest(testContext.getTestClass(), testContext.getTestMethod().getName()); } } private void afterTestMethod(TestContext testContext) { - ManualRestDocumentation restDocumentation = findManualRestDocumentation( - testContext); + ManualRestDocumentation restDocumentation = findManualRestDocumentation(testContext); if (restDocumentation != null) { restDocumentation.afterTest(); } } - private ManualRestDocumentation findManualRestDocumentation( - TestContext testContext) { + private ManualRestDocumentation findManualRestDocumentation(TestContext testContext) { try { - return testContext.getApplicationContext() - .getBean(ManualRestDocumentation.class); + return testContext.getApplicationContext().getBean(ManualRestDocumentation.class); } catch (NoSuchBeanDefinitionException ex) { return null; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsWebTestClientBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsWebTestClientBuilderCustomizer.java index 93c0ba243fe..5c034717f9c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsWebTestClientBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsWebTestClientBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,7 @@ class RestDocsWebTestClientBuilderCustomizer implements WebTestClientBuilderCust if (port == null) { return true; } - return (scheme.equals("http") && port == 80) - || (scheme.equals("https") && port == 443); + return (scheme.equals("http") && port == 80) || (scheme.equals("https") && port == 443); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java index c7fa9ddd5f5..36cb4227c1f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java @@ -35,8 +35,7 @@ import org.springframework.util.StringUtils; class RestDocumentationContextProviderRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map annotationAttributes = importingClassMetadata .getAnnotationAttributes(AutoConfigureRestDocs.class.getName()); BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder @@ -45,8 +44,7 @@ class RestDocumentationContextProviderRegistrar implements ImportBeanDefinitionR if (StringUtils.hasText(outputDir)) { definitionBuilder.addConstructorArgValue(outputDir); } - registry.registerBeanDefinition(ManualRestDocumentation.class.getName(), - definitionBuilder.getBeanDefinition()); + registry.registerBeanDefinition(ManualRestDocumentation.class.getName(), definitionBuilder.getBeanDefinition()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java index 95313777111..fc4f0c40c29 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java @@ -42,8 +42,7 @@ import org.springframework.web.client.RestTemplate; * @see AutoConfigureMockRestServiceServer */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver", - name = "enabled") +@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver", name = "enabled") public class MockRestServiceServerAutoConfiguration { @Bean @@ -52,8 +51,7 @@ public class MockRestServiceServerAutoConfiguration { } @Bean - public MockRestServiceServer mockRestServiceServer( - MockServerRestTemplateCustomizer customizer) { + public MockRestServiceServer mockRestServiceServer(MockServerRestTemplateCustomizer customizer) { try { return createDeferredMockRestServiceServer(customizer); } @@ -62,8 +60,8 @@ public class MockRestServiceServerAutoConfiguration { } } - private MockRestServiceServer createDeferredMockRestServiceServer( - MockServerRestTemplateCustomizer customizer) throws Exception { + private MockRestServiceServer createDeferredMockRestServiceServer(MockServerRestTemplateCustomizer customizer) + throws Exception { Constructor constructor = MockRestServiceServer.class .getDeclaredConstructor(RequestExpectationManager.class); constructor.setAccessible(true); @@ -76,8 +74,7 @@ public class MockRestServiceServerAutoConfiguration { * {@link MockServerRestTemplateCustomizer#customize(RestTemplate) * MockServerRestTemplateCustomizer} has been called. */ - private static class DeferredRequestExpectationManager - implements RequestExpectationManager { + private static class DeferredRequestExpectationManager implements RequestExpectationManager { private MockServerRestTemplateCustomizer customizer; @@ -86,14 +83,12 @@ public class MockRestServiceServerAutoConfiguration { } @Override - public ResponseActions expectRequest(ExpectedCount count, - RequestMatcher requestMatcher) { + public ResponseActions expectRequest(ExpectedCount count, RequestMatcher requestMatcher) { return getDelegate().expectRequest(count, requestMatcher); } @Override - public ClientHttpResponse validateRequest(ClientHttpRequest request) - throws IOException { + public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException { return getDelegate().validateRequest(request); } @@ -104,24 +99,18 @@ public class MockRestServiceServerAutoConfiguration { @Override public void reset() { - Map expectationManagers = this.customizer - .getExpectationManagers(); + Map expectationManagers = this.customizer.getExpectationManagers(); if (expectationManagers.size() == 1) { getDelegate().reset(); } } private RequestExpectationManager getDelegate() { - Map expectationManagers = this.customizer - .getExpectationManagers(); - Assert.state(!expectationManagers.isEmpty(), - "Unable to use auto-configured MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to " - + "a RestTemplate"); - Assert.state(expectationManagers.size() == 1, - "Unable to use auto-configured MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to " - + "more than one RestTemplate"); + Map expectationManagers = this.customizer.getExpectationManagers(); + Assert.state(!expectationManagers.isEmpty(), "Unable to use auto-configured MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to " + "a RestTemplate"); + Assert.state(expectationManagers.size() == 1, "Unable to use auto-configured MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to " + "more than one RestTemplate"); return expectationManagers.values().iterator().next(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java index aa3ea1e8178..f3adf553a8a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.test.web.client.MockRestServiceServer; * * @author Phillip Webb */ -class MockRestServiceServerResetTestExecutionListener - extends AbstractTestExecutionListener { +class MockRestServiceServerResetTestExecutionListener extends AbstractTestExecutionListener { @Override public int getOrder() { @@ -39,8 +38,7 @@ class MockRestServiceServerResetTestExecutionListener @Override public void afterTestMethod(TestContext testContext) throws Exception { ApplicationContext applicationContext = testContext.getApplicationContext(); - String[] names = applicationContext - .getBeanNamesForType(MockRestServiceServer.class, false, false); + String[] names = applicationContext.getBeanNamesForType(MockRestServiceServer.class, false, false); for (String name : names) { applicationContext.getBean(name, MockRestServiceServer.class).reset(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java index 2876cc86b43..c81d01cfb85 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java @@ -31,8 +31,7 @@ import org.springframework.util.ClassUtils; * * @author Stephane Nicoll */ -class RestClientExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class RestClientExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { private static final Class[] NO_COMPONENTS = {}; @@ -42,15 +41,13 @@ class RestClientExcludeFilter static { Set> includes = new LinkedHashSet<>(); - if (ClassUtils.isPresent(DATABIND_MODULE_CLASS_NAME, - RestClientExcludeFilter.class.getClassLoader())) { + if (ClassUtils.isPresent(DATABIND_MODULE_CLASS_NAME, RestClientExcludeFilter.class.getClassLoader())) { try { includes.add(Class.forName(DATABIND_MODULE_CLASS_NAME, true, RestClientExcludeFilter.class.getClassLoader())); } catch (ClassNotFoundException ex) { - throw new IllegalStateException( - "Failed to load " + DATABIND_MODULE_CLASS_NAME, ex); + throw new IllegalStateException("Failed to load " + DATABIND_MODULE_CLASS_NAME, ex); } includes.add(JsonComponent.class); } @@ -61,8 +58,7 @@ class RestClientExcludeFilter RestClientExcludeFilter(Class testClass) { super(testClass); - this.components = getAnnotation().getValue("components", Class[].class) - .orElse(NO_COMPONENTS); + this.components = getAnnotation().getValue("components", Class[].class).orElse(NO_COMPONENTS); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java index 520a4c9b0e6..b96c685b485 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java @@ -30,9 +30,8 @@ class RestClientTestContextBootstrapper extends SpringBootTestContextBootstrappe @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(RestClientTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(RestClientTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/SpringBootWebTestClientBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/SpringBootWebTestClientBuilderCustomizer.java index 99ac22b1394..cbd1a203d0f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/SpringBootWebTestClientBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/SpringBootWebTestClientBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies; * @author Andy Wilkinson * @since 2.0.0 */ -public class SpringBootWebTestClientBuilderCustomizer - implements WebTestClientBuilderCustomizer { +public class SpringBootWebTestClientBuilderCustomizer implements WebTestClientBuilderCustomizer { private final Collection codecCustomizers; @@ -48,8 +47,7 @@ public class SpringBootWebTestClientBuilderCustomizer * the builder's codecs using the given {@code codecCustomizers}. * @param codecCustomizers the codec customizers */ - public SpringBootWebTestClientBuilderCustomizer( - Collection codecCustomizers) { + public SpringBootWebTestClientBuilderCustomizer(Collection codecCustomizers) { this.codecCustomizers = codecCustomizers; } @@ -67,15 +65,13 @@ public class SpringBootWebTestClientBuilderCustomizer private void customizeWebTestClientCodecs(WebTestClient.Builder builder) { if (!CollectionUtils.isEmpty(this.codecCustomizers)) { - builder.exchangeStrategies(ExchangeStrategies.builder() - .codecs(applyCustomizers(this.codecCustomizers)).build()); + builder.exchangeStrategies( + ExchangeStrategies.builder().codecs(applyCustomizers(this.codecCustomizers)).build()); } } - private Consumer applyCustomizers( - Collection customizers) { - return (codecs) -> customizers - .forEach((customizer) -> customizer.customize(codecs)); + private Consumer applyCustomizers(Collection customizers) { + return (codecs) -> customizers.forEach((customizer) -> customizer.customize(codecs)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java index 3127ca7cb72..8f25e8c04e3 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java @@ -32,17 +32,14 @@ import org.springframework.test.context.TestContextBootstrapper; class WebFluxTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override - protected MergedContextConfiguration processMergedContextConfiguration( - MergedContextConfiguration mergedConfig) { - return new ReactiveWebMergedContextConfiguration( - super.processMergedContextConfiguration(mergedConfig)); + protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) { + return new ReactiveWebMergedContextConfiguration(super.processMergedContextConfiguration(mergedConfig)); } @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(WebFluxTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebFluxTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilter.java index bf25a0020ba..fb117e2f0f9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilter.java @@ -37,8 +37,7 @@ import org.springframework.web.server.WebExceptionHandler; * * @author Stephane Nicoll */ -class WebFluxTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class WebFluxTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { private static final Class[] NO_CONTROLLERS = {}; @@ -67,8 +66,7 @@ class WebFluxTypeExcludeFilter WebFluxTypeExcludeFilter(Class testClass) { super(testClass); - this.controllers = getAnnotation().getValue("controllers", Class[].class) - .orElse(NO_CONTROLLERS); + this.controllers = getAnnotation().getValue("controllers", Class[].class).orElse(NO_CONTROLLERS); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java index 9afcf23b670..6d3759d980d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java @@ -56,10 +56,8 @@ public class WebTestClientAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnBean(WebHandler.class) public WebTestClient webTestClient(ApplicationContext applicationContext, - List customizers, - List configurers) { - WebTestClient.MockServerSpec mockServerSpec = WebTestClient - .bindToApplicationContext(applicationContext); + List customizers, List configurers) { + WebTestClient.MockServerSpec mockServerSpec = WebTestClient.bindToApplicationContext(applicationContext); for (MockServerConfigurer configurer : configurers) { mockServerSpec.apply(configurer); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java index 736f6c8e1a0..b02d466c25b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java @@ -57,8 +57,7 @@ public class MockMvcAutoConfiguration { private final WebMvcProperties webMvcProperties; - MockMvcAutoConfiguration(WebApplicationContext context, - WebMvcProperties webMvcProperties) { + MockMvcAutoConfiguration(WebApplicationContext context, WebMvcProperties webMvcProperties) { this.context = context; this.webMvcProperties = webMvcProperties; } @@ -71,11 +70,9 @@ public class MockMvcAutoConfiguration { @Bean @ConditionalOnMissingBean(MockMvcBuilder.class) - public DefaultMockMvcBuilder mockMvcBuilder( - List customizers) { + public DefaultMockMvcBuilder mockMvcBuilder(List customizers) { DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.context); - builder.addDispatcherServletCustomizer( - new MockMvcDispatcherServletCustomizer(this.webMvcProperties)); + builder.addDispatcherServletCustomizer(new MockMvcDispatcherServletCustomizer(this.webMvcProperties)); for (MockMvcBuilderCustomizer customizer : customizers) { customizer.customize(builder); } @@ -100,8 +97,7 @@ public class MockMvcAutoConfiguration { return mockMvc.getDispatcherServlet(); } - private static class MockMvcDispatcherServletCustomizer - implements DispatcherServletCustomizer { + private static class MockMvcDispatcherServletCustomizer implements DispatcherServletCustomizer { private final WebMvcProperties webMvcProperties; @@ -111,12 +107,10 @@ public class MockMvcAutoConfiguration { @Override public void customize(DispatcherServlet dispatcherServlet) { - dispatcherServlet.setDispatchOptionsRequest( - this.webMvcProperties.isDispatchOptionsRequest()); - dispatcherServlet.setDispatchTraceRequest( - this.webMvcProperties.isDispatchTraceRequest()); - dispatcherServlet.setThrowExceptionIfNoHandlerFound( - this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); + dispatcherServlet.setDispatchOptionsRequest(this.webMvcProperties.isDispatchOptionsRequest()); + dispatcherServlet.setDispatchTraceRequest(this.webMvcProperties.isDispatchTraceRequest()); + dispatcherServlet + .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java index 1427476eefe..5ea1423d0e0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; * * @author Phillip Webb */ -class MockMvcPrintOnlyOnFailureTestExecutionListener - extends AbstractTestExecutionListener { +class MockMvcPrintOnlyOnFailureTestExecutionListener extends AbstractTestExecutionListener { @Override public int getOrder() { @@ -38,8 +37,7 @@ class MockMvcPrintOnlyOnFailureTestExecutionListener @Override public void afterTestMethod(TestContext testContext) throws Exception { if (testContext.getTestException() != null) { - DeferredLinesWriter writer = DeferredLinesWriter - .get(testContext.getApplicationContext()); + DeferredLinesWriter writer = DeferredLinesWriter.get(testContext.getApplicationContext()); if (writer != null) { writer.writeDeferredResult(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java index 66828c59c40..8ddb1311b04 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java @@ -58,8 +58,7 @@ class MockMvcSecurityConfiguration { builder.apply(new MockMvcConfigurerAdapter() { @Override - public RequestPostProcessor beforeMockMvcCreated( - ConfigurableMockMvcBuilder builder, + public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, WebApplicationContext context) { return SecurityMockMvcRequestPostProcessors.testSecurityContext(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java index 365c051aac8..07bb09cb0a7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java @@ -39,17 +39,14 @@ import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(WebClient.class) @AutoConfigureAfter(MockMvcAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.test.mockmvc.webclient", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.test.mockmvc.webclient", name = "enabled", matchIfMissing = true) public class MockMvcWebClientAutoConfiguration { @Bean @ConditionalOnMissingBean({ WebClient.class, MockMvcWebClientBuilder.class }) @ConditionalOnBean(MockMvc.class) - public MockMvcWebClientBuilder mockMvcWebClientBuilder(MockMvc mockMvc, - Environment environment) { - return MockMvcWebClientBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebClient(environment)); + public MockMvcWebClientBuilder mockMvcWebClientBuilder(MockMvc mockMvc, Environment environment) { + return MockMvcWebClientBuilder.mockMvcSetup(mockMvc).withDelegate(new LocalHostWebClient(environment)); } @Bean diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java index 601f24fb0f9..93b048db073 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java @@ -45,8 +45,7 @@ import org.springframework.util.ClassUtils; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(HtmlUnitDriver.class) @AutoConfigureAfter(MockMvcAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.test.mockmvc.webdriver", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.test.mockmvc.webdriver", name = "enabled", matchIfMissing = true) public class MockMvcWebDriverAutoConfiguration { private static final String SECURITY_CONTEXT_EXECUTOR = "org.springframework.security.concurrent.DelegatingSecurityContextExecutor"; @@ -54,11 +53,9 @@ public class MockMvcWebDriverAutoConfiguration { @Bean @ConditionalOnMissingBean({ WebDriver.class, MockMvcHtmlUnitDriverBuilder.class }) @ConditionalOnBean(MockMvc.class) - public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc, - Environment environment) { + public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc, Environment environment) { return MockMvcHtmlUnitDriverBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(environment, - BrowserVersion.CHROME)); + .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(environment, BrowserVersion.CHROME)); } @Bean @@ -66,10 +63,8 @@ public class MockMvcWebDriverAutoConfiguration { @ConditionalOnBean(MockMvcHtmlUnitDriverBuilder.class) public HtmlUnitDriver htmlUnitDriver(MockMvcHtmlUnitDriverBuilder builder) { HtmlUnitDriver driver = builder.build(); - if (ClassUtils.isPresent(SECURITY_CONTEXT_EXECUTOR, - getClass().getClassLoader())) { - driver.setExecutor(new DelegatingSecurityContextExecutor( - Executors.newSingleThreadExecutor())); + if (ClassUtils.isPresent(SECURITY_CONTEXT_EXECUTOR, getClass().getClassLoader())) { + driver.setExecutor(new DelegatingSecurityContextExecutor(Executors.newSingleThreadExecutor())); } return driver; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java index 775861ae273..a59c6f9c61b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,8 +114,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi .forEach((registration) -> addFilter(builder, registration)); } - private void addFilter(ConfigurableMockMvcBuilder builder, - AbstractFilterRegistrationBean registration) { + private void addFilter(ConfigurableMockMvcBuilder builder, AbstractFilterRegistrationBean registration) { Filter filter = registration.getFilter(); Collection urls = registration.getUrlPatterns(); if (urls.isEmpty()) { @@ -232,8 +231,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) { Assert.state(context instanceof ConfigurableApplicationContext, "A ConfigurableApplicationContext is required for printOnlyOnFailure"); - ((ConfigurableApplicationContext) context).getBeanFactory() - .registerSingleton(BEAN_NAME, this); + ((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton(BEAN_NAME, this); this.delegate = delegate; } @@ -262,8 +260,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi */ private static class LoggingLinesWriter implements LinesWriter { - private static final Log logger = LogFactory - .getLog("org.springframework.test.web.servlet.result"); + private static final Log logger = LogFactory.getLog("org.springframework.test.web.servlet.result"); @Override public void write(List lines) { @@ -310,24 +307,19 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi private static class FilterRegistrationBeans extends ServletContextInitializerBeans { FilterRegistrationBeans(ListableBeanFactory beanFactory) { - super(beanFactory, FilterRegistrationBean.class, - DelegatingFilterProxyRegistrationBean.class); + super(beanFactory, FilterRegistrationBean.class, DelegatingFilterProxyRegistrationBean.class); } @Override protected void addAdaptableBeans(ListableBeanFactory beanFactory) { - addAsRegistrationBean(beanFactory, Filter.class, - new FilterRegistrationBeanAdapter()); + addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter()); } - private static class FilterRegistrationBeanAdapter - implements RegistrationBeanAdapter { + private static class FilterRegistrationBeanAdapter implements RegistrationBeanAdapter { @Override - public RegistrationBean createRegistrationBean(String name, Filter source, - int totalNumberOfSourceBeans) { - FilterRegistrationBean bean = new FilterRegistrationBean<>( - source); + public RegistrationBean createRegistrationBean(String name, Filter source, int totalNumberOfSourceBeans) { + FilterRegistrationBean bean = new FilterRegistrationBean<>(source); bean.setName(name); return bean; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java index cda2e50aae4..2c2daad574c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ class WebDriverContextCustomizerFactory implements ContextCustomizerFactory { private static class Customizer implements ContextCustomizer { @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { WebDriverScope.registerWith(context); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java index fac9e5c36fe..4461a22d60d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,11 +117,9 @@ class WebDriverScope implements Scope { context.addBeanFactoryPostProcessor(WebDriverScope::postProcessBeanFactory); } - private static void postProcessBeanFactory( - ConfigurableListableBeanFactory beanFactory) { + private static void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { for (String beanClass : BEAN_CLASSES) { - for (String beanName : beanFactory - .getBeanNamesForType(ClassUtils.resolveClassName(beanClass, null))) { + for (String beanName : beanFactory.getBeanNamesForType(ClassUtils.resolveClassName(beanClass, null))) { BeanDefinition definition = beanFactory.getBeanDefinition(beanName); if (!StringUtils.hasLength(definition.getScope())) { definition.setScope(NAME); @@ -137,8 +135,7 @@ class WebDriverScope implements Scope { */ public static WebDriverScope getFrom(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext) { - Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory() - .getRegisteredScope(NAME); + Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory().getRegisteredScope(NAME); return (scope instanceof WebDriverScope) ? (WebDriverScope) scope : null; } return null; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java index 247cc012640..f192bbb1182 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,11 +38,9 @@ class WebDriverTestExecutionListener extends AbstractTestExecutionListener { @Override public void afterTestMethod(TestContext testContext) throws Exception { - WebDriverScope scope = WebDriverScope - .getFrom(testContext.getApplicationContext()); + WebDriverScope scope = WebDriverScope.getFrom(testContext.getApplicationContext()); if (scope != null && scope.reset()) { - testContext.setAttribute( - DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, + testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, Boolean.TRUE); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java index db0be79cf79..7d7b0c55ffd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java @@ -32,17 +32,14 @@ import org.springframework.test.context.web.WebMergedContextConfiguration; class WebMvcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override - protected MergedContextConfiguration processMergedContextConfiguration( - MergedContextConfiguration mergedConfig) { - return new WebMergedContextConfiguration( - super.processMergedContextConfiguration(mergedConfig), ""); + protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) { + return new WebMergedContextConfiguration(super.processMergedContextConfiguration(mergedConfig), ""); } @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(WebMvcTest.class).getValue("properties", String[].class) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebMvcTest.class) + .getValue("properties", String[].class).orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java index d392d83ccfa..28260e5f8b7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java @@ -43,8 +43,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @author Phillip Webb * @author Madhura Bhave */ -class WebMvcTypeExcludeFilter - extends StandardAnnotationCustomizableTypeExcludeFilter { +class WebMvcTypeExcludeFilter extends StandardAnnotationCustomizableTypeExcludeFilter { private static final Class[] NO_CONTROLLERS = {}; @@ -89,8 +88,7 @@ class WebMvcTypeExcludeFilter WebMvcTypeExcludeFilter(Class testClass) { super(testClass); - this.controllers = getAnnotation().getValue("controllers", Class[].class) - .orElse(NO_CONTROLLERS); + this.controllers = getAnnotation().getValue("controllers", Class[].class).orElse(NO_CONTROLLERS); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java index 7cd787a4de8..d1c789359a0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.context.ApplicationContext; * * @author Andy Wilkinson */ -public final class AutoConfigurationImportedCondition - extends Condition { +public final class AutoConfigurationImportedCondition extends Condition { private final Class autoConfigurationClass; @@ -41,10 +40,8 @@ public final class AutoConfigurationImportedCondition @Override public boolean matches(ApplicationContext context) { ConditionEvaluationReport report = ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) context - .getAutowireCapableBeanFactory()); - return report.getConditionAndOutcomesBySource() - .containsKey(this.autoConfigurationClass.getName()); + .get((ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory()); + return report.getConditionAndOutcomesBySource().containsKey(this.autoConfigurationClass.getName()); } /** @@ -53,8 +50,7 @@ public final class AutoConfigurationImportedCondition * @param autoConfigurationClass the auto-configuration class * @return the condition */ - public static AutoConfigurationImportedCondition importedAutoConfiguration( - Class autoConfigurationClass) { + public static AutoConfigurationImportedCondition importedAutoConfiguration(Class autoConfigurationClass) { return new AutoConfigurationImportedCondition(autoConfigurationClass); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java index a8f4a66fb8a..65e1ca1af75 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,31 +33,26 @@ public class OverrideAutoConfigurationContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null); assertThat(customizer).isNull(); } @Test public void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithAnnotationEnabledTrue.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledTrue.class, null); assertThat(customizer).isNull(); } @Test public void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithAnnotationEnabledFalse.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null); assertThat(customizer).isNotNull(); } @Test public void hashCodeAndEquals() { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(WithAnnotationEnabledFalse.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(WithSameAnnotation.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameAnnotation.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java index 470dc7bee9b..4307da33515 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java @@ -51,8 +51,7 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests { @Test public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() { Ordered injectionListener = new DependencyInjectionTestExecutionListener(); - assertThat(this.reportListener.getOrder()) - .isEqualTo(injectionListener.getOrder()); + assertThat(this.reportListener.getOrder()).isEqualTo(injectionListener.getOrder()); } @Test @@ -82,8 +81,7 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); given(testContext.getApplicationContext()).willThrow(new RuntimeException()); - assertThatIllegalStateException() - .isThrownBy(() -> this.reportListener.prepareTestInstance(testContext)) + assertThatIllegalStateException().isThrownBy(() -> this.reportListener.prepareTestInstance(testContext)) .isEqualTo(originalFailure); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java index 0055c7af222..f07e9335ace 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java @@ -48,8 +48,7 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { static ApplicationContext contextFromTest; @Test - public void testClassesThatHaveSameAnnotationsShareAContext() - throws InitializationError { + public void testClassesThatHaveSameAnnotationsShareAContext() throws InitializationError { RunNotifier notifier = new RunNotifier(); new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); ApplicationContext test1Context = contextFromTest; @@ -59,8 +58,7 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { } @Test - public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() - throws InitializationError { + public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() throws InitializationError { RunNotifier notifier = new RunNotifier(); new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); ApplicationContext test1Context = contextFromTest; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java index 8f6a8c68ec6..35f55e8ce68 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java @@ -59,36 +59,31 @@ public class DataJdbcTestIntegrationTests { @Test public void testRepository() { - this.jdbcTemplate.update( - "INSERT INTO EXAMPLE_ENTITY (id, name, reference) VALUES (1, 'a', 'alpha')"); - this.jdbcTemplate.update( - "INSERT INTO EXAMPLE_ENTITY (id, name, reference) VALUES (2, 'b', 'bravo')"); + this.jdbcTemplate.update("INSERT INTO EXAMPLE_ENTITY (id, name, reference) VALUES (1, 'a', 'alpha')"); + this.jdbcTemplate.update("INSERT INTO EXAMPLE_ENTITY (id, name, reference) VALUES (2, 'b', 'bravo')"); assertThat(this.repository.findAll()).hasSize(2); } @Test public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @Test public void didNotInjectExampleComponent() { - assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( - () -> this.applicationContext.getBean(ExampleComponent.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test public void flywayAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FlywayAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test public void liquibaseAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/ExampleDataJdbcApplication.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/ExampleDataJdbcApplication.java index 87ae71e2110..8544b5a5301 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/ExampleDataJdbcApplication.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/ExampleDataJdbcApplication.java @@ -34,8 +34,7 @@ public class ExampleDataJdbcApplication { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java index c7bd76c1a1d..5f5f01a5aa9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,11 +59,10 @@ public class DataLdapTestIntegrationTests { LdapQuery ldapQuery = LdapQueryBuilder.query().where("cn").is("Bob Smith"); Optional entry = this.exampleRepository.findOne(ldapQuery); assertThat(entry.isPresent()).isTrue(); - assertThat(entry.get().getDn()).isEqualTo(LdapUtils - .newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); + assertThat(entry.get().getDn()) + .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); assertThat(this.ldapTemplate.findOne(ldapQuery, ExampleEntry.class).getDn()) - .isEqualTo(LdapUtils.newLdapName( - "cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); + .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java index ce50530d4e4..8f83f0cacd9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java @@ -46,11 +46,9 @@ public class DataMongoTestReactiveIntegrationTests { public void testRepository() { ExampleDocument exampleDocument = new ExampleDocument(); exampleDocument.setText("Look, new @DataMongoTest!"); - exampleDocument = this.exampleRepository.save(exampleDocument) - .block(Duration.ofSeconds(30)); + exampleDocument = this.exampleRepository.save(exampleDocument).block(Duration.ofSeconds(30)); assertThat(exampleDocument.getId()).isNotNull(); - assertThat(this.mongoTemplate.collectionExists("exampleDocuments") - .block(Duration.ofSeconds(30))).isTrue(); + assertThat(this.mongoTemplate.collectionExists("exampleDocuments").block(Duration.ofSeconds(30))).isTrue(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/ExampleReactiveRepository.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/ExampleReactiveRepository.java index eb825b20f0f..9c8fad0a02d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/ExampleReactiveRepository.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/ExampleReactiveRepository.java @@ -23,7 +23,6 @@ import org.springframework.data.mongodb.repository.ReactiveMongoRepository; * * @author Stephane Nicoll */ -public interface ExampleReactiveRepository - extends ReactiveMongoRepository { +public interface ExampleReactiveRepository extends ReactiveMongoRepository { } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java index 627341d5d73..5c13527cad8 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java @@ -75,14 +75,11 @@ public class DataNeo4jTestIntegrationTests { .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override - public void initialize( - ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues - .of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java index 06f06a15b0d..3c1c3bdc23e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Artsiom Yudovin */ @Testcontainers -@ContextConfiguration( - initializers = DataNeo4jTestPropertiesIntegrationTests.Initializer.class) +@ContextConfiguration(initializers = DataNeo4jTestPropertiesIntegrationTests.Initializer.class) @DataNeo4jTest(properties = "spring.profiles.active=test") public class DataNeo4jTestPropertiesIntegrationTests { @@ -55,14 +54,11 @@ public class DataNeo4jTestPropertiesIntegrationTests { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override - public void initialize( - ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues - .of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java index b1f432a5b59..69be3c4a886 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Michael Simons */ @Testcontainers -@ContextConfiguration( - initializers = DataNeo4jTestWithIncludeFilterIntegrationTests.Initializer.class) +@ContextConfiguration(initializers = DataNeo4jTestWithIncludeFilterIntegrationTests.Initializer.class) @DataNeo4jTest(includeFilters = @Filter(Service.class)) public class DataNeo4jTestWithIncludeFilterIntegrationTests { @@ -56,14 +55,11 @@ public class DataNeo4jTestWithIncludeFilterIntegrationTests { assertThat(this.service.hasNode(ExampleGraph.class)).isFalse(); } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override - public void initialize( - ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues - .of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java index bcff44c84ce..f736feb418f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java @@ -79,12 +79,10 @@ public class DataRedisTestIntegrationTests { .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override - public void initialize( - ConfigurableApplicationContext configurableApplicationContext) { + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java index c4094f96a27..55c21c5ef0b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java @@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Artsiom Yudovin */ @Testcontainers -@ContextConfiguration( - initializers = DataRedisTestPropertiesIntegrationTests.Initializer.class) +@ContextConfiguration(initializers = DataRedisTestPropertiesIntegrationTests.Initializer.class) @DataRedisTest(properties = "spring.profiles.active=test") public class DataRedisTestPropertiesIntegrationTests { @@ -53,12 +52,10 @@ public class DataRedisTestPropertiesIntegrationTests { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override - public void initialize( - ConfigurableApplicationContext configurableApplicationContext) { + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java index 0f5dbd01cd4..fa76c11dd3b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java @@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Jayaram Pradhan */ @Testcontainers -@ContextConfiguration( - initializers = DataRedisTestWithIncludeFilterIntegrationTests.Initializer.class) +@ContextConfiguration(initializers = DataRedisTestWithIncludeFilterIntegrationTests.Initializer.class) @DataRedisTest(includeFilters = @Filter(Service.class)) public class DataRedisTestWithIncludeFilterIntegrationTests { @@ -60,12 +59,10 @@ public class DataRedisTestWithIncludeFilterIntegrationTests { assertThat(this.service.hasRecord(savedEntity)).isTrue(); } - static class Initializer - implements ApplicationContextInitializer { + static class Initializer implements ApplicationContextInitializer { @Override - public void initialize( - ConfigurableApplicationContext configurableApplicationContext) { + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java index 9b3af49ef68..5e2f28f4704 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java @@ -40,8 +40,8 @@ public class ExampleService { } public boolean hasRecord(PersonHash personHash) { - return this.operations.execute((RedisConnection connection) -> connection - .exists(("persons:" + personHash.getId()).getBytes(CHARSET))); + return this.operations.execute( + (RedisConnection connection) -> connection.exists(("persons:" + personHash.getId()).getBytes(CHARSET))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java index 4a37dacbb8f..82c213012aa 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java @@ -83,11 +83,9 @@ public class FilterAnnotationsTests { return new FilterAnnotations(getClass().getClassLoader(), filters.value()); } - private boolean match(FilterAnnotations filterAnnotations, Class type) - throws IOException { + private boolean match(FilterAnnotations filterAnnotations, Class type) throws IOException { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); - MetadataReader metadataReader = metadataReaderFactory - .getMetadataReader(type.getName()); + MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type.getName()); return filterAnnotations.anyMatches(metadataReader, metadataReaderFactory); } @@ -96,8 +94,7 @@ public class FilterAnnotationsTests { } - @Filters(@Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = ExampleWithoutAnnotation.class)) + @Filters(@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ExampleWithoutAnnotation.class)) static class FilterByType { } @@ -107,8 +104,7 @@ public class FilterAnnotationsTests { } - @Filters(@Filter(type = FilterType.ASPECTJ, - pattern = "(*..*ExampleWithoutAnnotation)")) + @Filters(@Filter(type = FilterType.ASPECTJ, pattern = "(*..*ExampleWithoutAnnotation)")) static class FilterByAspectJ { } @@ -130,10 +126,8 @@ public class FilterAnnotationsTests { static class ExampleCustomFilter implements TypeFilter { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) { - return metadataReader.getClassMetadata().getClassName() - .equals(ExampleWithoutAnnotation.class.getName()); + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { + return metadataReader.getClassMetadata().getClassName().equals(ExampleWithoutAnnotation.class.getName()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java index bcc280ed381..03fc511a784 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,54 +39,43 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests { private TypeExcludeFiltersContextCustomizerFactory factory = new TypeExcludeFiltersContextCustomizerFactory(); - private MergedContextConfiguration mergedContextConfiguration = mock( - MergedContextConfiguration.class); + private MergedContextConfiguration mergedContextConfiguration = mock(MergedContextConfiguration.class); private ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); @Test public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null); assertThat(customizer).isNull(); } @Test public void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithExcludeFilters.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null); assertThat(customizer).isNotNull(); } @Test public void hashCodeAndEquals() { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(WithExcludeFilters.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(WithSameExcludeFilters.class, null); - ContextCustomizer customizer3 = this.factory - .createContextCustomizer(WithDifferentExcludeFilters.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithExcludeFilters.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameExcludeFilters.class, null); + ContextCustomizer customizer3 = this.factory.createContextCustomizer(WithDifferentExcludeFilters.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); - assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2) - .isNotEqualTo(customizer3); + assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); } @Test public void getContextCustomizerShouldAddExcludeFilters() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithExcludeFilters.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null); customizer.customizeContext(this.context, this.mergedContextConfiguration); this.context.refresh(); TypeExcludeFilter filter = this.context.getBean(TypeExcludeFilter.class); MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); - MetadataReader metadataReader = metadataReaderFactory - .getMetadataReader(NoAnnotation.class.getName()); + MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NoAnnotation.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); - metadataReader = metadataReaderFactory - .getMetadataReader(SimpleExclude.class.getName()); + metadataReader = metadataReaderFactory.getMetadataReader(SimpleExclude.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); - metadataReader = metadataReaderFactory - .getMetadataReader(TestClassAwareExclude.class.getName()); + metadataReader = metadataReaderFactory.getMetadataReader(TestClassAwareExclude.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); } @@ -112,10 +101,8 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests { static class SimpleExclude extends TypeExcludeFilter { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) { - return metadataReader.getClassMetadata().getClassName() - .equals(getClass().getName()); + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { + return metadataReader.getClassMetadata().getClassName().equals(getClass().getName()); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java index 2269014fd07..f388d65c2a2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java @@ -49,8 +49,7 @@ public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests { @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // Look that the datasource is replaced with an H2 DB. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("H2"); } @@ -61,14 +60,12 @@ public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests { @Bean @Primary public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } @Bean public DataSource secondaryDataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java index e396a0b67b3..583d13fecae 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java @@ -34,8 +34,7 @@ public class ExampleJdbcApplication { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java index 60391107f7a..e8bd43e81dc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java @@ -44,13 +44,11 @@ public class ExampleRepository { @Transactional public void save(ExampleEntity entity) { - this.jdbcTemplate.update("insert into example (id, name) values (?, ?)", - entity.getId(), entity.getName()); + this.jdbcTemplate.update("insert into example (id, name) values (?, ?)", entity.getId(), entity.getName()); } public ExampleEntity findById(int id) { - return this.jdbcTemplate.queryForObject( - "select id, name from example where id =?", new Object[] { id }, + return this.jdbcTemplate.queryForObject("select id, name from example where id =?", new Object[] { id }, ROW_MAPPER); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java index e03585cc5ba..489c3edca10 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java @@ -69,27 +69,24 @@ public class JdbcTestIntegrationTests { @Test public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @Test public void didNotInjectExampleRepository() { - assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( - () -> this.applicationContext.getBean(ExampleRepository.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleRepository.class)); } @Test public void flywayAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FlywayAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test public void liquibaseAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java index 32a22c79954..01eb8942d29 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java @@ -46,8 +46,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrati @Test public void replacesAutoConfiguredDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java index 4b3ada155b9..a1f717f3b8a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java @@ -42,8 +42,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOv @Test public void usesDefaultEmbeddedDatabase() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); // @AutoConfigureTestDatabase would use H2 but HSQL is manually defined assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java index 6e24491e1b8..1801654b6ba 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java @@ -49,8 +49,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTest @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } @@ -60,8 +59,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTest @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.H2).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.H2).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java index 5dd218155a5..d10dfed32e6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java @@ -43,8 +43,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests { @Test public void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java index baba41ab47e..77e5d8f533f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java @@ -51,8 +51,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationT @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } @@ -62,8 +61,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationT @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.H2).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.H2).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java index 9e546b43aa7..1a47260d79e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java @@ -47,8 +47,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredI @Test public void replacesAutoConfiguredDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java index df1404a0187..fa314fc72d1 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java @@ -44,8 +44,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegration @Test public void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index f41bf1c42c9..61d0644992b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -39,33 +39,25 @@ import static org.assertj.core.api.Assertions.assertThat; public class TestDatabaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test public void replaceWithNoDataSourceAvailable() { - this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); } @Test public void replaceWithUniqueDatabase() { - this.contextRunner.withUserConfiguration(ExistingDataSourceConfiguration.class) - .run((context) -> { - DataSource datasource = context.getBean(DataSource.class); - JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); - jdbcTemplate.execute("create table example (id int, name varchar);"); - this.contextRunner - .withUserConfiguration(ExistingDataSourceConfiguration.class) - .run((secondContext) -> { - DataSource anotherDatasource = secondContext - .getBean(DataSource.class); - JdbcTemplate anotherJdbcTemplate = new JdbcTemplate( - anotherDatasource); - anotherJdbcTemplate.execute( - "create table example (id int, name varchar);"); - }); - }); + this.contextRunner.withUserConfiguration(ExistingDataSourceConfiguration.class).run((context) -> { + DataSource datasource = context.getBean(DataSource.class); + JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); + jdbcTemplate.execute("create table example (id int, name varchar);"); + this.contextRunner.withUserConfiguration(ExistingDataSourceConfiguration.class).run((secondContext) -> { + DataSource anotherDatasource = secondContext.getBean(DataSource.class); + JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); + anotherJdbcTemplate.execute("create table example (id int, name varchar);"); + }); + }); } @Configuration(proxyBeanMethods = false) @@ -73,8 +65,7 @@ public class TestDatabaseAutoConfigurationTests { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/ExampleJooqApplication.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/ExampleJooqApplication.java index 80f1c761222..6b01cf34ea1 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/ExampleJooqApplication.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/ExampleJooqApplication.java @@ -34,8 +34,7 @@ public class ExampleJooqApplication { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java index dc6620f1d78..0b551510047 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java @@ -55,34 +55,31 @@ public class JooqTestIntegrationTests { @Test public void testDSLContext() { - assertThat(this.dsl.selectCount().from("INFORMATION_SCHEMA.TABLES").fetchOne(0, - Integer.class)).isGreaterThan(0); + assertThat(this.dsl.selectCount().from("INFORMATION_SCHEMA.TABLES").fetchOne(0, Integer.class)) + .isGreaterThan(0); } @Test public void useDefinedDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); assertThat(this.dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); } @Test public void didNotInjectExampleComponent() { - assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( - () -> this.applicationContext.getBean(ExampleComponent.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test public void flywayAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FlywayAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test public void liquibaseAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java index 9771321d23f..1ee0a771101 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java @@ -48,8 +48,7 @@ public class JooqTestWithAutoConfigureTestDatabaseIntegrationTests { @Test public void replacesAutoConfiguredDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("H2"); assertThat(this.dsl.configuration().dialect()).isEqualTo(SQLDialect.H2); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java index a83da6ef852..f42b7fb924d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java @@ -42,8 +42,8 @@ public class ExampleJsonComponent { public static class Serializer extends JsonObjectSerializer { @Override - protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen, SerializerProvider provider) + throws IOException { jgen.writeStringField("value", value.toString()); } @@ -52,11 +52,9 @@ public class ExampleJsonComponent { public static class Deserializer extends JsonObjectDeserializer { @Override - protected ExampleCustomObject deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException { - return new ExampleCustomObject( - nullSafeValue(tree.get("value"), String.class)); + protected ExampleCustomObject deserializeObject(JsonParser jsonParser, DeserializationContext context, + ObjectCodec codec, JsonNode tree) throws IOException { + return new ExampleCustomObject(nullSafeValue(tree.get("value"), String.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java index 15f95e2265d..17a3c58d99d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class ExampleJsonObjectWithView { return false; } ExampleJsonObjectWithView other = (ExampleJsonObjectWithView) obj; - return ObjectUtils.nullSafeEquals(this.value, other.value) - && ObjectUtils.nullSafeEquals(this.id, other.id); + return ObjectUtils.nullSafeEquals(this.value, other.value) && ObjectUtils.nullSafeEquals(this.id, other.id); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java index d486e43e43b..1ab344381bd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java @@ -42,8 +42,7 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor */ @RunWith(SpringRunner.class) @DataJpaTest -@TestPropertySource( - properties = "spring.jpa.hibernate.use-new-id-generator-mappings=false") +@TestPropertySource(properties = "spring.jpa.hibernate.use-new-id-generator-mappings=false") public class DataJpaTestIntegrationTests { @Autowired @@ -72,12 +71,10 @@ public class DataJpaTestIntegrationTests { @Test public void testEntityManagerPersistAndGetId() { - Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), - Long.class); + Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), Long.class); assertThat(id).isNotNull(); - String reference = this.jdbcTemplate.queryForObject( - "SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?", new Object[] { id }, - String.class); + String reference = this.jdbcTemplate.queryForObject("SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?", + new Object[] { id }, String.class); assertThat(reference).isEqualTo("123"); } @@ -92,27 +89,24 @@ public class DataJpaTestIntegrationTests { @Test public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @Test public void didNotInjectExampleComponent() { - assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( - () -> this.applicationContext.getBean(ExampleComponent.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test public void flywayAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FlywayAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test public void liquibaseAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java index 3a5fd09f66d..fe3a31156d8 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java @@ -34,8 +34,7 @@ public class ExampleDataJpaApplication { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseType.HSQL).build(); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java index b6bd70f18c0..b61059a9fca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java @@ -46,29 +46,22 @@ public class TestDatabaseAutoConfigurationNoEmbeddedTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(ExistingDataSourceConfiguration.class) - .withConfiguration( - AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test public void applyAnyReplace() { - this.contextRunner.run((context) -> assertThat(context).getFailure() - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining( - "Failed to replace DataSource with an embedded database for tests.") - .hasMessageContaining( - "If you want an embedded database please put a supported one on the classpath") - .hasMessageContaining( - "or tune the replace attribute of @AutoConfigureTestDatabase.")); + this.contextRunner.run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to replace DataSource with an embedded database for tests.") + .hasMessageContaining("If you want an embedded database please put a supported one on the classpath") + .hasMessageContaining("or tune the replace attribute of @AutoConfigureTestDatabase.")); } @Test public void applyNoReplace() { - this.contextRunner.withPropertyValues("spring.test.database.replace=NONE") - .run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).getBean(DataSource.class) - .isSameAs(context.getBean("myCustomDataSource")); - }); + this.contextRunner.withPropertyValues("spring.test.database.replace=NONE").run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).getBean(DataSource.class).isSameAs(context.getBean("myCustomDataSource")); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java index 3ab0d934f3c..344f066b2ea 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ public class TestEntityManagerTests { public void setup() { MockitoAnnotations.initMocks(this); this.testEntityManager = new TestEntityManager(this.entityManagerFactory); - given(this.entityManagerFactory.getPersistenceUnitUtil()) - .willReturn(this.persistenceUnitUtil); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); } @Test @@ -187,8 +186,7 @@ public class TestEntityManagerTests { public void getIdForTypeWhenTypeIsWrongShouldThrowException() { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) + assertThatIllegalArgumentException().isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " + "must be an instance of class java.lang.Long"); } @@ -204,14 +202,12 @@ public class TestEntityManagerTests { @Test public void getEntityManagerShouldGetEntityManager() { bindEntityManager(); - assertThat(this.testEntityManager.getEntityManager()) - .isEqualTo(this.entityManager); + assertThat(this.testEntityManager.getEntityManager()).isEqualTo(this.entityManager); } @Test public void getEntityManagerWhenNotSetShouldThrowException() { - assertThatIllegalStateException() - .isThrownBy(this.testEntityManager::getEntityManager) + assertThatIllegalStateException().isThrownBy(this.testEntityManager::getEntityManager) .withMessageContaining("No transactional EntityManager found"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java index 2eb1e82278f..8414653abca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java @@ -52,8 +52,8 @@ public class OverrideAutoConfigurationEnabledFalseIntegrationTests { public void disabledAutoConfiguration() { ApplicationContext context = this.context; assertThat(context.getBean(ExampleTestConfig.class)).isNotNull(); - assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( - () -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java index 3dd77c771d3..9e3b350abdc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java @@ -49,10 +49,8 @@ public class OverrideAutoConfigurationEnabledTrueIntegrationTests { @Test public void autoConfiguredContext() { ApplicationContext context = this.context; - assertThat(context.getBean(OverrideAutoConfigurationSpringBootApplication.class)) - .isNotNull(); - assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class)) - .isNotNull(); + assertThat(context.getBean(OverrideAutoConfigurationSpringBootApplication.class)).isNotNull(); + assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class)).isNotNull(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java index ceb29873ad5..856aab5f4c5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java @@ -36,15 +36,13 @@ public class AnnotationsPropertySourceTests { @Test public void createWhenSourceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new AnnotationsPropertySource(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new AnnotationsPropertySource(null)) .withMessageContaining("Property source must not be null"); } @Test public void propertiesWhenHasNoAnnotationShouldBeEmpty() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - NoAnnotation.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(NoAnnotation.class); assertThat(source.getPropertyNames()).isEmpty(); assertThat(source.getProperty("value")).isNull(); } @@ -58,40 +56,35 @@ public class AnnotationsPropertySourceTests { @Test public void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - TypeLevelWithPrefix.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test.value"); assertThat(source.getProperty("test.value")).isEqualTo("abc"); } @Test public void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - AttributeLevelWithPrefix.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(AttributeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test"); assertThat(source.getProperty("test")).isEqualTo("abc"); } @Test public void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - TypeAndAttributeLevelWithPrefix.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(TypeAndAttributeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test.example"); assertThat(source.getProperty("test.example")).isEqualTo("abc"); } @Test public void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - NotMappedAtTypeLevel.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtTypeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("ignore")).isNull(); } @Test public void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - NotMappedAtAttributeLevel.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtAttributeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("ignore")).isNull(); } @@ -99,10 +92,9 @@ public class AnnotationsPropertySourceTests { @Test public void propertiesWhenContainsArraysShouldExpandNames() { AnnotationsPropertySource source = new AnnotationsPropertySource(Arrays.class); - assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]", - "classes[0]", "classes[1]", "ints[0]", "ints[1]", "longs[0]", "longs[1]", - "floats[0]", "floats[1]", "doubles[0]", "doubles[1]", "booleans[0]", - "booleans[1]"); + assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]", "classes[0]", "classes[1]", + "ints[0]", "ints[1]", "longs[0]", "longs[1]", "floats[0]", "floats[1]", "doubles[0]", "doubles[1]", + "booleans[0]", "booleans[1]"); assertThat(source.getProperty("strings[0]")).isEqualTo("a"); assertThat(source.getProperty("strings[1]")).isEqualTo("b"); assertThat(source.getProperty("classes[0]")).isEqualTo(Integer.class); @@ -121,25 +113,21 @@ public class AnnotationsPropertySourceTests { @Test public void propertiesWhenHasCamelCaseShouldConvertToKebabCase() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - CamelCaseToKebabCase.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(CamelCaseToKebabCase.class); assertThat(source.getPropertyNames()).contains("camel-case-to-kebab-case"); } @Test public void propertiesFromMetaAnnotationsAreMapped() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertiesFromSingleMetaAnnotation.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromSingleMetaAnnotation.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("foo"); } @Test public void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertiesFromMultipleMetaAnnotations.class); - assertThat(source.getPropertyNames()).containsExactly("value", "test.value", - "test.example"); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromMultipleMetaAnnotations.class); + assertThat(source.getPropertyNames()).containsExactly("value", "test.value", "test.example"); assertThat(source.getProperty("value")).isEqualTo("alpha"); assertThat(source.getProperty("test.value")).isEqualTo("bravo"); assertThat(source.getProperty("test.example")).isEqualTo("charlie"); @@ -147,8 +135,7 @@ public class AnnotationsPropertySourceTests { @Test public void propertyMappedAttributesCanBeAliased() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertyMappedAttributeWithAnAlias.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAttributeWithAnAlias.class); assertThat(source.getPropertyNames()).containsExactly("aliasing.value"); assertThat(source.getProperty("aliasing.value")).isEqualTo("baz"); } @@ -160,8 +147,7 @@ public class AnnotationsPropertySourceTests { @Test public void typeLevelAnnotationOnSuperClass() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertyMappedAnnotationOnSuperClass.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAnnotationOnSuperClass.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("abc"); } @@ -176,15 +162,13 @@ public class AnnotationsPropertySourceTests { @Test public void enumValueMapped() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - EnumValueMapped.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueMapped.class); assertThat(source.getProperty("testenum.value")).isEqualTo(EnumItem.TWO); } @Test public void enumValueNotMapped() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - EnumValueNotMapped.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueNotMapped.class); assertThat(source.containsProperty("testenum.value")).isFalse(); } @@ -277,9 +261,8 @@ public class AnnotationsPropertySourceTests { } - @ArraysAnnotation(strings = { "a", "b" }, classes = { Integer.class, Long.class }, - ints = { 1, 2 }, longs = { 1, 2 }, floats = { 1.0f, 2.0f }, - doubles = { 1.0, 2.0 }, booleans = { false, true }) + @ArraysAnnotation(strings = { "a", "b" }, classes = { Integer.class, Long.class }, ints = { 1, 2 }, + longs = { 1, 2 }, floats = { 1.0f, 2.0f }, doubles = { 1.0, 2.0 }, booleans = { false, true }) static class Arrays { } @@ -380,8 +363,7 @@ public class AnnotationsPropertySourceTests { } - static class AliasedPropertyMappedAnnotationOnSuperClass - extends PropertyMappedAttributeWithAnAlias { + static class AliasedPropertyMappedAnnotationOnSuperClass extends PropertyMappedAttributeWithAnAlias { } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java index a044f39c91e..45eadf376d0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java @@ -46,13 +46,10 @@ public class PropertyMappingContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasNoMappingShouldNotAddPropertySource() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoMapping.class, null); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ContextCustomizer customizer = this.factory.createContextCustomizer(NoMapping.class, null); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - ConfigurableListableBeanFactory beanFactory = mock( - ConfigurableListableBeanFactory.class); + ConfigurableListableBeanFactory beanFactory = mock(ConfigurableListableBeanFactory.class); given(context.getEnvironment()).willReturn(environment); given(context.getBeanFactory()).willReturn(beanFactory); customizer.customizeContext(context, null); @@ -61,35 +58,28 @@ public class PropertyMappingContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasTypeMappingShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TypeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TypeMapping.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerWhenHasAttributeMappingShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); assertThat(customizer).isNotNull(); } @Test public void hashCodeAndEqualsShouldBeBasedOnPropertyValues() { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(TypeMapping.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(AttributeMapping.class, null); - ContextCustomizer customizer3 = this.factory - .createContextCustomizer(OtherMapping.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(TypeMapping.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer3 = this.factory.createContextCustomizer(OtherMapping.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); - assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2) - .isNotEqualTo(customizer3); + assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); } @Test public void prepareContextShouldAddPropertySource() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, null); assertThat(context.getEnvironment().getProperty("mapped")).isEqualTo("Mapped"); @@ -97,13 +87,11 @@ public class PropertyMappingContextCustomizerFactoryTests { @Test public void propertyMappingShouldNotBeUsedWithComponent() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(ConfigMapping.class); customizer.customizeContext(context, null); - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(context::refresh) + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(context::refresh) .withMessageContaining("The @PropertyMapping annotation " + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " + "cannot be used in combination with the @Component annotation @Configuration"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 06124cd7308..818adf9620a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -66,19 +66,17 @@ public class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTes @Before public void deleteSnippets() { - this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), - "generated-snippets"); + this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test public void snippetGeneration() throws Exception { - this.mvc.perform(get("/")).andDo(this.documentationHandler.document(links( - linkWithRel("self").description("Canonical location of this resource")))); + this.mvc.perform(get("/")).andDo(this.documentationHandler + .document(links(linkWithRel("self").description("Canonical location of this resource")))); File defaultSnippetsDir = new File(this.generatedSnippets, "snippet-generation"); assertThat(defaultSnippetsDir).exists(); - assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))) - .contains("'http://localhost:8080/'"); + assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'http://localhost:8080/'"); assertThat(new File(defaultSnippetsDir, "links.md")).isFile(); assertThat(new File(defaultSnippetsDir, "response-fields.md")).isFile(); } @@ -93,14 +91,13 @@ public class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTes @Bean public RestDocsMockMvcConfigurationCustomizer templateFormatCustomizer() { - return (configurer) -> configurer.snippets() - .withTemplateFormat(TemplateFormats.markdown()); + return (configurer) -> configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); } @Bean public RestDocsMockMvcConfigurationCustomizer defaultSnippetsCustomizer() { - return (configurer) -> configurer.snippets().withAdditionalDefaults( - responseFields(fieldWithPath("_links.self").description("Main URL"))); + return (configurer) -> configurer.snippets() + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java index d312485d82f..348bdd42bc2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ public class MockMvcRestDocsAutoConfigurationIntegrationTests { @Before public void deleteSnippets() { - this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), - "generated-snippets"); + this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @@ -61,10 +60,8 @@ public class MockMvcRestDocsAutoConfigurationIntegrationTests { this.mvc.perform(get("/")).andDo(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); - assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))) - .contains("'https://api.example.com/'"); - assertThat(contentOf(new File(defaultSnippetsDir, "http-request.adoc"))) - .contains("api.example.com"); + assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); + assertThat(contentOf(new File(defaultSnippetsDir, "http-request.adoc"))).contains("api.example.com"); assertThat(new File(defaultSnippetsDir, "http-response.adoc")).isFile(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 3a1d2c14a4d..d9afa9459e7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -67,8 +67,7 @@ public class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegratio @Before public void deleteSnippets() { - this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), - "generated-snippets"); + this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @@ -76,15 +75,12 @@ public class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegratio public void snippetGeneration() { given(this.documentationSpec) .filter(document("default-snippets", - preprocessRequest(modifyUris().scheme("https") - .host("api.example.com").removePort()))) + preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) .when().port(this.port).get("/").then().assertThat().statusCode(is(200)); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); - assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))) - .contains("'https://api.example.com/'"); - assertThat(contentOf(new File(defaultSnippetsDir, "http-request.md"))) - .contains("api.example.com"); + assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'https://api.example.com/'"); + assertThat(contentOf(new File(defaultSnippetsDir, "http-request.md"))).contains("api.example.com"); assertThat(new File(defaultSnippetsDir, "http-response.md")).isFile(); assertThat(new File(defaultSnippetsDir, "response-fields.md")).isFile(); } @@ -99,14 +95,13 @@ public class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegratio @Bean public RestDocsRestAssuredConfigurationCustomizer templateFormatCustomizer() { - return (configurer) -> configurer.snippets() - .withTemplateFormat(TemplateFormats.markdown()); + return (configurer) -> configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); } @Bean public RestDocsRestAssuredConfigurationCustomizer defaultSnippetsCustomizer() { - return (configurer) -> configurer.snippets().withAdditionalDefaults( - responseFields(fieldWithPath("_links.self").description("Main URL"))); + return (configurer) -> configurer.snippets() + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java index 822d5e450de..cf96361e618 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java @@ -59,8 +59,7 @@ public class RestAssuredRestDocsAutoConfigurationIntegrationTests { @Before public void deleteSnippets() { - this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), - "generated-snippets"); + this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @@ -68,15 +67,12 @@ public class RestAssuredRestDocsAutoConfigurationIntegrationTests { public void defaultSnippetsAreWritten() { given(this.documentationSpec) .filter(document("default-snippets", - preprocessRequest(modifyUris().scheme("https") - .host("api.example.com").removePort()))) + preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) .when().port(this.port).get("/").then().assertThat().statusCode(is(200)); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); - assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))) - .contains("'https://api.example.com/'"); - assertThat(contentOf(new File(defaultSnippetsDir, "http-request.adoc"))) - .contains("api.example.com"); + assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); + assertThat(contentOf(new File(defaultSnippetsDir, "http-request.adoc"))).contains("api.example.com"); assertThat(new File(defaultSnippetsDir, "http-response.adoc")).isFile(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index db94099da61..aa73c5dbfcb 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,21 +59,18 @@ public class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrat @Before public void deleteSnippets() { - this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), - "generated-snippets"); + this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test public void defaultSnippetsAreWritten() throws Exception { - this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful() - .expectBody().consumeWith(document("default-snippets")); + this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() + .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); - assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))) - .contains("'https://api.example.com/'"); - assertThat(contentOf(new File(defaultSnippetsDir, "http-request.md"))) - .contains("api.example.com"); + assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'https://api.example.com/'"); + assertThat(contentOf(new File(defaultSnippetsDir, "http-request.md"))).contains("api.example.com"); assertThat(new File(defaultSnippetsDir, "http-response.md")).isFile(); assertThat(new File(defaultSnippetsDir, "response-fields.md")).isFile(); } @@ -88,14 +85,13 @@ public class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrat @Bean public RestDocsWebTestClientConfigurationCustomizer templateFormatCustomizer() { - return (configurer) -> configurer.snippets() - .withTemplateFormat(TemplateFormats.markdown()); + return (configurer) -> configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); } @Bean public RestDocsWebTestClientConfigurationCustomizer defaultSnippetsCustomizer() { - return (configurer) -> configurer.snippets().withAdditionalDefaults( - responseFields(fieldWithPath("_links.self").description("Main URL"))); + return (configurer) -> configurer.snippets() + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java index 94fabc200ab..8869b95e815 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,21 +52,18 @@ public class WebTestClientRestDocsAutoConfigurationIntegrationTests { @Before public void deleteSnippets() { - this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), - "generated-snippets"); + this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test public void defaultSnippetsAreWritten() throws Exception { - this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful() - .expectBody().consumeWith(document("default-snippets")); + this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() + .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); - assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))) - .contains("'https://api.example.com/'"); - assertThat(contentOf(new File(defaultSnippetsDir, "http-request.adoc"))) - .contains("api.example.com"); + assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); + assertThat(contentOf(new File(defaultSnippetsDir, "http-request.adoc"))).contains("api.example.com"); assertThat(new File(defaultSnippetsDir, "http-response.adoc")).isFile(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java index af01a1a73c6..510ab6c0571 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java @@ -53,16 +53,13 @@ public class MockMvcSecurityIntegrationTests { @Test public void unauthorizedResponseWithNoUser() throws Exception { - this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()); + this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); } @Test public void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception { - this.mockMvc - .perform(get("/").header(HttpHeaders.AUTHORIZATION, - "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))) - .andExpect(status().isOk()); + this.mockMvc.perform(get("/").header(HttpHeaders.AUTHORIZATION, + "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))).andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java index 5681f1fdcb0..e0f69b59c71 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java @@ -45,8 +45,7 @@ public class AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests { @Test public void mockServerRestTemplateCustomizerShouldNotBeRegistered() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext - .getBean(MockServerRestTemplateCustomizer.class)); + .isThrownBy(() -> this.applicationContext.getBean(MockServerRestTemplateCustomizer.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java index 453a6ad7dc3..8d67dfea88c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java @@ -54,10 +54,8 @@ public class AutoConfigureWebClientWithRestTemplateIntegrationTests { @Test public void restTemplateTest() { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.getForEntity("/test", - String.class); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + ResponseEntity entity = this.restTemplate.getForEntity("/test", String.class); assertThat(entity.getBody()).isEqualTo("hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java index 37d15d51274..c2d679815cf 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java @@ -46,15 +46,13 @@ public class RestClientRestIntegrationTests { @Test public void mockServerCall1() { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("1", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("1", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("1"); } @Test public void mockServerCall2() { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("2", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("2", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("2"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java index 243df64f752..996131429d7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java @@ -52,15 +52,14 @@ public class RestClientTestNoComponentIntegrationTests { @Test public void exampleRestClientIsNotInjected() { - assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( - () -> this.applicationContext.getBean(ExampleRestClient.class)); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleRestClient.class)); } @Test public void manuallyCreateBean() { ExampleRestClient client = new ExampleRestClient(this.restTemplateBuilder); - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(client.test()).isEqualTo("hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java index b9374c53bd0..ec593fdc14a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java @@ -53,24 +53,21 @@ public class RestClientTestTwoComponentsIntegrationTests { @Test public void serverShouldNotWork() { - assertThatIllegalStateException() - .isThrownBy(() -> this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML))) + assertThatIllegalStateException().isThrownBy( + () -> this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML))) .withMessageContaining("Unable to use auto-configured"); } @Test public void client1RestCallViaCustomizer() { - this.customizer.getServer(this.client1.getRestTemplate()) - .expect(requestTo("/test")) + this.customizer.getServer(this.client1.getRestTemplate()).expect(requestTo("/test")) .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client1.test()).isEqualTo("hello"); } @Test public void client2RestCallViaCustomizer() { - this.customizer.getServer(this.client2.getRestTemplate()) - .expect(requestTo("/test")) + this.customizer.getServer(this.client2.getRestTemplate()).expect(requestTo("/test")) .andRespond(withSuccess("there", MediaType.TEXT_HTML)); assertThat(this.client2.test()).isEqualTo("there"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java index 758db3fba57..e54d2a06646 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java @@ -45,8 +45,7 @@ public class RestClientTestWithComponentIntegrationTests { @Test public void mockServerCall() { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java index f3ebae42d8c..b2e89629da1 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java @@ -38,10 +38,9 @@ public class RestClientTestWithoutJacksonIntegrationTests { @Test public void restClientTestCanBeUsedWhenJacksonIsNotOnTheClassPath() { - assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", - getClass().getClassLoader())).isFalse(); - Result result = JUnitCore - .runClasses(RestClientTestWithComponentIntegrationTests.class); + assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", getClass().getClassLoader())) + .isFalse(); + Result result = JUnitCore.runClasses(RestClientTestWithComponentIntegrationTests.class); assertThat(result.getFailureCount()).isEqualTo(0); assertThat(result.getRunCount()).isGreaterThan(0); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java index 11d58e4256e..19f8b5fb7e4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java @@ -45,8 +45,7 @@ public class WebFluxTypeExcludeFilterTests { @Test public void matchWhenHasNoControllers() throws Exception { - WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter( - WithNoControllers.class); + WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithNoControllers.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -57,8 +56,7 @@ public class WebFluxTypeExcludeFilterTests { @Test public void matchWhenHasController() throws Exception { - WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter( - WithController.class); + WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithController.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isTrue(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -69,8 +67,7 @@ public class WebFluxTypeExcludeFilterTests { @Test public void matchNotUsingDefaultFilters() throws Exception { - WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter( - NotUsingDefaultFilters.class); + WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(NotUsingDefaultFilters.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isTrue(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isTrue(); @@ -81,8 +78,7 @@ public class WebFluxTypeExcludeFilterTests { @Test public void matchWithIncludeFilter() throws Exception { - WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter( - WithIncludeFilter.class); + WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithIncludeFilter.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -93,8 +89,7 @@ public class WebFluxTypeExcludeFilterTests { @Test public void matchWithExcludeFilter() throws Exception { - WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter( - WithExcludeFilter.class); + WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithExcludeFilter.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -103,10 +98,8 @@ public class WebFluxTypeExcludeFilterTests { assertThat(excludes(filter, ExampleRepository.class)).isTrue(); } - private boolean excludes(WebFluxTypeExcludeFilter filter, Class type) - throws IOException { - MetadataReader metadataReader = this.metadataReaderFactory - .getMetadataReader(type.getName()); + private boolean excludes(WebFluxTypeExcludeFilter filter, Class type) throws IOException { + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(type.getName()); return filter.match(metadataReader, this.metadataReaderFactory); } @@ -130,8 +123,7 @@ public class WebFluxTypeExcludeFilterTests { } - @WebFluxTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = Controller1.class)) + @WebFluxTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Controller1.class)) static class WithExcludeFilter { } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java index 65c39115ab9..6d31af0265e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java @@ -51,8 +51,7 @@ import static org.mockito.Mockito.verify; public class WebTestClientAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebTestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); @Test public void shouldNotBeConfiguredWithoutWebHandler() { @@ -64,23 +63,19 @@ public class WebTestClientAutoConfigurationTests { @Test public void shouldCustomizeClientCodecs() { - this.contextRunner.withUserConfiguration(CodecConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(WebTestClient.class); - assertThat(context).hasSingleBean(CodecCustomizer.class); - verify(context.getBean(CodecCustomizer.class)) - .customize(any(CodecConfigurer.class)); - }); + this.contextRunner.withUserConfiguration(CodecConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(WebTestClient.class); + assertThat(context).hasSingleBean(CodecCustomizer.class); + verify(context.getBean(CodecCustomizer.class)).customize(any(CodecConfigurer.class)); + }); } @Test public void shouldCustomizeTimeout() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("spring.test.webtestclient.timeout=15m") - .run((context) -> { + .withPropertyValues("spring.test.webtestclient.timeout=15m").run((context) -> { WebTestClient webTestClient = context.getBean(WebTestClient.class); - Object duration = ReflectionTestUtils.getField(webTestClient, - "timeout"); + Object duration = ReflectionTestUtils.getField(webTestClient, "timeout"); assertThat(duration).isEqualTo(Duration.of(15, ChronoUnit.MINUTES)); }); } @@ -88,34 +83,31 @@ public class WebTestClientAutoConfigurationTests { @Test @SuppressWarnings("unchecked") public void shouldApplySpringSecurityConfigurer() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> { - WebTestClient webTestClient = context.getBean(WebTestClient.class); - WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils - .getField(webTestClient, "builder"); - WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils - .getField(builder, "httpHandlerBuilder"); - List filters = (List) ReflectionTestUtils - .getField(httpHandlerBuilder, "filters"); - assertThat(filters.get(0).getClass().getName()).isEqualTo( - "org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers$MutatorFilter"); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { + WebTestClient webTestClient = context.getBean(WebTestClient.class); + WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, + "builder"); + WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils.getField(builder, + "httpHandlerBuilder"); + List filters = (List) ReflectionTestUtils.getField(httpHandlerBuilder, "filters"); + assertThat(filters.get(0).getClass().getName()).isEqualTo( + "org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers$MutatorFilter"); + }); } @Test @SuppressWarnings("unchecked") public void shouldNotApplySpringSecurityConfigurerWhenSpringSecurityNotOnClassPath() { - FilteredClassLoader classLoader = new FilteredClassLoader( - SecurityMockServerConfigurers.class); - this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withClassLoader(classLoader).run((context) -> { + FilteredClassLoader classLoader = new FilteredClassLoader(SecurityMockServerConfigurers.class); + this.contextRunner.withUserConfiguration(BaseConfiguration.class).withClassLoader(classLoader) + .run((context) -> { WebTestClient webTestClient = context.getBean(WebTestClient.class); - WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils - .getField(webTestClient, "builder"); + WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, + "builder"); WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils .getField(builder, "httpHandlerBuilder"); - List filters = (List) ReflectionTestUtils - .getField(httpHandlerBuilder, "filters"); + List filters = (List) ReflectionTestUtils.getField(httpHandlerBuilder, + "filters"); assertThat(filters).isEmpty(); }); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/ExampleIdConverter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/ExampleIdConverter.java index 1e296d3dc51..ed660a8613d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/ExampleIdConverter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/ExampleIdConverter.java @@ -39,8 +39,7 @@ public class ExampleIdConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java index b058adff486..d6f8004b9ac 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java @@ -40,14 +40,12 @@ public class WebFluxTestAllControllersIntegrationTests { @Test public void shouldFindController1() { - this.webClient.get().uri("/one").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("one"); + this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("one"); } @Test public void shouldFindController2() { - this.webClient.get().uri("/two").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("two"); + this.webClient.get().uri("/two").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("two"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java index 9bb08a088db..4c3ae375a2a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java @@ -49,38 +49,32 @@ public class WebFluxTestAutoConfigurationIntegrationTests { @Test public void messageSourceAutoConfigurationIsImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(MessageSourceAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(MessageSourceAutoConfiguration.class)); } @Test public void validationAutoConfigurationIsImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(ValidationAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(ValidationAutoConfiguration.class)); } @Test public void mustacheAutoConfigurationIsImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(MustacheAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(MustacheAutoConfiguration.class)); } @Test public void freeMarkerAutoConfigurationIsImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); } @Test public void thymeleafAutoConfigurationIsImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); } @Test public void errorWebFluxAutoConfigurationIsImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(ErrorWebFluxAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(ErrorWebFluxAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java index 575373273ce..dd9d0c59396 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java @@ -43,8 +43,8 @@ public class WebFluxTestConverterIntegrationTests { @Test public void shouldFindConverter() { UUID id = UUID.randomUUID(); - this.webClient.get().uri("/two/" + id).exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo(id + "two"); + this.webClient.get().uri("/two/" + id).exchange().expectStatus().isOk().expectBody(String.class) + .isEqualTo(id + "two"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java index f61668e1c88..e2e737f6046 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java @@ -40,8 +40,7 @@ public class WebFluxTestOneControllerIntegrationTests { @Test public void shouldFindController() { - this.webClient.get().uri("/one").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("one"); + this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("one"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java index 3c8cad6486a..90107caf4e3 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java @@ -41,8 +41,7 @@ public class WebFluxTestWebTestClientCodecCustomizationIntegrationTests { @Test public void shouldBeAbleToCreatePojoViaParametersModule() { - this.webClient.get().uri("/json").exchange().expectStatus().isOk() - .expectBody(ExamplePojo.class); + this.webClient.get().uri("/json").exchange().expectStatus().isOk().expectBody(ExamplePojo.class); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java index ca332b8a0e3..1a3cc17b1c1 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java @@ -40,9 +40,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = "spring.main.web-application-type=reactive", - classes = { WebTestClientSpringBootTestIntegrationTests.TestConfiguration.class, - ExampleWebFluxApplication.class }) +@SpringBootTest(properties = "spring.main.web-application-type=reactive", classes = { + WebTestClientSpringBootTestIntegrationTests.TestConfiguration.class, ExampleWebFluxApplication.class }) @AutoConfigureWebTestClient public class WebTestClientSpringBootTestIntegrationTests { @@ -54,20 +53,17 @@ public class WebTestClientSpringBootTestIntegrationTests { @Test public void shouldFindController1() { - this.webClient.get().uri("/one").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("one"); + this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("one"); } @Test public void shouldFindController2() { - this.webClient.get().uri("/two").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("two"); + this.webClient.get().uri("/two").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("two"); } @Test public void shouldHaveRealService() { - assertThat(this.applicationContext.getBeansOfType(ExampleRealService.class)) - .hasSize(1); + assertThat(this.applicationContext.getBeansOfType(ExampleRealService.class)).hasSize(1); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java index c1ca8b84385..ead392c780a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public class MockMvcAutoConfigurationTests { this.contextRunner.run((context) -> { MockMvc mockMvc = context.getBean(MockMvc.class); assertThat(context).hasSingleBean(DispatcherServlet.class); - assertThat(context.getBean(DispatcherServlet.class)) - .isEqualTo(mockMvc.getDispatcherServlet()); + assertThat(context.getBean(DispatcherServlet.class)).isEqualTo(mockMvc.getDispatcherServlet()); }); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java index 47f60bf8c5b..c811f261d03 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java @@ -61,8 +61,7 @@ public class SpringBootMockMvcBuilderCustomizerTests { .getBean("filterRegistrationBean"); Filter testFilter = (Filter) context.getBean("testFilter"); Filter otherTestFilter = registrationBean.getFilter(); - List filters = (List) ReflectionTestUtils.getField(builder, - "filters"); + List filters = (List) ReflectionTestUtils.getField(builder, "filters"); assertThat(filters).containsExactlyInAnyOrder(testFilter, otherTestFilter); } @@ -103,8 +102,7 @@ public class SpringBootMockMvcBuilderCustomizerTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } @@ -123,8 +121,7 @@ public class SpringBootMockMvcBuilderCustomizerTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java index d6ce9558c32..bae24b6a6ae 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java @@ -49,42 +49,34 @@ public class WebMvcTestAutoConfigurationIntegrationTests { @Test public void freemarkerAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); } @Test public void groovyTemplatesAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class)); } @Test public void mustacheAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(MustacheAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(MustacheAutoConfiguration.class)); } @Test public void thymeleafAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); } @Test public void taskExecutionAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(TaskExecutionAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(TaskExecutionAutoConfiguration.class)); } @Test public void asyncTaskExecutorWithApplicationTaskExecutor() { - assertThat(this.applicationContext.getBeansOfType(AsyncTaskExecutor.class)) - .hasSize(1); - assertThat(ReflectionTestUtils.getField( - this.applicationContext.getBean(RequestMappingHandlerAdapter.class), - "taskExecutor")).isSameAs( - this.applicationContext.getBean("applicationTaskExecutor")); + assertThat(this.applicationContext.getBeansOfType(AsyncTaskExecutor.class)).hasSize(1); + assertThat(ReflectionTestUtils.getField(this.applicationContext.getBean(RequestMappingHandlerAdapter.class), + "taskExecutor")).isSameAs(this.applicationContext.getBean("applicationTaskExecutor")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java index 1eb33697d07..08f585eb297 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java @@ -46,8 +46,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWhenHasNoControllers() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithNoControllers.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithNoControllers.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -60,8 +59,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWhenHasController() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithController.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithController.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isTrue(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -74,8 +72,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchNotUsingDefaultFilters() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - NotUsingDefaultFilters.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(NotUsingDefaultFilters.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isTrue(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isTrue(); @@ -88,8 +85,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWithIncludeFilter() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithIncludeFilter.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithIncludeFilter.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -101,8 +97,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWithExcludeFilter() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithExcludeFilter.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithExcludeFilter.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -113,10 +108,8 @@ public class WebMvcTypeExcludeFilterTests { assertThat(excludes(filter, ExampleWebSecurityConfigurer.class)).isFalse(); } - private boolean excludes(WebMvcTypeExcludeFilter filter, Class type) - throws IOException { - MetadataReader metadataReader = this.metadataReaderFactory - .getMetadataReader(type.getName()); + private boolean excludes(WebMvcTypeExcludeFilter filter, Class type) throws IOException { + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(type.getName()); return filter.match(metadataReader, this.metadataReaderFactory); } @@ -140,8 +133,7 @@ public class WebMvcTypeExcludeFilterTests { } - @WebMvcTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = Controller1.class)) + @WebMvcTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Controller1.class)) static class WithExcludeFilter { } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleControllerAdvice.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleControllerAdvice.java index 03332e38e62..297787e7290 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleControllerAdvice.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleControllerAdvice.java @@ -41,10 +41,8 @@ public class ExampleControllerAdvice { @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public ResponseEntity noHandlerFoundHandler( - NoHandlerFoundException exception) { - return ResponseEntity.badRequest() - .body("Invalid request: " + exception.getRequestURL()); + public ResponseEntity noHandlerFoundHandler(NoHandlerFoundException exception) { + return ResponseEntity.badRequest().body("Invalid request: " + exception.getRequestURL()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleFilter.java index 6eed55d04a5..a4732f8e627 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleFilter.java @@ -42,8 +42,8 @@ public class ExampleFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { chain.doFilter(request, response); ((HttpServletResponse) response).addHeader("x-test", "abc"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleWebMvcConfigurer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleWebMvcConfigurer.java index 6debc59bc2f..e9bade2ec91 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleWebMvcConfigurer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/ExampleWebMvcConfigurer.java @@ -36,8 +36,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; public class ExampleWebMvcConfigurer implements WebMvcConfigurer { @Override - public void addArgumentResolvers( - List argumentResolvers) { + public void addArgumentResolvers(List argumentResolvers) { argumentResolvers.add(new HandlerMethodArgumentResolver() { @Override @@ -46,9 +45,8 @@ public class ExampleWebMvcConfigurer implements WebMvcConfigurer { } @Override - public Object resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { return new ExampleArgument("hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/HateoasController.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/HateoasController.java index 7f813dd2b8a..435670d5724 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/HateoasController.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/HateoasController.java @@ -36,8 +36,7 @@ class HateoasController { @RequestMapping("/resource") public EntityModel> resource() { - return new EntityModel<>(new HashMap<>(), - new Link("self", "https://api.example.com")); + return new EntityModel<>(new HashMap<>(), new Link("self", "https://api.example.com")); } @RequestMapping("/plain") diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java index d6525588e1e..de3f9f39f73 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java @@ -62,21 +62,18 @@ public class MockMvcSpringBootTestIntegrationTests { @Test public void shouldFindController1() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).contains("Request URI = /one"); } @Test public void shouldFindController2() throws Exception { - this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } @Test public void shouldFindControllerAdvice() throws Exception { - this.mvc.perform(get("/error")).andExpect(content().string("recovered")) - .andExpect(status().isOk()); + this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk()); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java index 51bfa3b4e0d..6052e8e1f86 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java @@ -54,26 +54,22 @@ public class WebMvcTestAllControllersIntegrationTests { @Test public void shouldFindController1() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); } @Test public void shouldFindController2() throws Exception { - this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } @Test public void shouldFindControllerAdvice() throws Exception { - this.mvc.perform(get("/error")).andExpect(content().string("recovered")) - .andExpect(status().isOk()); + this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk()); } @Test public void shouldRunValidationSuccess() throws Exception { - this.mvc.perform(get("/three/OK")).andExpect(status().isOk()) - .andExpect(content().string("Hello OK")); + this.mvc.perform(get("/three/OK")).andExpect(status().isOk()).andExpect(content().string("Hello OK")); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java index e1e619cbf04..bc28a4bd465 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java @@ -47,8 +47,7 @@ public class WebMvcTestConverterIntegrationTests { @Test public void shouldFindConverter() throws Exception { String id = UUID.randomUUID().toString(); - this.mvc.perform(get("/two/" + id)).andExpect(content().string(id + "two")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two/" + id)).andExpect(content().string(id + "two")).andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java index f6de85b4b77..6c582637c0c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java @@ -50,8 +50,8 @@ public class WebMvcTestHateoasIntegrationTests { @Test public void hateoasResponse() throws Exception { - this.mockMvc.perform(get("/hateoas/resource")).andExpect(header() - .string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8")); + this.mockMvc.perform(get("/hateoas/resource")) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java index d738a232766..f3bb39edd05 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java @@ -49,8 +49,7 @@ public class WebMvcTestOneControllerIntegrationTests { @Test public void shouldFindController2() throws Exception { - this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java index f347d713864..c1d07293f3b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java @@ -44,8 +44,8 @@ public class WebMvcTestPageableIntegrationTests { @Test public void shouldSupportPageable() throws Exception { - this.mvc.perform(get("/paged").param("page", "2").param("size", "42")) - .andExpect(status().isOk()).andExpect(content().string("2:42")); + this.mvc.perform(get("/paged").param("page", "2").param("size", "42")).andExpect(status().isOk()) + .andExpect(content().string("2:42")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java index cc13f525a70..51f0914378a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java @@ -52,8 +52,7 @@ public class WebMvcTestPrintAlwaysIntegrationTests { @Test public void shouldPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).contains("Request URI = /one"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java index 224685d99f8..a49eb7b601c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java @@ -45,14 +45,12 @@ public class WebMvcTestPrintDefaultIntegrationTests { @Test public void shouldNotPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); } @Test public void shouldPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("none")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("none")).andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java index 326621ae362..44a7c3ca794 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java @@ -52,8 +52,7 @@ public class WebMvcTestPrintDefaultOverrideIntegrationTests { @Test public void shouldFindController1() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).doesNotContain("Request URI = /one"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java index a84bbe5ebfc..f42f0f339b5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java @@ -53,8 +53,7 @@ public class WebMvcTestPrintOverrideIntegrationTests { @Test public void shouldNotPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).doesNotContain("Request URI = /one"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java index 66bf25874d8..3a25352b28a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java @@ -51,10 +51,8 @@ public class WebMvcTestServletFilterRegistrationDisabledIntegrationTests { static class DisabledRegistrationConfiguration { @Bean - public FilterRegistrationBean exampleFilterRegistration( - ExampleFilter filter) { - FilterRegistrationBean registration = new FilterRegistrationBean<>( - filter); + public FilterRegistrationBean exampleFilterRegistration(ExampleFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); registration.setEnabled(false); return registration; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java index c1bf8c06ade..6d7727ee82d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java @@ -62,8 +62,7 @@ public class WebMvcTestWebDriverIntegrationTests { this.webDriver.get("/html"); WebElement element = this.webDriver.findElement(By.tagName("body")); assertThat(element.getText()).isEqualTo("Hello"); - assertThatExceptionOfType(NoSuchWindowException.class) - .isThrownBy(previousWebDriver::getWindowHandle); + assertThatExceptionOfType(NoSuchWindowException.class).isThrownBy(previousWebDriver::getWindowHandle); assertThat(previousWebDriver).isNotNull().isNotSameAs(this.webDriver); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index 3725db10c15..5588e1a9255 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java @@ -42,8 +42,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @WebMvcTest -@AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, - webDriverEnabled = false) +@AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, webDriverEnabled = false) public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { @Autowired diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/AnnotatedClassFinder.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/AnnotatedClassFinder.java index e4963fba79c..9fdf7803b20 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/AnnotatedClassFinder.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/AnnotatedClassFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import org.springframework.util.ClassUtils; */ public final class AnnotatedClassFinder { - private static final Map> cache = Collections - .synchronizedMap(new Cache(40)); + private static final Map> cache = Collections.synchronizedMap(new Cache(40)); private final Class annotationType; @@ -90,11 +89,9 @@ public final class AnnotatedClassFinder { while (!source.isEmpty()) { Set components = this.scanner.findCandidateComponents(source); if (!components.isEmpty()) { - Assert.state(components.size() == 1, - () -> "Found multiple @" + this.annotationType.getSimpleName() - + " annotated classes " + components); - return ClassUtils.resolveClassName( - components.iterator().next().getBeanClassName(), null); + Assert.state(components.size() == 1, () -> "Found multiple @" + this.annotationType.getSimpleName() + + " annotated classes " + components); + return ClassUtils.resolveClassName(components.iterator().next().getBeanClassName(), null); } source = getParentPackage(source); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java index 8bb686469b9..b9470709336 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class ConfigFileApplicationContextInitializer public void initialize(ConfigurableApplicationContext applicationContext) { new ConfigFileApplicationListener() { public void apply() { - addPropertySources(applicationContext.getEnvironment(), - applicationContext); + addPropertySources(applicationContext.getEnvironment(), applicationContext); addPostProcessors(applicationContext); } }.apply(); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/FilteredClassLoader.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/FilteredClassLoader.java index 6ace2beaeaa..e8d577cf706 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/FilteredClassLoader.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/FilteredClassLoader.java @@ -48,8 +48,7 @@ public class FilteredClassLoader extends URLClassLoader { * @param hiddenClasses the classes to hide */ public FilteredClassLoader(Class... hiddenClasses) { - this(Collections.singleton(ClassFilter.of(hiddenClasses)), - Collections.emptyList()); + this(Collections.singleton(ClassFilter.of(hiddenClasses)), Collections.emptyList()); } /** @@ -57,8 +56,7 @@ public class FilteredClassLoader extends URLClassLoader { * @param hiddenPackages the packages to hide */ public FilteredClassLoader(String... hiddenPackages) { - this(Collections.singleton(PackageFilter.of(hiddenPackages)), - Collections.emptyList()); + this(Collections.singleton(PackageFilter.of(hiddenPackages)), Collections.emptyList()); } /** @@ -68,8 +66,7 @@ public class FilteredClassLoader extends URLClassLoader { * @since 2.1.0 */ public FilteredClassLoader(ClassPathResource... hiddenResources) { - this(Collections.emptyList(), - Collections.singleton(ClassPathResourceFilter.of(hiddenResources))); + this(Collections.emptyList(), Collections.singleton(ClassPathResourceFilter.of(hiddenResources))); } /** @@ -92,8 +89,7 @@ public class FilteredClassLoader extends URLClassLoader { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { for (Predicate filter : this.classesFilters) { if (filter.test(name)) { throw new ClassNotFoundException(); @@ -202,8 +198,7 @@ public class FilteredClassLoader extends URLClassLoader { @Override public boolean test(String resourceName) { for (ClassPathResource hiddenResource : this.hiddenResources) { - if (hiddenResource.getFilename() != null - && resourceName.equals(hiddenResource.getPath())) { + if (hiddenResource.getFilename() != null && resourceName.equals(hiddenResource.getPath())) { return true; } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java index 03d2ad73755..3d33b764ce5 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java @@ -75,24 +75,20 @@ class ImportsContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context); - AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader( - registry); + AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry); registerCleanupPostProcessor(registry, reader); registerImportsConfiguration(registry, reader); } - private void registerCleanupPostProcessor(BeanDefinitionRegistry registry, - AnnotatedBeanDefinitionReader reader) { - BeanDefinition definition = registerBean(registry, reader, - ImportsCleanupPostProcessor.BEAN_NAME, ImportsCleanupPostProcessor.class); - definition.getConstructorArgumentValues().addIndexedArgumentValue(0, - this.testClass); + private void registerCleanupPostProcessor(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) { + BeanDefinition definition = registerBean(registry, reader, ImportsCleanupPostProcessor.BEAN_NAME, + ImportsCleanupPostProcessor.class); + definition.getConstructorArgumentValues().addIndexedArgumentValue(0, this.testClass); } - private void registerImportsConfiguration(BeanDefinitionRegistry registry, - AnnotatedBeanDefinitionReader reader) { - BeanDefinition definition = registerBean(registry, reader, - ImportsConfiguration.BEAN_NAME, ImportsConfiguration.class); + private void registerImportsConfiguration(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) { + BeanDefinition definition = registerBean(registry, reader, ImportsConfiguration.BEAN_NAME, + ImportsConfiguration.class); definition.setAttribute(TEST_CLASS_ATTRIBUTE, this.testClass); } @@ -101,14 +97,13 @@ class ImportsContextCustomizer implements ContextCustomizer { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { - return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) - .getBeanFactory(); + return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } - private BeanDefinition registerBean(BeanDefinitionRegistry registry, - AnnotatedBeanDefinitionReader reader, String beanName, Class type) { + private BeanDefinition registerBean(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader, + String beanName, Class type) { reader.registerBean(type, beanName); return registry.getBeanDefinition(beanName); } @@ -165,12 +160,9 @@ class ImportsContextCustomizer implements ContextCustomizer { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { - BeanDefinition definition = this.beanFactory - .getBeanDefinition(ImportsConfiguration.BEAN_NAME); - Object testClass = (definition != null) - ? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null; - return (testClass != null) ? new String[] { ((Class) testClass).getName() } - : NO_IMPORTS; + BeanDefinition definition = this.beanFactory.getBeanDefinition(ImportsConfiguration.BEAN_NAME); + Object testClass = (definition != null) ? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null; + return (testClass != null) ? new String[] { ((Class) testClass).getName() } : NO_IMPORTS; } } @@ -180,8 +172,7 @@ class ImportsContextCustomizer implements ContextCustomizer { * added to load imports. */ @Order(Ordered.LOWEST_PRECEDENCE) - static class ImportsCleanupPostProcessor - implements BeanDefinitionRegistryPostProcessor { + static class ImportsCleanupPostProcessor implements BeanDefinitionRegistryPostProcessor { static final String BEAN_NAME = ImportsCleanupPostProcessor.class.getName(); @@ -192,13 +183,11 @@ class ImportsContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { try { String[] names = registry.getBeanDefinitionNames(); for (String name : names) { @@ -243,12 +232,10 @@ class ImportsContextCustomizer implements ContextCustomizer { Set> seen = new HashSet<>(); collectClassAnnotations(testClass, annotations, seen); Set determinedImports = determineImports(annotations, testClass); - this.key = Collections.unmodifiableSet( - (determinedImports != null) ? determinedImports : annotations); + this.key = Collections.unmodifiableSet((determinedImports != null) ? determinedImports : annotations); } - private void collectClassAnnotations(Class classType, - Set annotations, Set> seen) { + private void collectClassAnnotations(Class classType, Set annotations, Set> seen) { if (seen.add(classType)) { collectElementAnnotations(classType, annotations, seen); for (Class interfaceType : classType.getInterfaces()) { @@ -260,13 +247,12 @@ class ImportsContextCustomizer implements ContextCustomizer { } } - private void collectElementAnnotations(AnnotatedElement element, - Set annotations, Set> seen) { + private void collectElementAnnotations(AnnotatedElement element, Set annotations, + Set> seen) { for (Annotation annotation : element.getDeclaredAnnotations()) { if (!isIgnoredAnnotation(annotation)) { annotations.add(annotation); - collectClassAnnotations(annotation.annotationType(), annotations, - seen); + collectClassAnnotations(annotation.annotationType(), annotations, seen); } } } @@ -280,15 +266,12 @@ class ImportsContextCustomizer implements ContextCustomizer { return false; } - private Set determineImports(Set annotations, - Class testClass) { + private Set determineImports(Set annotations, Class testClass) { Set determinedImports = new LinkedHashSet<>(); - AnnotationMetadata testClassMetadata = AnnotationMetadata - .introspect(testClass); + AnnotationMetadata testClassMetadata = AnnotationMetadata.introspect(testClass); for (Annotation annotation : annotations) { for (Class source : getImports(annotation)) { - Set determinedSourceImports = determineImports(source, - testClassMetadata); + Set determinedSourceImports = determineImports(source, testClassMetadata); if (determinedSourceImports == null) { return null; } @@ -305,12 +288,10 @@ class ImportsContextCustomizer implements ContextCustomizer { return NO_IMPORTS; } - private Set determineImports(Class source, - AnnotationMetadata metadata) { + private Set determineImports(Class source, AnnotationMetadata metadata) { if (DeterminableImports.class.isAssignableFrom(source)) { // We can determine the imports - return ((DeterminableImports) instantiate(source)) - .determineImports(metadata); + return ((DeterminableImports) instantiate(source)).determineImports(metadata); } if (ImportSelector.class.isAssignableFrom(source) || ImportBeanDefinitionRegistrar.class.isAssignableFrom(source)) { @@ -330,17 +311,14 @@ class ImportsContextCustomizer implements ContextCustomizer { return (T) constructor.newInstance(); } catch (Throwable ex) { - throw new IllegalStateException( - "Unable to instantiate DeterminableImportSelector " - + source.getName(), + throw new IllegalStateException("Unable to instantiate DeterminableImportSelector " + source.getName(), ex); } } @Override public boolean equals(Object obj) { - return (obj != null && getClass() == obj.getClass() - && this.key.equals(((ContextCustomizerKey) obj).key)); + return (obj != null && getClass() == obj.getClass() && this.key.equals(((ContextCustomizerKey) obj).key)); } @Override diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java index c4c5e45fb8c..1259cebd4fd 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java @@ -41,8 +41,7 @@ class ImportsContextCustomizerFactory implements ContextCustomizerFactory { @Override public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { - if (MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE) - .isPresent(Import.class)) { + if (MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE).isPresent(Import.class)) { assertHasNoBeanMethods(testClass); return new ImportsContextCustomizer(testClass); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ReactiveWebMergedContextConfiguration.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ReactiveWebMergedContextConfiguration.java index 5e1cc0b5ef3..d598c51e2e0 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ReactiveWebMergedContextConfiguration.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ReactiveWebMergedContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import org.springframework.test.context.MergedContextConfiguration; */ public class ReactiveWebMergedContextConfiguration extends MergedContextConfiguration { - public ReactiveWebMergedContextConfiguration( - MergedContextConfiguration mergedConfig) { + public ReactiveWebMergedContextConfiguration(MergedContextConfiguration mergedConfig) { super(mergedConfig); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java index 5660e73ebde..778097443f4 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java @@ -83,18 +83,13 @@ public class SpringBootContextLoader extends AbstractContextLoader { private static final String[] NO_ARGS = new String[0]; @Override - public ApplicationContext loadContext(MergedContextConfiguration config) - throws Exception { + public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception { Class[] configClasses = config.getClasses(); String[] configLocations = config.getLocations(); - Assert.state( - !ObjectUtils.isEmpty(configClasses) - || !ObjectUtils.isEmpty(configLocations), - () -> "No configuration classes " - + "or locations found in @SpringApplicationConfiguration. " - + "For default configuration detection to work you need " - + "Spring 4.0.3 or better (found " + SpringVersion.getVersion() - + ")."); + Assert.state(!ObjectUtils.isEmpty(configClasses) || !ObjectUtils.isEmpty(configLocations), + () -> "No configuration classes " + "or locations found in @SpringApplicationConfiguration. " + + "For default configuration detection to work you need " + "Spring 4.0.3 or better (found " + + SpringVersion.getVersion() + ")."); SpringApplication application = getSpringApplication(); application.setMainApplicationClass(config.getTestClass()); application.addPrimarySources(Arrays.asList(configClasses)); @@ -103,16 +98,13 @@ public class SpringBootContextLoader extends AbstractContextLoader { if (!ObjectUtils.isEmpty(config.getActiveProfiles())) { setActiveProfiles(environment, config.getActiveProfiles()); } - ResourceLoader resourceLoader = (application.getResourceLoader() != null) - ? application.getResourceLoader() + ResourceLoader resourceLoader = (application.getResourceLoader() != null) ? application.getResourceLoader() : new DefaultResourceLoader(getClass().getClassLoader()); - TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, - resourceLoader, config.getPropertySourceLocations()); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - getInlinedProperties(config)); + TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, resourceLoader, + config.getPropertySourceLocations()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, getInlinedProperties(config)); application.setEnvironment(environment); - List> initializers = getInitializers(config, - application); + List> initializers = getInitializers(config, application); if (config instanceof WebMergedContextConfiguration) { application.setWebApplicationType(WebApplicationType.SERVLET); if (!isEmbeddedWebEnvironment(config)) { @@ -158,16 +150,12 @@ public class SpringBootContextLoader extends AbstractContextLoader { * @see SpringApplication#run(String...) */ protected String[] getArgs(MergedContextConfiguration config) { - return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE) - .get(SpringBootTest.class).getValue("args", String[].class) - .orElse(NO_ARGS); + return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE).get(SpringBootTest.class) + .getValue("args", String[].class).orElse(NO_ARGS); } - private void setActiveProfiles(ConfigurableEnvironment environment, - String[] profiles) { - TestPropertyValues - .of("spring.profiles.active=" - + StringUtils.arrayToCommaDelimitedString(profiles)) + private void setActiveProfiles(ConfigurableEnvironment environment, String[] profiles) { + TestPropertyValues.of("spring.profiles.active=" + StringUtils.arrayToCommaDelimitedString(profiles)) .applyTo(environment); } @@ -191,10 +179,9 @@ public class SpringBootContextLoader extends AbstractContextLoader { return binder.bind("server.port", Bindable.of(String.class)).isBound(); } - private ConfigurationPropertySource convertToConfigurationPropertySource( - List properties) { - return new MapConfigurationPropertySource(TestPropertySourceUtils - .convertInlinedPropertiesToMap(StringUtils.toStringArray(properties))); + private ConfigurationPropertySource convertToConfigurationPropertySource(List properties) { + return new MapConfigurationPropertySource( + TestPropertySourceUtils.convertInlinedPropertiesToMap(StringUtils.toStringArray(properties))); } /** @@ -209,8 +196,8 @@ public class SpringBootContextLoader extends AbstractContextLoader { * @return the initializers to apply * @since 2.0.0 */ - protected List> getInitializers( - MergedContextConfiguration config, SpringApplication application) { + protected List> getInitializers(MergedContextConfiguration config, + SpringApplication application) { List> initializers = new ArrayList<>(); for (ContextCustomizer contextCustomizer : config.getContextCustomizers()) { initializers.add(new ContextCustomizerAdapter(contextCustomizer, config)); @@ -221,26 +208,21 @@ public class SpringBootContextLoader extends AbstractContextLoader { initializers.add(BeanUtils.instantiateClass(initializerClass)); } if (config.getParent() != null) { - initializers.add(new ParentContextApplicationContextInitializer( - config.getParentApplicationContext())); + initializers.add(new ParentContextApplicationContextInitializer(config.getParentApplicationContext())); } return initializers; } private boolean isEmbeddedWebEnvironment(MergedContextConfiguration config) { - return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE) - .get(SpringBootTest.class) - .getValue("webEnvironment", WebEnvironment.class) - .orElse(WebEnvironment.NONE).isEmbedded(); + return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE).get(SpringBootTest.class) + .getValue("webEnvironment", WebEnvironment.class).orElse(WebEnvironment.NONE).isEmbedded(); } @Override - public void processContextConfiguration( - ContextConfigurationAttributes configAttributes) { + public void processContextConfiguration(ContextConfigurationAttributes configAttributes) { super.processContextConfiguration(configAttributes); if (!configAttributes.hasResources()) { - Class[] defaultConfigClasses = detectDefaultConfigurationClasses( - configAttributes.getDeclaringClass()); + Class[] defaultConfigClasses = detectDefaultConfigurationClasses(configAttributes.getDeclaringClass()); configAttributes.setClasses(defaultConfigClasses); } } @@ -255,14 +237,13 @@ public class SpringBootContextLoader extends AbstractContextLoader { * @see AnnotationConfigContextLoaderUtils */ protected Class[] detectDefaultConfigurationClasses(Class declaringClass) { - return AnnotationConfigContextLoaderUtils - .detectDefaultConfigurationClasses(declaringClass); + return AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(declaringClass); } @Override public ApplicationContext loadContext(String... locations) throws Exception { - throw new UnsupportedOperationException("SpringApplicationContextLoader " - + "does not support the loadContext(String...) method"); + throw new UnsupportedOperationException( + "SpringApplicationContextLoader " + "does not support the loadContext(String...) method"); } @Override @@ -282,21 +263,18 @@ public class SpringBootContextLoader extends AbstractContextLoader { private static final Class WEB_CONTEXT_CLASS = GenericWebApplicationContext.class; - void configure(MergedContextConfiguration configuration, - SpringApplication application, + void configure(MergedContextConfiguration configuration, SpringApplication application, List> initializers) { WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration; addMockServletContext(initializers, webConfiguration); application.setApplicationContextClass(WEB_CONTEXT_CLASS); } - private void addMockServletContext( - List> initializers, + private void addMockServletContext(List> initializers, WebMergedContextConfiguration webConfiguration) { SpringBootMockServletContext servletContext = new SpringBootMockServletContext( webConfiguration.getResourceBasePath()); - initializers.add(0, new ServletContextApplicationContextInitializer( - servletContext, true)); + initializers.add(0, new ServletContextApplicationContextInitializer(servletContext, true)); } } @@ -325,8 +303,7 @@ public class SpringBootContextLoader extends AbstractContextLoader { private final MergedContextConfiguration config; - ContextCustomizerAdapter(ContextCustomizer contextCustomizer, - MergedContextConfiguration config) { + ContextCustomizerAdapter(ContextCustomizer contextCustomizer, MergedContextConfiguration config) { this.contextCustomizer = contextCustomizer; this.config = config; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java index d8c5355a4c8..2758490dcc4 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java @@ -84,24 +84,21 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework." + "web.reactive.DispatcherHandler"; - private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework." - + "web.servlet.DispatcherServlet"; + private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework." + "web.servlet.DispatcherServlet"; private static final String JERSEY_WEB_ENVIRONMENT_CLASS = "org.glassfish.jersey.server.ResourceConfig"; private static final String ACTIVATE_SERVLET_LISTENER = "org.springframework.test." + "context.web.ServletTestExecutionListener.activateListener"; - private static final Log logger = LogFactory - .getLog(SpringBootTestContextBootstrapper.class); + private static final Log logger = LogFactory.getLog(SpringBootTestContextBootstrapper.class); @Override public TestContext buildTestContext() { TestContext context = super.buildTestContext(); verifyConfiguration(context.getTestClass()); WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass()); - if (webEnvironment == WebEnvironment.MOCK - && deduceWebApplicationType() == WebApplicationType.SERVLET) { + if (webEnvironment == WebEnvironment.MOCK && deduceWebApplicationType() == WebApplicationType.SERVLET) { context.setAttribute(ACTIVATE_SERVLET_LISTENER, true); } else if (webEnvironment != null && webEnvironment.isEmbedded()) { @@ -114,8 +111,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr protected Set> getDefaultTestExecutionListenerClasses() { Set> listeners = super.getDefaultTestExecutionListenerClasses(); List postProcessors = SpringFactoriesLoader - .loadFactories(DefaultTestExecutionListenersPostProcessor.class, - getClass().getClassLoader()); + .loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader()); for (DefaultTestExecutionListenersPostProcessor postProcessor : postProcessors) { listeners = postProcessor.postProcessDefaultTestExecutionListeners(listeners); } @@ -134,8 +130,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return super.resolveContextLoader(testClass, configAttributesList); } - private void addConfigAttributesClasses( - ContextConfigurationAttributes configAttributes, Class[] classes) { + private void addConfigAttributesClasses(ContextConfigurationAttributes configAttributes, Class[] classes) { List> combined = new ArrayList<>(); combined.addAll(Arrays.asList(classes)); if (configAttributes.getClasses() != null) { @@ -145,51 +140,38 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr } @Override - protected Class getDefaultContextLoaderClass( - Class testClass) { + protected Class getDefaultContextLoaderClass(Class testClass) { return SpringBootContextLoader.class; } @Override - protected MergedContextConfiguration processMergedContextConfiguration( - MergedContextConfiguration mergedConfig) { + protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) { Class[] classes = getOrFindConfigurationClasses(mergedConfig); - List propertySourceProperties = getAndProcessPropertySourceProperties( - mergedConfig); - mergedConfig = createModifiedConfig(mergedConfig, classes, - StringUtils.toStringArray(propertySourceProperties)); + List propertySourceProperties = getAndProcessPropertySourceProperties(mergedConfig); + mergedConfig = createModifiedConfig(mergedConfig, classes, StringUtils.toStringArray(propertySourceProperties)); WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass()); if (webEnvironment != null && isWebEnvironmentSupported(mergedConfig)) { WebApplicationType webApplicationType = getWebApplicationType(mergedConfig); if (webApplicationType == WebApplicationType.SERVLET - && (webEnvironment.isEmbedded() - || webEnvironment == WebEnvironment.MOCK)) { - String resourceBasePath = MergedAnnotations - .from(mergedConfig.getTestClass(), SearchStrategy.EXHAUSTIVE) - .get(WebAppConfiguration.class) - .getValue(MergedAnnotation.VALUE, String.class) + && (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) { + String resourceBasePath = MergedAnnotations.from(mergedConfig.getTestClass(), SearchStrategy.EXHAUSTIVE) + .get(WebAppConfiguration.class).getValue(MergedAnnotation.VALUE, String.class) .orElse("src/main/webapp"); - mergedConfig = new WebMergedContextConfiguration(mergedConfig, - resourceBasePath); + mergedConfig = new WebMergedContextConfiguration(mergedConfig, resourceBasePath); } else if (webApplicationType == WebApplicationType.REACTIVE - && (webEnvironment.isEmbedded() - || webEnvironment == WebEnvironment.MOCK)) { + && (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) { return new ReactiveWebMergedContextConfiguration(mergedConfig); } } return mergedConfig; } - private WebApplicationType getWebApplicationType( - MergedContextConfiguration configuration) { + private WebApplicationType getWebApplicationType(MergedContextConfiguration configuration) { ConfigurationPropertySource source = new MapConfigurationPropertySource( - TestPropertySourceUtils.convertInlinedPropertiesToMap( - configuration.getPropertySourceProperties())); + TestPropertySourceUtils.convertInlinedPropertiesToMap(configuration.getPropertySourceProperties())); Binder binder = new Binder(source); - return binder - .bind("spring.main.web-application-type", - Bindable.of(WebApplicationType.class)) + return binder.bind("spring.main.web-application-type", Bindable.of(WebApplicationType.class)) .orElseGet(this::deduceWebApplicationType); } @@ -209,22 +191,19 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private boolean isWebEnvironmentSupported(MergedContextConfiguration mergedConfig) { Class testClass = mergedConfig.getTestClass(); - ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass, - ContextHierarchy.class); + ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass, ContextHierarchy.class); if (hierarchy == null || hierarchy.value().length == 0) { return true; } ContextConfiguration[] configurations = hierarchy.value(); - return isFromConfiguration(mergedConfig, - configurations[configurations.length - 1]); + return isFromConfiguration(mergedConfig, configurations[configurations.length - 1]); } private boolean isFromConfiguration(MergedContextConfiguration candidateConfig, ContextConfiguration configuration) { - ContextConfigurationAttributes attributes = new ContextConfigurationAttributes( - candidateConfig.getTestClass(), configuration); - Set> configurationClasses = new HashSet<>( - Arrays.asList(attributes.getClasses())); + ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(candidateConfig.getTestClass(), + configuration); + Set> configurationClasses = new HashSet<>(Arrays.asList(attributes.getClasses())); for (Class candidate : candidateConfig.getClasses()) { if (configurationClasses.contains(candidate)) { return true; @@ -233,20 +212,16 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return false; } - protected Class[] getOrFindConfigurationClasses( - MergedContextConfiguration mergedConfig) { + protected Class[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig) { Class[] classes = mergedConfig.getClasses(); if (containsNonTestComponent(classes) || mergedConfig.hasLocations()) { return classes; } Class found = new AnnotatedClassFinder(SpringBootConfiguration.class) .findFromClass(mergedConfig.getTestClass()); - Assert.state(found != null, - "Unable to find a @SpringBootConfiguration, you need to use " - + "@ContextConfiguration or @SpringBootTest(classes=...) " - + "with your test"); - logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " - + mergedConfig.getTestClass()); + Assert.state(found != null, "Unable to find a @SpringBootConfiguration, you need to use " + + "@ContextConfiguration or @SpringBootTest(classes=...) " + "with your test"); + logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " + mergedConfig.getTestClass()); return merge(found, classes); } @@ -267,8 +242,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return result; } - private List getAndProcessPropertySourceProperties( - MergedContextConfiguration mergedConfig) { + private List getAndProcessPropertySourceProperties(MergedContextConfiguration mergedConfig) { List propertySourceProperties = new ArrayList<>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); @@ -296,8 +270,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr * @param mergedConfig the merged context configuration * @param propertySourceProperties the property source properties to process */ - protected void processPropertySourceProperties( - MergedContextConfiguration mergedConfig, + protected void processPropertySourceProperties(MergedContextConfiguration mergedConfig, List propertySourceProperties) { Class testClass = mergedConfig.getTestClass(); String[] properties = getProperties(testClass); @@ -332,26 +305,22 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr } protected SpringBootTest getAnnotation(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(SpringBootTest.class).synthesize(MergedAnnotation::isPresent) - .orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(SpringBootTest.class) + .synthesize(MergedAnnotation::isPresent).orElse(null); } protected void verifyConfiguration(Class testClass) { SpringBootTest springBootTest = getAnnotation(testClass); - if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) - && MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .isPresent(WebAppConfiguration.class)) { + if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) && MergedAnnotations + .from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).isPresent(WebAppConfiguration.class)) { throw new IllegalStateException("@WebAppConfiguration should only be used " + "with @SpringBootTest when @SpringBootTest is configured with a " - + "mock web environment. Please remove @WebAppConfiguration or " - + "reconfigure @SpringBootTest."); + + "mock web environment. Please remove @WebAppConfiguration or " + "reconfigure @SpringBootTest."); } } private boolean isListeningOnPort(WebEnvironment webEnvironment) { - return webEnvironment == WebEnvironment.DEFINED_PORT - || webEnvironment == WebEnvironment.RANDOM_PORT; + return webEnvironment == WebEnvironment.DEFINED_PORT || webEnvironment == WebEnvironment.RANDOM_PORT; } /** @@ -360,10 +329,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr * @param classes the replacement classes * @return a new {@link MergedContextConfiguration} */ - protected final MergedContextConfiguration createModifiedConfig( - MergedContextConfiguration mergedConfig, Class[] classes) { - return createModifiedConfig(mergedConfig, classes, - mergedConfig.getPropertySourceProperties()); + protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig, + Class[] classes) { + return createModifiedConfig(mergedConfig, classes, mergedConfig.getPropertySourceProperties()); } /** @@ -374,13 +342,10 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr * @param propertySourceProperties the replacement properties * @return a new {@link MergedContextConfiguration} */ - protected final MergedContextConfiguration createModifiedConfig( - MergedContextConfiguration mergedConfig, Class[] classes, - String[] propertySourceProperties) { - return new MergedContextConfiguration(mergedConfig.getTestClass(), - mergedConfig.getLocations(), classes, - mergedConfig.getContextInitializerClasses(), - mergedConfig.getActiveProfiles(), + protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig, + Class[] classes, String[] propertySourceProperties) { + return new MergedContextConfiguration(mergedConfig.getTestClass(), mergedConfig.getLocations(), classes, + mergedConfig.getContextInitializerClasses(), mergedConfig.getActiveProfiles(), mergedConfig.getPropertySourceLocations(), propertySourceProperties, mergedConfig.getContextCustomizers(), mergedConfig.getContextLoader(), getCacheAwareContextLoaderDelegate(), mergedConfig.getParent()); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java index 1a99d84cc9b..48c41c99646 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,13 +80,12 @@ public class ApplicationContextAssert */ public ApplicationContextAssert hasBean(String name) { if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to have bean named:%n <%s>", name)); + throwAssertionError(contextFailedToStartWhenExpecting("to have bean named:%n <%s>", name)); } if (findBean(name) == null) { throwAssertionError(new BasicErrorMessageFactory( - "%nExpecting:%n <%s>%nto have bean named:%n <%s>%nbut found no such bean", - getApplicationContext(), name)); + "%nExpecting:%n <%s>%nto have bean named:%n <%s>%nbut found no such bean", getApplicationContext(), + name)); } return this; } @@ -124,8 +123,7 @@ public class ApplicationContextAssert public ApplicationContextAssert hasSingleBean(Class type, Scope scope) { Assert.notNull(scope, "Scope must not be null"); if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to have a single bean of type:%n <%s>", type)); + throwAssertionError(contextFailedToStartWhenExpecting("to have a single bean of type:%n <%s>", type)); } String[] names = scope.getBeanNamesForType(getApplicationContext(), type); if (names.length == 0) { @@ -172,8 +170,7 @@ public class ApplicationContextAssert public ApplicationContextAssert doesNotHaveBean(Class type, Scope scope) { Assert.notNull(scope, "Scope must not be null"); if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "not to have any beans of type:%n <%s>", type)); + throwAssertionError(contextFailedToStartWhenExpecting("not to have any beans of type:%n <%s>", type)); } String[] names = scope.getBeanNamesForType(getApplicationContext(), type); if (names.length > 0) { @@ -197,8 +194,7 @@ public class ApplicationContextAssert */ public ApplicationContextAssert doesNotHaveBean(String name) { if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "not to have any beans of name:%n <%s>", name)); + throwAssertionError(contextFailedToStartWhenExpecting("not to have any beans of name:%n <%s>", name)); } try { Object bean = getApplicationContext().getBean(name); @@ -224,8 +220,7 @@ public class ApplicationContextAssert */ public AbstractObjectArrayAssert getBeanNames(Class type) { if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to get beans names with type:%n <%s>", type)); + throwAssertionError(contextFailedToStartWhenExpecting("to get beans names with type:%n <%s>", type)); } return Assertions.assertThat(getApplicationContext().getBeanNamesForType(type)) .as("Bean names of type <%s> from <%s>", type, getApplicationContext()); @@ -271,19 +266,17 @@ public class ApplicationContextAssert public AbstractObjectAssert getBean(Class type, Scope scope) { Assert.notNull(scope, "Scope must not be null"); if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to contain bean of type:%n <%s>", type)); + throwAssertionError(contextFailedToStartWhenExpecting("to contain bean of type:%n <%s>", type)); } String[] names = scope.getBeanNamesForType(getApplicationContext(), type); String name = (names.length > 0) ? getPrimary(names, scope) : null; if (names.length > 1 && name == null) { - throwAssertionError(new BasicErrorMessageFactory( - "%nExpecting:%n <%s>%nsingle bean of type:%n <%s>%nbut found:%n <%s>", - getApplicationContext(), type, names)); + throwAssertionError( + new BasicErrorMessageFactory("%nExpecting:%n <%s>%nsingle bean of type:%n <%s>%nbut found:%n <%s>", + getApplicationContext(), type, names)); } T bean = (name != null) ? getApplicationContext().getBean(name, type) : null; - return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type, - getApplicationContext()); + return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type, getApplicationContext()); } private String getPrimary(String[] names, Scope scope) { @@ -306,10 +299,8 @@ public class ApplicationContextAssert ApplicationContext context = getApplicationContext(); while (context != null) { if (context instanceof ConfigurableApplicationContext) { - ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) context) - .getBeanFactory(); - if (factory.containsBean(name) - && factory.getMergedBeanDefinition(name).isPrimary()) { + ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) context).getBeanFactory(); + if (factory.containsBean(name) && factory.getMergedBeanDefinition(name).isPrimary()) { return true; } } @@ -333,12 +324,10 @@ public class ApplicationContextAssert */ public AbstractObjectAssert getBean(String name) { if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to contain a bean of name:%n <%s>", name)); + throwAssertionError(contextFailedToStartWhenExpecting("to contain a bean of name:%n <%s>", name)); } Object bean = findBean(name); - return Assertions.assertThat(bean).as("Bean of name <%s> from <%s>", name, - getApplicationContext()); + return Assertions.assertThat(bean).as("Bean of name <%s> from <%s>", name, getApplicationContext()); } /** @@ -361,8 +350,8 @@ public class ApplicationContextAssert @SuppressWarnings("unchecked") public AbstractObjectAssert getBean(String name, Class type) { if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to contain a bean of name:%n <%s> (%s)", name, type)); + throwAssertionError( + contextFailedToStartWhenExpecting("to contain a bean of name:%n <%s> (%s)", name, type)); } Object bean = findBean(name); if (bean != null && type != null && !type.isInstance(bean)) { @@ -370,8 +359,7 @@ public class ApplicationContextAssert "%nExpecting:%n <%s>%nto contain a bean of name:%n <%s> (%s)%nbut found:%n <%s> of type <%s>", getApplicationContext(), name, type, bean, bean.getClass())); } - return Assertions.assertThat((T) bean).as( - "Bean of name <%s> and type <%s> from <%s>", name, type, + return Assertions.assertThat((T) bean).as("Bean of name <%s> and type <%s> from <%s>", name, type, getApplicationContext()); } @@ -420,8 +408,7 @@ public class ApplicationContextAssert public MapAssert getBeans(Class type, Scope scope) { Assert.notNull(scope, "Scope must not be null"); if (this.startupFailure != null) { - throwAssertionError(contextFailedToStartWhenExpecting( - "to get beans of type:%n <%s>", type)); + throwAssertionError(contextFailedToStartWhenExpecting("to get beans of type:%n <%s>", type)); } return Assertions.assertThat(scope.getBeansOfType(getApplicationContext(), type)) .as("Beans of type <%s> from <%s>", type, getApplicationContext()); @@ -453,8 +440,7 @@ public class ApplicationContextAssert public ApplicationContextAssert hasFailed() { if (this.startupFailure == null) { throwAssertionError(new BasicErrorMessageFactory( - "%nExpecting:%n <%s>%nto have failed%nbut context started successfully", - getApplicationContext())); + "%nExpecting:%n <%s>%nto have failed%nbut context started successfully", getApplicationContext())); } return this; } @@ -482,10 +468,8 @@ public class ApplicationContextAssert return this.startupFailure; } - private ContextFailedToStart contextFailedToStartWhenExpecting( - String expectationFormat, Object... arguments) { - return new ContextFailedToStart<>(getApplicationContext(), this.startupFailure, - expectationFormat, arguments); + private ContextFailedToStart contextFailedToStartWhenExpecting(String expectationFormat, Object... arguments) { + return new ContextFailedToStart<>(getApplicationContext(), this.startupFailure, expectationFormat, arguments); } /** @@ -499,14 +483,12 @@ public class ApplicationContextAssert NO_ANCESTORS { @Override - String[] getBeanNamesForType(ApplicationContext applicationContext, - Class type) { + String[] getBeanNamesForType(ApplicationContext applicationContext, Class type) { return applicationContext.getBeanNamesForType(type); } @Override - Map getBeansOfType(ApplicationContext applicationContext, - Class type) { + Map getBeansOfType(ApplicationContext applicationContext, Class type) { return applicationContext.getBeansOfType(type); } @@ -518,46 +500,35 @@ public class ApplicationContextAssert INCLUDE_ANCESTORS { @Override - String[] getBeanNamesForType(ApplicationContext applicationContext, - Class type) { - return BeanFactoryUtils - .beanNamesForTypeIncludingAncestors(applicationContext, type); + String[] getBeanNamesForType(ApplicationContext applicationContext, Class type) { + return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, type); } @Override - Map getBeansOfType(ApplicationContext applicationContext, - Class type) { - return BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, - type); + Map getBeansOfType(ApplicationContext applicationContext, Class type) { + return BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, type); } }; - abstract String[] getBeanNamesForType(ApplicationContext applicationContext, - Class type); + abstract String[] getBeanNamesForType(ApplicationContext applicationContext, Class type); - abstract Map getBeansOfType(ApplicationContext applicationContext, - Class type); + abstract Map getBeansOfType(ApplicationContext applicationContext, Class type); } - private static final class ContextFailedToStart - extends BasicErrorMessageFactory { + private static final class ContextFailedToStart extends BasicErrorMessageFactory { - private ContextFailedToStart(C context, Throwable ex, String expectationFormat, - Object... arguments) { - super("%nExpecting:%n <%s>%n" + expectationFormat - + ":%nbut context failed to start:%n%s", + private ContextFailedToStart(C context, Throwable ex, String expectationFormat, Object... arguments) { + super("%nExpecting:%n <%s>%n" + expectationFormat + ":%nbut context failed to start:%n%s", combineArguments(context.toString(), ex, arguments)); } - private static Object[] combineArguments(String context, Throwable ex, - Object[] arguments) { + private static Object[] combineArguments(String context, Throwable ex, Object[] arguments) { Object[] combinedArguments = new Object[arguments.length + 2]; combinedArguments[0] = unquotedString(context); System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length); - combinedArguments[combinedArguments.length - 1] = unquotedString( - getIndentedStackTraceAsString(ex)); + combinedArguments[combinedArguments.length - 1] = unquotedString(getIndentedStackTraceAsString(ex)); return combinedArguments; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProvider.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProvider.java index d4c8f6c45d7..1452eddd295 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProvider.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProvider.java @@ -48,8 +48,8 @@ import org.springframework.util.Assert; * @see AssertableReactiveWebApplicationContext * @see ApplicationContextAssert */ -public interface ApplicationContextAssertProvider extends - ApplicationContext, AssertProvider>, Closeable { +public interface ApplicationContextAssertProvider + extends ApplicationContext, AssertProvider>, Closeable { /** * Return an assert for AspectJ. @@ -101,17 +101,15 @@ public interface ApplicationContextAssertProvider * @return a {@link ApplicationContextAssertProvider} instance */ @SuppressWarnings("unchecked") - static , C extends ApplicationContext> T get( - Class type, Class contextType, - Supplier contextSupplier) { + static , C extends ApplicationContext> T get(Class type, + Class contextType, Supplier contextSupplier) { Assert.notNull(type, "Type must not be null"); Assert.isTrue(type.isInterface(), "Type must be an interface"); Assert.notNull(contextType, "ContextType must not be null"); Assert.isTrue(contextType.isInterface(), "ContextType must be an interface"); Class[] interfaces = { type, contextType }; - return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), - interfaces, new AssertProviderApplicationContextInvocationHandler( - contextType, contextSupplier)); + return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, + new AssertProviderApplicationContextInvocationHandler(contextType, contextSupplier)); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java index 3fd506f668b..872145a1d87 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan private final RuntimeException startupFailure; - AssertProviderApplicationContextInvocationHandler(Class applicationContextType, - Supplier contextSupplier) { + AssertProviderApplicationContextInvocationHandler(Class applicationContextType, Supplier contextSupplier) { this.applicationContextType = applicationContextType; Object contextOrStartupFailure = getContextOrStartupFailure(contextSupplier); if (contextOrStartupFailure instanceof RuntimeException) { @@ -93,22 +92,19 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan @Override public String toString() { if (this.startupFailure != null) { - return "Unstarted application context " - + this.applicationContextType.getName() + "[startupFailure=" + return "Unstarted application context " + this.applicationContextType.getName() + "[startupFailure=" + this.startupFailure.getClass().getName() + "]"; } ToStringCreator builder = new ToStringCreator(this.applicationContext) .append("id", this.applicationContext.getId()) .append("applicationName", this.applicationContext.getApplicationName()) - .append("beanDefinitionCount", - this.applicationContext.getBeanDefinitionCount()); + .append("beanDefinitionCount", this.applicationContext.getBeanDefinitionCount()); return "Started application " + builder; } private boolean isGetSourceContext(Method method) { - return "getSourceApplicationContext".equals(method.getName()) - && ((method.getParameterCount() == 0) || Arrays.equals( - new Class[] { Class.class }, method.getParameterTypes())); + return "getSourceApplicationContext".equals(method.getName()) && ((method.getParameterCount() == 0) + || Arrays.equals(new Class[] { Class.class }, method.getParameterTypes())); } private Object getSourceContext(Object[] args) { @@ -120,8 +116,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan } private boolean isGetStartupFailure(Method method) { - return ("getStartupFailure".equals(method.getName()) - && method.getParameterCount() == 0); + return ("getStartupFailure".equals(method.getName()) && method.getParameterCount() == 0); } private Object getStartupFailure() { @@ -133,8 +128,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan } private Object getAssertThat(Object proxy) { - return new ApplicationContextAssert<>((ApplicationContext) proxy, - this.startupFailure); + return new ApplicationContextAssert<>((ApplicationContext) proxy, this.startupFailure); } private boolean isCloseMethod(Method method) { @@ -148,8 +142,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan return null; } - private Object invokeApplicationContextMethod(Method method, Object[] args) - throws Throwable { + private Object invokeApplicationContextMethod(Method method, Object[] args) throws Throwable { try { return method.invoke(getStartedApplicationContext(), args); } @@ -160,8 +153,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan private ApplicationContext getStartedApplicationContext() { if (this.startupFailure != null) { - throw new IllegalStateException(toString() + " failed to start", - this.startupFailure); + throw new IllegalStateException(toString() + " failed to start", this.startupFailure); } return this.applicationContext; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableApplicationContext.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableApplicationContext.java index 10156135770..9c2a4782f2b 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableApplicationContext.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ import org.springframework.context.ConfigurableApplicationContext; * @see ApplicationContext */ public interface AssertableApplicationContext - extends ApplicationContextAssertProvider, - ConfigurableApplicationContext { + extends ApplicationContextAssertProvider, ConfigurableApplicationContext { /** * Factory method to create a new {@link AssertableApplicationContext} instance. @@ -45,8 +44,7 @@ public interface AssertableApplicationContext * to start. * @return an {@link AssertableApplicationContext} instance */ - static AssertableApplicationContext get( - Supplier contextSupplier) { + static AssertableApplicationContext get(Supplier contextSupplier) { return ApplicationContextAssertProvider.get(AssertableApplicationContext.class, ConfigurableApplicationContext.class, contextSupplier); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContext.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContext.java index b32e14703e6..5af5a9fdd98 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContext.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ import org.springframework.boot.web.reactive.context.ReactiveWebApplicationConte * @see ReactiveWebApplicationContext * @see ReactiveWebApplicationContext */ -public interface AssertableReactiveWebApplicationContext extends - ApplicationContextAssertProvider, +public interface AssertableReactiveWebApplicationContext + extends ApplicationContextAssertProvider, ConfigurableReactiveWebApplicationContext { /** @@ -47,8 +47,7 @@ public interface AssertableReactiveWebApplicationContext extends */ static AssertableReactiveWebApplicationContext get( Supplier contextSupplier) { - return ApplicationContextAssertProvider.get( - AssertableReactiveWebApplicationContext.class, + return ApplicationContextAssertProvider.get(AssertableReactiveWebApplicationContext.class, ConfigurableReactiveWebApplicationContext.class, contextSupplier); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContext.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContext.java index 7b2bc5c663f..96a7d03dd1b 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContext.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ import org.springframework.web.context.WebApplicationContext; * @see WebApplicationContext */ public interface AssertableWebApplicationContext - extends ApplicationContextAssertProvider, - ConfigurableWebApplicationContext { + extends ApplicationContextAssertProvider, ConfigurableWebApplicationContext { /** * Factory method to create a new {@link AssertableWebApplicationContext} instance. @@ -45,8 +44,7 @@ public interface AssertableWebApplicationContext * fails to start. * @return a {@link AssertableWebApplicationContext} instance */ - static AssertableWebApplicationContext get( - Supplier contextSupplier) { + static AssertableWebApplicationContext get(Supplier contextSupplier) { return ApplicationContextAssertProvider.get(AssertableWebApplicationContext.class, ConfigurableWebApplicationContext.class, contextSupplier); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java index b15a674f3e0..4f7a6260311 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ class ExcludeFilterContextCustomizer implements ContextCustomizer { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { - context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(), - new TestTypeExcludeFilter()); + context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(), new TestTypeExcludeFilter()); } @Override diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java index e2e3f4eae74..7098a920f65 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java @@ -36,12 +36,11 @@ class TestTypeExcludeFilter extends TypeExcludeFilter { "org.junit.jupiter.api.extension.ExtendWith", "org.testng.annotations.Test" }; private static final String[] METHOD_ANNOTATIONS = { "org.junit.Test", - "org.junit.platform.commons.annotation.Testable", - "org.testng.annotations.Test" }; + "org.junit.platform.commons.annotation.Testable", "org.testng.annotations.Test" }; @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { if (isTestConfiguration(metadataReader)) { return true; } @@ -51,8 +50,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter { String enclosing = metadataReader.getClassMetadata().getEnclosingClassName(); if (enclosing != null) { try { - if (match(metadataReaderFactory.getMetadataReader(enclosing), - metadataReaderFactory)) { + if (match(metadataReaderFactory.getMetadataReader(enclosing), metadataReaderFactory)) { return true; } } @@ -64,8 +62,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter { } private boolean isTestConfiguration(MetadataReader metadataReader) { - return (metadataReader.getAnnotationMetadata() - .isAnnotated(TestComponent.class.getName())); + return (metadataReader.getAnnotationMetadata().isAnnotated(TestComponent.class.getName())); } private boolean isTestClass(MetadataReader metadataReader) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java index 6b26d3cf7ea..8e43214ec26 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java @@ -124,9 +124,8 @@ public abstract class AbstractApplicationContextRunner contextFactory) { - this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), - TestPropertyValues.empty(), null, null, Collections.emptyList(), - Collections.emptyList()); + this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), TestPropertyValues.empty(), null, + null, Collections.emptyList(), Collections.emptyList()); } /** @@ -141,11 +140,9 @@ public abstract class AbstractApplicationContextRunner contextFactory, - List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, - List configurations) { + List> initializers, TestPropertyValues environmentProperties, + TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent, + List> beanRegistrations, List configurations) { Assert.notNull(contextFactory, "ContextFactory must not be null"); Assert.notNull(environmentProperties, "EnvironmentProperties must not be null"); Assert.notNull(systemProperties, "SystemProperties must not be null"); @@ -169,9 +166,8 @@ public abstract class AbstractApplicationContextRunner initializer) { Assert.notNull(initializer, "Initializer must not be null"); - return newInstance(this.contextFactory, add(this.initializers, initializer), - this.environmentProperties, this.systemProperties, this.classLoader, - this.parent, this.beanRegistrations, this.configurations); + return newInstance(this.contextFactory, add(this.initializers, initializer), this.environmentProperties, + this.systemProperties, this.classLoader, this.parent, this.beanRegistrations, this.configurations); } /** @@ -185,10 +181,8 @@ public abstract class AbstractApplicationContextRunner SELF withBean(String name, Class type, Object... constructorArgs) { - return newInstance(this.contextFactory, this.initializers, - this.environmentProperties, this.systemProperties, this.classLoader, - this.parent, - add(this.beanRegistrations, - new BeanRegistration<>(name, type, constructorArgs)), - this.configurations); + return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties, + this.classLoader, this.parent, + add(this.beanRegistrations, new BeanRegistration<>(name, type, constructorArgs)), this.configurations); } /** @@ -287,8 +275,7 @@ public abstract class AbstractApplicationContextRunner the type of the bean * @return a new instance with the updated bean */ - public SELF withBean(Class type, Supplier supplier, - BeanDefinitionCustomizer... customizers) { + public SELF withBean(Class type, Supplier supplier, BeanDefinitionCustomizer... customizers) { return withBean(null, type, supplier, customizers); } @@ -309,11 +296,9 @@ public abstract class AbstractApplicationContextRunner SELF withBean(String name, Class type, Supplier supplier, BeanDefinitionCustomizer... customizers) { - return newInstance(this.contextFactory, this.initializers, - this.environmentProperties, this.systemProperties, this.classLoader, - this.parent, - add(this.beanRegistrations, - new BeanRegistration<>(name, type, supplier, customizers)), + return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties, + this.classLoader, this.parent, + add(this.beanRegistrations, new BeanRegistration<>(name, type, supplier, customizers)), this.configurations); } @@ -334,10 +319,8 @@ public abstract class AbstractApplicationContextRunner contextFactory, - List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, - List configurations); + List> initializers, TestPropertyValues environmentProperties, + TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent, + List> beanRegistrations, List configurations); /** * Create and refresh a new {@link ApplicationContext} based on the current state of @@ -402,12 +383,10 @@ public abstract class AbstractApplicationContextRunner assertType = (Class) resolvableType.resolveGeneric(1); Class contextType = (Class) resolvableType.resolveGeneric(2); - return ApplicationContextAssertProvider.get(assertType, contextType, - this::createAndLoadContext); + return ApplicationContextAssertProvider.get(assertType, contextType, this::createAndLoadContext); } private C createAndLoadContext() { @@ -464,14 +443,12 @@ public abstract class AbstractApplicationContextRunner registrar; public BeanRegistration(String name, Class type, Object... constructorArgs) { - this.registrar = (context) -> context.registerBean(name, type, - constructorArgs); + this.registrar = (context) -> context.registerBean(name, type, constructorArgs); } public BeanRegistration(String name, Class type, Supplier supplier, BeanDefinitionCustomizer... customizers) { - this.registrar = (context) -> context.registerBean(name, type, supplier, - customizers); + this.registrar = (context) -> context.registerBean(name, type, supplier, customizers); } public void apply(ConfigurableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ApplicationContextRunner.java index 571576532f2..a45fd753c23 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ApplicationContextRunner.java @@ -54,33 +54,27 @@ public class ApplicationContextRunner extends * {@code contextFactory} as the underlying source. * @param contextFactory a supplier that returns a new instance on each call */ - public ApplicationContextRunner( - Supplier contextFactory) { + public ApplicationContextRunner(Supplier contextFactory) { super(contextFactory); } - private ApplicationContextRunner( - Supplier contextFactory, + private ApplicationContextRunner(Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List> beanRegistrations, List configurations) { - super(contextFactory, initializers, environmentProperties, systemProperties, - classLoader, parent, beanRegistrations, configurations); - } - - @Override - protected ApplicationContextRunner newInstance( - Supplier contextFactory, - List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, - List configurations) { - return new ApplicationContextRunner(contextFactory, initializers, - environmentProperties, systemProperties, classLoader, parent, + super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent, beanRegistrations, configurations); } + @Override + protected ApplicationContextRunner newInstance(Supplier contextFactory, + List> initializers, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List> beanRegistrations, + List configurations) { + return new ApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties, + classLoader, parent, beanRegistrations, configurations); + } + } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ReactiveWebApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ReactiveWebApplicationContextRunner.java index 446c306e62e..7f05a8743fd 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ReactiveWebApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/ReactiveWebApplicationContextRunner.java @@ -54,33 +54,28 @@ public final class ReactiveWebApplicationContextRunner extends * {@code contextFactory} as the underlying source. * @param contextFactory a supplier that returns a new instance on each call */ - public ReactiveWebApplicationContextRunner( - Supplier contextFactory) { + public ReactiveWebApplicationContextRunner(Supplier contextFactory) { super(contextFactory); } - private ReactiveWebApplicationContextRunner( - Supplier contextFactory, + private ReactiveWebApplicationContextRunner(Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List> beanRegistrations, List configurations) { - super(contextFactory, initializers, environmentProperties, systemProperties, - classLoader, parent, beanRegistrations, configurations); + super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent, + beanRegistrations, configurations); } @Override protected ReactiveWebApplicationContextRunner newInstance( Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List> beanRegistrations, List configurations) { - return new ReactiveWebApplicationContextRunner(contextFactory, initializers, - environmentProperties, systemProperties, classLoader, parent, - beanRegistrations, configurations); + return new ReactiveWebApplicationContextRunner(contextFactory, initializers, environmentProperties, + systemProperties, classLoader, parent, beanRegistrations, configurations); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/WebApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/WebApplicationContextRunner.java index 5b4387928e2..1df1bca5fc2 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/WebApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/WebApplicationContextRunner.java @@ -58,33 +58,27 @@ public final class WebApplicationContextRunner extends * {@code contextFactory} as the underlying source. * @param contextFactory a supplier that returns a new instance on each call */ - public WebApplicationContextRunner( - Supplier contextFactory) { + public WebApplicationContextRunner(Supplier contextFactory) { super(contextFactory); } - private WebApplicationContextRunner( - Supplier contextFactory, + private WebApplicationContextRunner(Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List> beanRegistrations, List configurations) { - super(contextFactory, initializers, environmentProperties, systemProperties, - classLoader, parent, beanRegistrations, configurations); + super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent, + beanRegistrations, configurations); } @Override - protected WebApplicationContextRunner newInstance( - Supplier contextFactory, + protected WebApplicationContextRunner newInstance(Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List> beanRegistrations, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List> beanRegistrations, List configurations) { - return new WebApplicationContextRunner(contextFactory, initializers, - environmentProperties, systemProperties, classLoader, parent, - beanRegistrations, configurations); + return new WebApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties, + classLoader, parent, beanRegistrations, configurations); } /** diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java index 1e09fdc7b0f..449ba819ad3 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java @@ -320,8 +320,7 @@ public abstract class AbstractJsonMarshalTester { } private void verify() { - Assert.state(this.resourceLoadClass != null, - "Uninitialized JsonMarshalTester (ResourceLoadClass is null)"); + Assert.state(this.resourceLoadClass != null, "Uninitialized JsonMarshalTester (ResourceLoadClass is null)"); Assert.state(this.type != null, "Uninitialized JsonMarshalTester (Type is null)"); } @@ -332,8 +331,7 @@ public abstract class AbstractJsonMarshalTester { * @return the JSON string * @throws IOException on write error */ - protected abstract String writeObject(T value, ResolvableType type) - throws IOException; + protected abstract String writeObject(T value, ResolvableType type) throws IOException; /** * Read from the specified input stream to create an object of the specified type. The @@ -343,8 +341,7 @@ public abstract class AbstractJsonMarshalTester { * @return the resulting object * @throws IOException on read error */ - protected T readObject(InputStream inputStream, ResolvableType type) - throws IOException { + protected T readObject(InputStream inputStream, ResolvableType type) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); return readObject(reader, type); } @@ -356,8 +353,7 @@ public abstract class AbstractJsonMarshalTester { * @return the resulting object * @throws IOException on read error */ - protected abstract T readObject(Reader reader, ResolvableType type) - throws IOException; + protected abstract T readObject(Reader reader, ResolvableType type) throws IOException; /** * Utility class used to support field initialization. Used by subclasses to support @@ -370,8 +366,7 @@ public abstract class AbstractJsonMarshalTester { private final Class testerClass; @SuppressWarnings("rawtypes") - protected FieldInitializer( - Class testerClass) { + protected FieldInitializer(Class testerClass) { Assert.notNull(testerClass, "TesterClass must not be null"); this.testerClass = testerClass; } @@ -389,8 +384,7 @@ public abstract class AbstractJsonMarshalTester { (field) -> doWithField(field, testInstance, marshaller)); } - protected void doWithField(Field field, Object test, - ObjectFactory marshaller) { + protected void doWithField(Field field, Object test, ObjectFactory marshaller) { if (this.testerClass.isAssignableFrom(field.getType())) { ReflectionUtils.makeAccessible(field); Object existingValue = ReflectionUtils.getField(field, test); @@ -402,12 +396,11 @@ public abstract class AbstractJsonMarshalTester { private void setupField(Field field, Object test, ObjectFactory marshaller) { ResolvableType type = ResolvableType.forField(field).getGeneric(); - ReflectionUtils.setField(field, test, - createTester(test.getClass(), type, marshaller.getObject())); + ReflectionUtils.setField(field, test, createTester(test.getClass(), type, marshaller.getObject())); } - protected abstract AbstractJsonMarshalTester createTester( - Class resourceLoadClass, ResolvableType type, M marshaller); + protected abstract AbstractJsonMarshalTester createTester(Class resourceLoadClass, + ResolvableType type, M marshaller); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java index 61f33c633d9..bf82090e678 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,15 +44,12 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa return new DuplicateJsonObjectContextCustomizer(); } - private static class DuplicateJsonObjectContextCustomizer - implements ContextCustomizer { + private static class DuplicateJsonObjectContextCustomizer implements ContextCustomizer { - private final Log logger = LogFactory - .getLog(DuplicateJsonObjectContextCustomizer.class); + private final Log logger = LogFactory.getLog(DuplicateJsonObjectContextCustomizer.class); @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { List jsonObjects = findJsonObjects(); if (jsonObjects.size() > 1) { logDuplicateJsonObjectsWarning(jsonObjects); @@ -62,8 +59,7 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa private List findJsonObjects() { List jsonObjects = new ArrayList<>(); try { - Enumeration resources = getClass().getClassLoader() - .getResources("org/json/JSONObject.class"); + Enumeration resources = getClass().getClassLoader().getResources("org/json/JSONObject.class"); while (resources.hasMoreElements()) { jsonObjects.add(resources.nextElement()); } @@ -76,13 +72,12 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa private void logDuplicateJsonObjectsWarning(List jsonObjects) { StringBuilder message = new StringBuilder( - String.format("%n%nFound multiple occurrences of" - + " org.json.JSONObject on the class path:%n%n")); + String.format("%n%nFound multiple occurrences of" + " org.json.JSONObject on the class path:%n%n")); for (URL jsonObject : jsonObjects) { message.append(String.format("\t%s%n", jsonObject)); } - message.append(String.format("%nYou may wish to exclude one of them to ensure" - + " predictable runtime behavior%n")); + message.append(String + .format("%nYou may wish to exclude one of them to ensure" + " predictable runtime behavior%n")); this.logger.warn(message); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java index bcef31b0fb5..797c98918c8 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java @@ -119,8 +119,8 @@ public class GsonTester extends AbstractJsonMarshalTester { } @Override - protected AbstractJsonMarshalTester createTester( - Class resourceLoadClass, ResolvableType type, Gson marshaller) { + protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type, + Gson marshaller) { return new GsonTester<>(resourceLoadClass, type, marshaller); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java index a971bc8a97f..79ba54bdf1b 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java @@ -83,13 +83,11 @@ public class JacksonTester extends AbstractJsonMarshalTester { * @param type the type under test * @param objectMapper the Jackson object mapper */ - public JacksonTester(Class resourceLoadClass, ResolvableType type, - ObjectMapper objectMapper) { + public JacksonTester(Class resourceLoadClass, ResolvableType type, ObjectMapper objectMapper) { this(resourceLoadClass, type, objectMapper, null); } - public JacksonTester(Class resourceLoadClass, ResolvableType type, - ObjectMapper objectMapper, Class view) { + public JacksonTester(Class resourceLoadClass, ResolvableType type, ObjectMapper objectMapper, Class view) { super(resourceLoadClass, type); Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; @@ -98,15 +96,13 @@ public class JacksonTester extends AbstractJsonMarshalTester { @Override protected JsonContent getJsonContent(String json) { - Configuration configuration = Configuration.builder() - .jsonProvider(new JacksonJsonProvider(this.objectMapper)) + Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonProvider(this.objectMapper)) .mappingProvider(new JacksonMappingProvider(this.objectMapper)).build(); return new JsonContent<>(getResourceLoadClass(), getType(), json, configuration); } @Override - protected T readObject(InputStream inputStream, ResolvableType type) - throws IOException { + protected T readObject(InputStream inputStream, ResolvableType type) throws IOException { return getObjectReader(type).readValue(inputStream); } @@ -158,8 +154,7 @@ public class JacksonTester extends AbstractJsonMarshalTester { * @param objectMapperFactory a factory to create the object mapper * @see #initFields(Object, ObjectMapper) */ - public static void initFields(Object testInstance, - ObjectFactory objectMapperFactory) { + public static void initFields(Object testInstance, ObjectFactory objectMapperFactory) { new JacksonFieldInitializer().initFields(testInstance, objectMapperFactory); } @@ -170,8 +165,7 @@ public class JacksonTester extends AbstractJsonMarshalTester { * @return the new instance */ public JacksonTester forView(Class view) { - return new JacksonTester<>(this.getResourceLoadClass(), this.getType(), - this.objectMapper, view); + return new JacksonTester<>(this.getResourceLoadClass(), this.getType(), this.objectMapper, view); } /** @@ -184,8 +178,7 @@ public class JacksonTester extends AbstractJsonMarshalTester { } @Override - protected AbstractJsonMarshalTester createTester( - Class resourceLoadClass, ResolvableType type, + protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type, ObjectMapper marshaller) { return new JacksonTester<>(resourceLoadClass, type, marshaller); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java index ac85253dab2..735f808a49a 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java @@ -59,8 +59,7 @@ public final class JsonContent implements AssertProvider { * @param json the actual JSON content * @param configuration the JsonPath configuration */ - JsonContent(Class resourceLoadClass, ResolvableType type, String json, - Configuration configuration) { + JsonContent(Class resourceLoadClass, ResolvableType type, String json, Configuration configuration) { Assert.notNull(resourceLoadClass, "ResourceLoadClass must not be null"); Assert.notNull(json, "JSON must not be null"); Assert.notNull(configuration, "Configuration must not be null"); @@ -79,8 +78,7 @@ public final class JsonContent implements AssertProvider { @Override @Deprecated public JsonContentAssert assertThat() { - return new JsonContentAssert(this.resourceLoadClass, null, this.json, - this.configuration); + return new JsonContentAssert(this.resourceLoadClass, null, this.json, this.configuration); } /** diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java index a729ccac939..bb490852367 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java @@ -73,8 +73,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass, Charset charset, - CharSequence json) { + public JsonContentAssert(Class resourceLoadClass, Charset charset, CharSequence json) { this(resourceLoadClass, charset, json, Configuration.defaultConfiguration()); } @@ -86,8 +85,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass, Charset charset, CharSequence json, - Configuration configuration) { + JsonContentAssert(Class resourceLoadClass, Charset charset, CharSequence json, Configuration configuration) { super(json, JsonContentAssert.class); this.configuration = configuration; this.loader = new JsonLoader(resourceLoadClass, charset); @@ -218,8 +216,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass) { + public JsonContentAssert isStrictlyEqualToJson(String path, Class resourceLoadClass) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, JSONCompareMode.STRICT)); } @@ -232,8 +229,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass, - JSONCompareMode compareMode) { + public JsonContentAssert isEqualToJson(String path, Class resourceLoadClass, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, compareMode)); } @@ -333,8 +327,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass, - JSONComparator comparator) { + public JsonContentAssert isEqualToJson(String path, Class resourceLoadClass, JSONComparator comparator) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, comparator)); } @@ -412,8 +402,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass) { + public JsonContentAssert isNotStrictlyEqualToJson(String path, Class resourceLoadClass) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotPassed(compare(expectedJson, JSONCompareMode.STRICT)); } @@ -619,8 +606,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(String path, Class resourceLoadClass, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -646,8 +631,7 @@ public class JsonContentAssert extends AbstractAssert resourceLoadClass, - JSONComparator comparator) { + public JsonContentAssert isNotEqualToJson(String path, Class resourceLoadClass, JSONComparator comparator) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotPassed(compare(expectedJson, comparator)); } @@ -728,8 +707,7 @@ public class JsonContentAssert extends AbstractAssert extractingJsonPathValue( - CharSequence expression, Object... args) { + public AbstractObjectAssert extractingJsonPathValue(CharSequence expression, Object... args) { return Assertions.assertThat(new JsonPathValue(expression, args).getValue(false)); } @@ -928,10 +895,9 @@ public class JsonContentAssert extends AbstractAssert extractingJsonPathStringValue( - CharSequence expression, Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, String.class, "a string")); + public AbstractCharSequenceAssert extractingJsonPathStringValue(CharSequence expression, + Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, String.class, "a string")); } /** @@ -942,10 +908,8 @@ public class JsonContentAssert extends AbstractAssert extractingJsonPathNumberValue( - CharSequence expression, Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, Number.class, "a number")); + public AbstractObjectAssert extractingJsonPathNumberValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, Number.class, "a number")); } /** @@ -956,10 +920,8 @@ public class JsonContentAssert extends AbstractAssert extractingJsonPathBooleanValue( - CharSequence expression, Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, Boolean.class, "a boolean")); + public AbstractBooleanAssert extractingJsonPathBooleanValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, Boolean.class, "a boolean")); } /** @@ -972,10 +934,8 @@ public class JsonContentAssert extends AbstractAssert ListAssert extractingJsonPathArrayValue(CharSequence expression, - Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, List.class, "an array")); + public ListAssert extractingJsonPathArrayValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, List.class, "an array")); } /** @@ -989,15 +949,13 @@ public class JsonContentAssert extends AbstractAssert MapAssert extractingJsonPathMapValue(CharSequence expression, - Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, Map.class, "a map")); + public MapAssert extractingJsonPathMapValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, Map.class, "a map")); } @SuppressWarnings("unchecked") - private T extractingJsonPathValue(CharSequence expression, Object[] args, - Class type, String expectedDescription) { + private T extractingJsonPathValue(CharSequence expression, Object[] args, Class type, + String expectedDescription) { JsonPathValue value = new JsonPathValue(expression, args); if (value.getValue(false) != null) { value.assertHasValue(type, expectedDescription); @@ -1005,14 +963,12 @@ public class JsonContentAssert extends AbstractAssert extends AbstractJsonMarshalTester { } @Override - protected AbstractJsonMarshalTester createTester( - Class resourceLoadClass, ResolvableType type, Jsonb marshaller) { + protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type, + Jsonb marshaller) { return new JsonbTester<>(resourceLoadClass, type, marshaller); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java index 16081dacd03..2d5aa7b2b42 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.assertj.core.internal.Objects; * @author Phillip Webb * @since 1.4.0 */ -public class ObjectContentAssert - extends AbstractObjectAssert, A> { +public class ObjectContentAssert extends AbstractObjectAssert, A> { protected ObjectContentAssert(A actual) { super(actual, ObjectContentAssert.class); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java index a18f5f5f794..515e77b26bb 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ abstract class Definition { private final QualifierDefinition qualifier; - Definition(String name, MockReset reset, boolean proxyTargetAware, - QualifierDefinition qualifier) { + Definition(String name, MockReset reset, boolean proxyTargetAware, QualifierDefinition qualifier) { this.name = name; this.reset = (reset != null) ? reset : MockReset.AFTER; this.proxyTargetAware = proxyTargetAware; @@ -88,8 +87,7 @@ abstract class Definition { boolean result = true; result = result && ObjectUtils.nullSafeEquals(this.name, other.name); result = result && ObjectUtils.nullSafeEquals(this.reset, other.reset); - result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware, - other.proxyTargetAware); + result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware, other.proxyTargetAware); result = result && ObjectUtils.nullSafeEquals(this.qualifier, other.qualifier); return result; } @@ -99,8 +97,7 @@ abstract class Definition { int result = 1; result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.name); result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.reset); - result = MULTIPLIER * result - + ObjectUtils.nullSafeHashCode(this.proxyTargetAware); + result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.proxyTargetAware); result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.qualifier); return result; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java index 4376d0c9eec..fdd907eedca 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java @@ -65,8 +65,7 @@ class DefinitionsParser { } private void parseElement(AnnotatedElement element) { - MergedAnnotations annotations = MergedAnnotations.from(element, - SearchStrategy.SUPERCLASS); + MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.SUPERCLASS); annotations.stream(MockBean.class).map(MergedAnnotation::synthesize) .forEach((annotation) -> parseMockBeanAnnotation(annotation, element)); annotations.stream(SpyBean.class).map(MergedAnnotation::synthesize) @@ -75,16 +74,13 @@ class DefinitionsParser { private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element) { Set typesToMock = getOrDeduceTypes(element, annotation.value()); - Assert.state(!typesToMock.isEmpty(), - () -> "Unable to deduce type to mock from " + element); + Assert.state(!typesToMock.isEmpty(), () -> "Unable to deduce type to mock from " + element); if (StringUtils.hasLength(annotation.name())) { - Assert.state(typesToMock.size() == 1, - "The name attribute can only be used when mocking a single class"); + Assert.state(typesToMock.size() == 1, "The name attribute can only be used when mocking a single class"); } for (ResolvableType typeToMock : typesToMock) { - MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, - annotation.extraInterfaces(), annotation.answer(), - annotation.serializable(), annotation.reset(), + MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, annotation.extraInterfaces(), + annotation.answer(), annotation.serializable(), annotation.reset(), QualifierDefinition.forElement(element)); addDefinition(element, definition, "mock"); } @@ -92,33 +88,27 @@ class DefinitionsParser { private void parseSpyBeanAnnotation(SpyBean annotation, AnnotatedElement element) { Set typesToSpy = getOrDeduceTypes(element, annotation.value()); - Assert.state(!typesToSpy.isEmpty(), - () -> "Unable to deduce type to spy from " + element); + Assert.state(!typesToSpy.isEmpty(), () -> "Unable to deduce type to spy from " + element); if (StringUtils.hasLength(annotation.name())) { - Assert.state(typesToSpy.size() == 1, - "The name attribute can only be used when spying a single class"); + Assert.state(typesToSpy.size() == 1, "The name attribute can only be used when spying a single class"); } for (ResolvableType typeToSpy : typesToSpy) { - SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, - annotation.reset(), annotation.proxyTargetAware(), - QualifierDefinition.forElement(element)); + SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, annotation.reset(), + annotation.proxyTargetAware(), QualifierDefinition.forElement(element)); addDefinition(element, definition, "spy"); } } - private void addDefinition(AnnotatedElement element, Definition definition, - String type) { + private void addDefinition(AnnotatedElement element, Definition definition, String type) { boolean isNewDefinition = this.definitions.add(definition); - Assert.state(isNewDefinition, - () -> "Duplicate " + type + " definition " + definition); + Assert.state(isNewDefinition, () -> "Duplicate " + type + " definition " + definition); if (element instanceof Field) { Field field = (Field) element; this.definitionFields.put(definition, field); } } - private Set getOrDeduceTypes(AnnotatedElement element, - Class[] value) { + private Set getOrDeduceTypes(AnnotatedElement element, Class[] value) { Set types = new LinkedHashSet<>(); for (Class clazz : value) { types.add(ResolvableType.forClass(clazz)); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java index 9ec92299228..13ee6280f72 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,8 @@ class MockDefinition extends Definition { private final boolean serializable; - MockDefinition(String name, ResolvableType typeToMock, Class[] extraInterfaces, - Answers answer, boolean serializable, MockReset reset, - QualifierDefinition qualifier) { + MockDefinition(String name, ResolvableType typeToMock, Class[] extraInterfaces, Answers answer, + boolean serializable, MockReset reset, QualifierDefinition qualifier) { super(name, reset, false, qualifier); Assert.notNull(typeToMock, "TypeToMock must not be null"); this.typeToMock = typeToMock; @@ -111,8 +110,7 @@ class MockDefinition extends Definition { MockDefinition other = (MockDefinition) obj; boolean result = super.equals(obj); result = result && ObjectUtils.nullSafeEquals(this.typeToMock, other.typeToMock); - result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces, - other.extraInterfaces); + result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces, other.extraInterfaces); result = result && ObjectUtils.nullSafeEquals(this.answer, other.answer); result = result && this.serializable == other.serializable; return result; @@ -130,11 +128,9 @@ class MockDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()) - .append("typeToMock", this.typeToMock) - .append("extraInterfaces", this.extraInterfaces) - .append("answer", this.answer).append("serializable", this.serializable) - .append("reset", getReset()).toString(); + return new ToStringCreator(this).append("name", getName()).append("typeToMock", this.typeToMock) + .append("extraInterfaces", this.extraInterfaces).append("answer", this.answer) + .append("serializable", this.serializable).append("reset", getReset()).toString(); } public T createMock() { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java index 5fa3c4866b8..93d0c4acf0e 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ class MockitoContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { if (context instanceof BeanDefinitionRegistry) { - MockitoPostProcessor.register((BeanDefinitionRegistry) context, - this.definitions); + MockitoPostProcessor.register((BeanDefinitionRegistry) context, this.definitions); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java index 5bc41161db6..1b52fd5c6ce 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java @@ -76,16 +76,14 @@ import org.springframework.util.StringUtils; * @since 1.4.0 */ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAdapter - implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor, - Ordered { + implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor, Ordered { private static final String FACTORY_BEAN_OBJECT_TYPE = "factoryBeanObjectType"; private static final String BEAN_NAME = MockitoPostProcessor.class.getName(); private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions - .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, - "configurationClass"); + .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); private static final BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); @@ -125,16 +123,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory, - "@MockBean can only be used on bean factories that " - + "implement BeanDefinitionRegistry"); + "@MockBean can only be used on bean factories that " + "implement BeanDefinitionRegistry"); postProcessBeanFactory(beanFactory, (BeanDefinitionRegistry) beanFactory); } - private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry) { + private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { beanFactory.registerSingleton(MockitoBeans.class.getName(), this.mockitoBeans); DefinitionsParser parser = new DefinitionsParser(this.definitions); for (Class configurationClass : getConfigurationClasses(beanFactory)) { @@ -147,19 +142,15 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private Set> getConfigurationClasses( - ConfigurableListableBeanFactory beanFactory) { + private Set> getConfigurationClasses(ConfigurableListableBeanFactory beanFactory) { Set> configurationClasses = new LinkedHashSet<>(); - for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory) - .values()) { - configurationClasses.add(ClassUtils.resolveClassName( - beanDefinition.getBeanClassName(), this.classLoader)); + for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory).values()) { + configurationClasses.add(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), this.classLoader)); } return configurationClasses; } - private Map getConfigurationBeanDefinitions( - ConfigurableListableBeanFactory beanFactory) { + private Map getConfigurationBeanDefinitions(ConfigurableListableBeanFactory beanFactory) { Map definitions = new LinkedHashMap<>(); for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition definition = beanFactory.getBeanDefinition(beanName); @@ -170,8 +161,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return definitions; } - private void register(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, Definition definition, Field field) { + private void register(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + Definition definition, Field field) { if (definition instanceof MockDefinition) { registerMock(beanFactory, registry, (MockDefinition) definition, field); } @@ -180,8 +171,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private void registerMock(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, MockDefinition definition, Field field) { + private void registerMock(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + MockDefinition definition, Field field) { RootBeanDefinition beanDefinition = createBeanDefinition(definition); String beanName = getBeanName(beanFactory, registry, definition, beanDefinition); String transformedBeanName = BeanFactoryUtils.transformedBeanName(beanName); @@ -201,8 +192,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } private RootBeanDefinition createBeanDefinition(MockDefinition mockDefinition) { - RootBeanDefinition definition = new RootBeanDefinition( - mockDefinition.getTypeToMock().resolve()); + RootBeanDefinition definition = new RootBeanDefinition(mockDefinition.getTypeToMock().resolve()); definition.setTargetType(mockDefinition.getTypeToMock()); if (mockDefinition.getQualifier() != null) { mockDefinition.getQualifier().applyTo(definition); @@ -210,40 +200,35 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return definition; } - private String getBeanName(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, MockDefinition mockDefinition, - RootBeanDefinition beanDefinition) { + private String getBeanName(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + MockDefinition mockDefinition, RootBeanDefinition beanDefinition) { if (StringUtils.hasLength(mockDefinition.getName())) { return mockDefinition.getName(); } - Set existingBeans = getExistingBeans(beanFactory, - mockDefinition.getTypeToMock(), mockDefinition.getQualifier()); + Set existingBeans = getExistingBeans(beanFactory, mockDefinition.getTypeToMock(), + mockDefinition.getQualifier()); if (existingBeans.isEmpty()) { - return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, - registry); + return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry); } if (existingBeans.size() == 1) { return existingBeans.iterator().next(); } - String primaryCandidate = determinePrimaryCandidate(registry, existingBeans, - mockDefinition.getTypeToMock()); + String primaryCandidate = determinePrimaryCandidate(registry, existingBeans, mockDefinition.getTypeToMock()); if (primaryCandidate != null) { return primaryCandidate; } - throw new IllegalStateException( - "Unable to register mock bean " + mockDefinition.getTypeToMock() - + " expected a single matching bean to replace but found " - + existingBeans); + throw new IllegalStateException("Unable to register mock bean " + mockDefinition.getTypeToMock() + + " expected a single matching bean to replace but found " + existingBeans); } private void copyBeanDefinitionDetails(BeanDefinition from, RootBeanDefinition to) { to.setPrimary(from.isPrimary()); } - private void registerSpy(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) { - Set existingBeans = getExistingBeans(beanFactory, - spyDefinition.getTypeToSpy(), spyDefinition.getQualifier()); + private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + SpyDefinition spyDefinition, Field field) { + Set existingBeans = getExistingBeans(beanFactory, spyDefinition.getTypeToSpy(), + spyDefinition.getQualifier()); if (ObjectUtils.isEmpty(existingBeans)) { createSpy(registry, spyDefinition, field); } @@ -252,8 +237,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private Set getExistingBeans(ConfigurableListableBeanFactory beanFactory, - ResolvableType type, QualifierDefinition qualifier) { + private Set getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type, + QualifierDefinition qualifier) { Set candidates = new TreeSet<>(); for (String candidate : getExistingBeans(beanFactory, type)) { if (qualifier == null || qualifier.matches(beanFactory, candidate)) { @@ -263,10 +248,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return candidates; } - private Set getExistingBeans(ConfigurableListableBeanFactory beanFactory, - ResolvableType type) { - Set beans = new LinkedHashSet<>( - Arrays.asList(beanFactory.getBeanNamesForType(type))); + private Set getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) { + Set beans = new LinkedHashSet<>(Arrays.asList(beanFactory.getBeanNamesForType(type))); String typeName = type.resolve(Object.class).getName(); for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class)) { beanName = BeanFactoryUtils.transformedBeanName(beanName); @@ -288,49 +271,43 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, - Field field) { - RootBeanDefinition beanDefinition = new RootBeanDefinition( - spyDefinition.getTypeToSpy().resolve()); - String beanName = MockitoPostProcessor.beanNameGenerator - .generateBeanName(beanDefinition, registry); + private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(spyDefinition.getTypeToSpy().resolve()); + String beanName = MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry); registry.registerBeanDefinition(beanName, beanDefinition); registerSpy(spyDefinition, field, beanName); } - private void registerSpies(BeanDefinitionRegistry registry, - SpyDefinition spyDefinition, Field field, Collection existingBeans) { + private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field, + Collection existingBeans) { try { String beanName = determineBeanName(existingBeans, spyDefinition, registry); registerSpy(spyDefinition, field, beanName); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex); + throw new IllegalStateException("Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex); } } - private String determineBeanName(Collection existingBeans, - SpyDefinition definition, BeanDefinitionRegistry registry) { + private String determineBeanName(Collection existingBeans, SpyDefinition definition, + BeanDefinitionRegistry registry) { if (StringUtils.hasText(definition.getName())) { return definition.getName(); } if (existingBeans.size() == 1) { return existingBeans.iterator().next(); } - return determinePrimaryCandidate(registry, existingBeans, - definition.getTypeToSpy()); + return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy()); } - private String determinePrimaryCandidate(BeanDefinitionRegistry registry, - Collection candidateBeanNames, ResolvableType type) { + private String determinePrimaryCandidate(BeanDefinitionRegistry registry, Collection candidateBeanNames, + ResolvableType type) { String primaryBeanName = null; for (String candidateBeanName : candidateBeanNames) { BeanDefinition beanDefinition = registry.getBeanDefinition(candidateBeanName); if (beanDefinition.isPrimary()) { if (primaryBeanName != null) { - throw new NoUniqueBeanDefinitionException(type.resolve(), - candidateBeanNames.size(), + throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.size(), "more than one 'primary' bean found among candidates: " + Arrays.asList(candidateBeanNames)); } @@ -348,8 +325,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - protected final Object createSpyIfNecessary(Object bean, String beanName) - throws BeansException { + protected final Object createSpyIfNecessary(Object bean, String beanName) throws BeansException { SpyDefinition definition = this.spies.get(beanName); if (definition != null) { bean = definition.createSpy(beanName, bean); @@ -358,11 +334,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } @Override - public PropertyValues postProcessPropertyValues(PropertyValues pvs, - PropertyDescriptor[] pds, final Object bean, String beanName) - throws BeansException { - ReflectionUtils.doWithFields(bean.getClass(), - (field) -> postProcessField(bean, field)); + public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean, + String beanName) throws BeansException { + ReflectionUtils.doWithFields(bean.getClass(), (field) -> postProcessField(bean, field)); return pvs; } @@ -375,8 +349,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda void inject(Field field, Object target, Definition definition) { String beanName = this.beanNameRegistry.get(definition); - Assert.state(StringUtils.hasLength(beanName), - () -> "No bean found for definition " + definition); + Assert.state(StringUtils.hasLength(beanName), () -> "No bean found for definition " + definition); inject(field, target, beanName); } @@ -413,8 +386,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * @param registry the bean definition registry * @param definitions the initial mock/spy definitions */ - public static void register(BeanDefinitionRegistry registry, - Set definitions) { + public static void register(BeanDefinitionRegistry registry, Set definitions) { register(registry, MockitoPostProcessor.class, definitions); } @@ -426,13 +398,11 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * @param definitions the initial mock/spy definitions */ @SuppressWarnings("unchecked") - public static void register(BeanDefinitionRegistry registry, - Class postProcessor, + public static void register(BeanDefinitionRegistry registry, Class postProcessor, Set definitions) { SpyPostProcessor.register(registry); BeanDefinition definition = getOrAddBeanDefinition(registry, postProcessor); - ValueHolder constructorArg = definition.getConstructorArgumentValues() - .getIndexedArgumentValue(0, Set.class); + ValueHolder constructorArg = definition.getConstructorArgumentValues().getIndexedArgumentValue(0, Set.class); Set existing = (Set) constructorArg.getValue(); if (definitions != null) { existing.addAll(definitions); @@ -444,10 +414,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda if (!registry.containsBeanDefinition(BEAN_NAME)) { RootBeanDefinition definition = new RootBeanDefinition(postProcessor); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - ConstructorArgumentValues constructorArguments = definition - .getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - new LinkedHashSet()); + ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); + constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet()); registry.registerBeanDefinition(BEAN_NAME, definition); return definition; } @@ -459,8 +427,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * Registered as a separate processor so that it can be ordered above AOP post * processors. */ - static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter - implements PriorityOrdered { + static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements PriorityOrdered { private static final String BEAN_NAME = SpyPostProcessor.class.getName(); @@ -476,14 +443,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } @Override - public Object getEarlyBeanReference(Object bean, String beanName) - throws BeansException { + public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { return this.mockitoPostProcessor.createSpyIfNecessary(bean, beanName); } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof FactoryBean) { return bean; } @@ -492,11 +457,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda public static void register(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BEAN_NAME)) { - RootBeanDefinition definition = new RootBeanDefinition( - SpyPostProcessor.class); + RootBeanDefinition definition = new RootBeanDefinition(SpyPostProcessor.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - ConstructorArgumentValues constructorArguments = definition - .getConstructorArgumentValues(); + ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); constructorArguments.addIndexedArgumentValue(0, new RuntimeBeanReference(MockitoPostProcessor.BEAN_NAME)); registry.registerBeanDefinition(BEAN_NAME, definition); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java index afa05192047..febfb6436d3 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java @@ -56,8 +56,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener @Override public void beforeTestMethod(TestContext testContext) throws Exception { - if (Boolean.TRUE.equals(testContext.getAttribute( - DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) { + if (Boolean.TRUE.equals( + testContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) { initMocks(testContext); reinjectFields(testContext); } @@ -76,23 +76,19 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener } private void injectFields(TestContext testContext) { - postProcessFields(testContext, - (mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field, - mockitoField.target, mockitoField.definition)); + postProcessFields(testContext, (mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field, + mockitoField.target, mockitoField.definition)); } private void reinjectFields(final TestContext testContext) { postProcessFields(testContext, (mockitoField, postProcessor) -> { ReflectionUtils.makeAccessible(mockitoField.field); - ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(), - null); - postProcessor.inject(mockitoField.field, mockitoField.target, - mockitoField.definition); + ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(), null); + postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition); }); } - private void postProcessFields(TestContext testContext, - BiConsumer consumer) { + private void postProcessFields(TestContext testContext, BiConsumer consumer) { DefinitionsParser parser = new DefinitionsParser(); parser.parse(testContext.getTestClass()); if (!parser.getDefinitions().isEmpty()) { @@ -101,8 +97,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener for (Definition definition : parser.getDefinitions()) { Field field = parser.getField(definition); if (field != null) { - consumer.accept(new MockitoField(field, testContext.getTestInstance(), - definition), postProcessor); + consumer.accept(new MockitoField(field, testContext.getTestInstance(), definition), postProcessor); } } } @@ -116,8 +111,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener private final Set annotations = new LinkedHashSet<>(); @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation.annotationType().getName().startsWith("org.mockito")) { this.annotations.add(annotation); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java index a5cb92659d6..07aebd1d030 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java @@ -105,8 +105,7 @@ class QualifierDefinition { return true; } MergedAnnotations metaAnnotations = MergedAnnotations.from(type); - return metaAnnotations.isPresent(MockBean.class) - || metaAnnotations.isPresent(SpyBean.class); + return metaAnnotations.isPresent(MockBean.class) || metaAnnotations.isPresent(SpyBean.class); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java index 66b81ec5ea3..27cce2d8663 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ import org.springframework.util.ClassUtils; */ public class ResetMocksTestExecutionListener extends AbstractTestExecutionListener { - private static final boolean MOCKITO_IS_PRESENT = ClassUtils.isPresent( - "org.mockito.MockSettings", + private static final boolean MOCKITO_IS_PRESENT = ClassUtils.isPresent("org.mockito.MockSettings", ResetMocksTestExecutionListener.class.getClassLoader()); @Override @@ -71,12 +70,10 @@ public class ResetMocksTestExecutionListener extends AbstractTestExecutionListen } } - private void resetMocks(ConfigurableApplicationContext applicationContext, - MockReset reset) { + private void resetMocks(ConfigurableApplicationContext applicationContext, MockReset reset) { ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); String[] names = beanFactory.getBeanDefinitionNames(); - Set instantiatedSingletons = new HashSet<>( - Arrays.asList(beanFactory.getSingletonNames())); + Set instantiatedSingletons = new HashSet<>(Arrays.asList(beanFactory.getSingletonNames())); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (definition.isSingleton() && instantiatedSingletons.contains(name)) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java index 5871763b96d..1ede1150390 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ class SpyDefinition extends Definition { private final ResolvableType typeToSpy; - SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset, - boolean proxyTargetAware, QualifierDefinition qualifier) { + SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset, boolean proxyTargetAware, + QualifierDefinition qualifier) { super(name, reset, proxyTargetAware, qualifier); Assert.notNull(typeToSpy, "TypeToSpy must not be null"); this.typeToSpy = typeToSpy; @@ -74,9 +74,8 @@ class SpyDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()) - .append("typeToSpy", this.typeToSpy).append("reset", getReset()) - .toString(); + return new ToStringCreator(this).append("name", getName()).append("typeToSpy", this.typeToSpy) + .append("reset", getReset()).toString(); } public T createSpy(Object instance) { @@ -97,8 +96,7 @@ class SpyDefinition extends Definition { settings.spiedInstance(instance); settings.defaultAnswer(Mockito.CALLS_REAL_METHODS); if (this.isProxyTargetAware()) { - settings.verificationStartedListeners( - new SpringAopBypassingVerificationStartedListener()); + settings.verificationStartedListeners(new SpringAopBypassingVerificationStartedListener()); } return (T) Mockito.mock(instance.getClass(), settings); } @@ -107,8 +105,7 @@ class SpyDefinition extends Definition { * A {@link VerificationStartedListener} that bypasses any proxy created by Spring AOP * when the verification of a spy starts. */ - private static final class SpringAopBypassingVerificationStartedListener - implements VerificationStartedListener { + private static final class SpringAopBypassingVerificationStartedListener implements VerificationStartedListener { @Override public void onVerificationStarted(VerificationStartedEvent event) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java index eb9dc9cb6a7..90b5fc5775a 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,9 +36,8 @@ import org.springframework.mock.web.MockServletContext; */ public class SpringBootMockServletContext extends MockServletContext { - private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] { - "classpath:META-INF/resources", "classpath:resources", "classpath:static", - "classpath:public" }; + private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] { "classpath:META-INF/resources", + "classpath:resources", "classpath:static", "classpath:public" }; private final ResourceLoader resourceLoader; @@ -48,8 +47,7 @@ public class SpringBootMockServletContext extends MockServletContext { this(resourceBasePath, new FileSystemResourceLoader()); } - public SpringBootMockServletContext(String resourceBasePath, - ResourceLoader resourceLoader) { + public SpringBootMockServletContext(String resourceBasePath, ResourceLoader resourceLoader) { super(resourceBasePath, resourceLoader); this.resourceLoader = resourceLoader; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java index 48797579406..d99ea4fc862 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java @@ -147,8 +147,7 @@ class OutputCapture implements CapturedOutput { private final PrintStreamCapture err; - private final List capturedStrings = Collections - .synchronizedList(new ArrayList<>()); + private final List capturedStrings = Collections.synchronizedList(new ArrayList<>()); SystemCapture() { this.out = new PrintStreamCapture(System.out, this::captureOut); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureExtension.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureExtension.java index a5672ee5e29..4138c3908b2 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureExtension.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureExtension.java @@ -54,8 +54,8 @@ import org.junit.jupiter.api.extension.ParameterResolver; * @since 2.2.0 * @see CapturedOutput */ -public class OutputCaptureExtension implements BeforeAllCallback, AfterAllCallback, - BeforeEachCallback, AfterEachCallback, ParameterResolver { +public class OutputCaptureExtension + implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver { private final OutputCapture outputCapture = new OutputCapture(); @@ -84,14 +84,14 @@ public class OutputCaptureExtension implements BeforeAllCallback, AfterAllCallba } @Override - public boolean supportsParameter(ParameterContext parameterContext, - ExtensionContext extensionContext) throws ParameterResolutionException { + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { return CapturedOutput.class.equals(parameterContext.getParameter().getType()); } @Override - public Object resolveParameter(ParameterContext parameterContext, - ExtensionContext extensionContext) throws ParameterResolutionException { + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { return this.outputCapture; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java index 29db81075b2..c2b16356c19 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java @@ -53,8 +53,7 @@ public class OutputCaptureRule implements TestRule { try { if (!OutputCaptureRule.this.matchers.isEmpty()) { String output = OutputCaptureRule.this.delegate.toString(); - Assert.assertThat(output, - allOf(OutputCaptureRule.this.matchers)); + Assert.assertThat(output, allOf(OutputCaptureRule.this.matchers)); } } finally { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/TestPropertyValues.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/TestPropertyValues.java index 45f192419f5..e9ca8b6ede7 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/TestPropertyValues.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/TestPropertyValues.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ import org.springframework.util.StringUtils; */ public final class TestPropertyValues { - private static final TestPropertyValues EMPTY = new TestPropertyValues( - Collections.emptyMap()); + private static final TestPropertyValues EMPTY = new TestPropertyValues(Collections.emptyMap()); private final Map properties; @@ -145,8 +144,7 @@ public final class TestPropertyValues { if (sources.contains(name)) { PropertySource propertySource = sources.get(name); if (propertySource.getClass() == type.getSourceClass()) { - ((Map) propertySource.getSource()) - .putAll(this.properties); + ((Map) propertySource.getSource()).putAll(this.properties); return; } } @@ -300,8 +298,7 @@ public final class TestPropertyValues { private Map apply(Map properties) { Map previous = new LinkedHashMap<>(); - properties.forEach((name, value) -> previous.put(name, - setOrClear(name, (String) value))); + properties.forEach((name, value) -> previous.put(name, setOrClear(name, (String) value))); return previous; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java index 2fbb698a574..052278c1949 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java @@ -34,30 +34,24 @@ import org.springframework.util.ClassUtils; * @author Madhura Bhave * @author Andy Wilkinson */ -class SpringBootTestRandomPortEnvironmentPostProcessor - implements EnvironmentPostProcessor { +class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPostProcessor { private static final String MANAGEMENT_PORT_PROPERTY = "management.server.port"; private static final String SERVER_PORT_PROPERTY = "server.port"; @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MapPropertySource source = (MapPropertySource) environment.getPropertySources() .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); - if (source == null || isTestServerPortFixed(source, environment) - || isTestManagementPortConfigured(source)) { + if (source == null || isTestServerPortFixed(source, environment) || isTestManagementPortConfigured(source)) { return; } - Integer managementPort = getPropertyAsInteger(environment, - MANAGEMENT_PORT_PROPERTY, null); - if (managementPort == null || managementPort.equals(-1) - || managementPort.equals(0)) { + Integer managementPort = getPropertyAsInteger(environment, MANAGEMENT_PORT_PROPERTY, null); + if (managementPort == null || managementPort.equals(-1) || managementPort.equals(0)) { return; } - Integer serverPort = getPropertyAsInteger(environment, SERVER_PORT_PROPERTY, - 8080); + Integer serverPort = getPropertyAsInteger(environment, SERVER_PORT_PROPERTY, 8080); if (!managementPort.equals(serverPort)) { source.getSource().put(MANAGEMENT_PORT_PROPERTY, "0"); } @@ -66,23 +60,19 @@ class SpringBootTestRandomPortEnvironmentPostProcessor } } - private boolean isTestServerPortFixed(MapPropertySource source, - ConfigurableEnvironment environment) { - return !Integer.valueOf(0) - .equals(getPropertyAsInteger(source, SERVER_PORT_PROPERTY, environment)); + private boolean isTestServerPortFixed(MapPropertySource source, ConfigurableEnvironment environment) { + return !Integer.valueOf(0).equals(getPropertyAsInteger(source, SERVER_PORT_PROPERTY, environment)); } private boolean isTestManagementPortConfigured(PropertySource source) { return source.getProperty(MANAGEMENT_PORT_PROPERTY) != null; } - private Integer getPropertyAsInteger(ConfigurableEnvironment environment, - String property, Integer defaultValue) { - return environment.getPropertySources().stream() - .filter((source) -> !source.getName().equals( - TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME)) - .map((source) -> getPropertyAsInteger(source, property, environment)) - .filter(Objects::nonNull).findFirst().orElse(defaultValue); + private Integer getPropertyAsInteger(ConfigurableEnvironment environment, String property, Integer defaultValue) { + return environment.getPropertySources().stream().filter( + (source) -> !source.getName().equals(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME)) + .map((source) -> getPropertyAsInteger(source, property, environment)).filter(Objects::nonNull) + .findFirst().orElse(defaultValue); } private Integer getPropertyAsInteger(PropertySource source, String property, @@ -105,8 +95,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessor } } - private Integer getResolvedValueIfPossible(ConfigurableEnvironment environment, - String value) { + private Integer getResolvedValueIfPossible(ConfigurableEnvironment environment, String value) { String resolvedValue = environment.resolveRequiredPlaceholders(value); return environment.getConversionService().convert(resolvedValue, Integer.class); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandler.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandler.java index 0c8527bed5b..035779d2ec8 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandler.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,7 @@ public class LocalHostUriTemplateHandler extends RootUriTemplateHandler { * @param handler the delegate handler * @since 2.0.3 */ - public LocalHostUriTemplateHandler(Environment environment, String scheme, - UriTemplateHandler handler) { + public LocalHostUriTemplateHandler(Environment environment, String scheme, UriTemplateHandler handler) { super(handler); Assert.notNull(environment, "Environment must not be null"); Assert.notNull(scheme, "Scheme must not be null"); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java index 103b5fd0e15..67aea9ae501 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +65,7 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer this.expectationManager = SimpleRequestExpectationManager.class; } - public MockServerRestTemplateCustomizer( - Class expectationManager) { + public MockServerRestTemplateCustomizer(Class expectationManager) { Assert.notNull(expectationManager, "ExpectationManager must not be null"); this.expectationManager = expectationManager; } @@ -84,11 +83,9 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer public void customize(RestTemplate restTemplate) { RequestExpectationManager expectationManager = createExpectationManager(); if (this.detectRootUri) { - expectationManager = RootUriRequestExpectationManager - .forRestTemplate(restTemplate, expectationManager); + expectationManager = RootUriRequestExpectationManager.forRestTemplate(restTemplate, expectationManager); } - MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate) - .build(expectationManager); + MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build(expectationManager); this.expectationManagers.put(restTemplate, expectationManager); this.servers.put(restTemplate, server); } @@ -98,14 +95,10 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer } public MockRestServiceServer getServer() { - Assert.state(!this.servers.isEmpty(), - "Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to " - + "a RestTemplate"); - Assert.state(this.servers.size() == 1, - "Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to " - + "more than one RestTemplate"); + Assert.state(!this.servers.isEmpty(), "Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to " + "a RestTemplate"); + Assert.state(this.servers.size() == 1, "Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to " + "more than one RestTemplate"); return this.servers.values().iterator().next(); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java index 28820c1551e..8a0bc77985a 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag private final RequestExpectationManager expectationManager; - public RootUriRequestExpectationManager(String rootUri, - RequestExpectationManager expectationManager) { + public RootUriRequestExpectationManager(String rootUri, RequestExpectationManager expectationManager) { Assert.notNull(rootUri, "RootUri must not be null"); Assert.notNull(expectationManager, "ExpectationManager must not be null"); this.rootUri = rootUri; @@ -68,14 +67,12 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag } @Override - public ResponseActions expectRequest(ExpectedCount count, - RequestMatcher requestMatcher) { + public ResponseActions expectRequest(ExpectedCount count, RequestMatcher requestMatcher) { return this.expectationManager.expectRequest(count, requestMatcher); } @Override - public ClientHttpResponse validateRequest(ClientHttpRequest request) - throws IOException { + public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException { String uri = request.getURI().toString(); if (uri.startsWith(this.rootUri)) { request = replaceURI(request, uri.substring(this.rootUri.length())); @@ -87,15 +84,14 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag String message = ex.getMessage(); String prefix = "Request URI expected: new CustomHttpComponentsClientHttpRequestFactory( - httpClientOptions)); + builder = builder + .requestFactory(() -> new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); } } if (username != null || password != null) { @@ -180,8 +178,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error on client-side HTTP error * @see RestTemplate#getForObject(String, Class, Object...) */ - public T getForObject(String url, Class responseType, Object... urlVariables) - throws RestClientException { + public T getForObject(String url, Class responseType, Object... urlVariables) throws RestClientException { return this.restTemplate.getForObject(url, responseType, urlVariables); } @@ -198,8 +195,8 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#getForObject(String, Class, Object...) */ - public T getForObject(String url, Class responseType, - Map urlVariables) throws RestClientException { + public T getForObject(String url, Class responseType, Map urlVariables) + throws RestClientException { return this.restTemplate.getForObject(url, responseType, urlVariables); } @@ -231,8 +228,8 @@ public class TestRestTemplate { * @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, * java.lang.Object[]) */ - public ResponseEntity getForEntity(String url, Class responseType, - Object... urlVariables) throws RestClientException { + public ResponseEntity getForEntity(String url, Class responseType, Object... urlVariables) + throws RestClientException { return this.restTemplate.getForEntity(url, responseType, urlVariables); } @@ -249,8 +246,8 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, java.util.Map) */ - public ResponseEntity getForEntity(String url, Class responseType, - Map urlVariables) throws RestClientException { + public ResponseEntity getForEntity(String url, Class responseType, Map urlVariables) + throws RestClientException { return this.restTemplate.getForEntity(url, responseType, urlVariables); } @@ -264,8 +261,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#getForEntity(java.net.URI, java.lang.Class) */ - public ResponseEntity getForEntity(URI url, Class responseType) - throws RestClientException { + public ResponseEntity getForEntity(URI url, Class responseType) throws RestClientException { return this.restTemplate.getForEntity(applyRootUriIfNecessary(url), responseType); } @@ -279,8 +275,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#headForHeaders(java.lang.String, java.lang.Object[]) */ - public HttpHeaders headForHeaders(String url, Object... urlVariables) - throws RestClientException { + public HttpHeaders headForHeaders(String url, Object... urlVariables) throws RestClientException { return this.restTemplate.headForHeaders(url, urlVariables); } @@ -294,8 +289,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#headForHeaders(java.lang.String, java.util.Map) */ - public HttpHeaders headForHeaders(String url, Map urlVariables) - throws RestClientException { + public HttpHeaders headForHeaders(String url, Map urlVariables) throws RestClientException { return this.restTemplate.headForHeaders(url, urlVariables); } @@ -328,8 +322,7 @@ public class TestRestTemplate { * @see RestTemplate#postForLocation(java.lang.String, java.lang.Object, * java.lang.Object[]) */ - public URI postForLocation(String url, Object request, Object... urlVariables) - throws RestClientException { + public URI postForLocation(String url, Object request, Object... urlVariables) throws RestClientException { return this.restTemplate.postForLocation(url, request, urlVariables); } @@ -351,8 +344,7 @@ public class TestRestTemplate { * @see RestTemplate#postForLocation(java.lang.String, java.lang.Object, * java.util.Map) */ - public URI postForLocation(String url, Object request, Map urlVariables) - throws RestClientException { + public URI postForLocation(String url, Object request, Map urlVariables) throws RestClientException { return this.restTemplate.postForLocation(url, request, urlVariables); } @@ -393,8 +385,8 @@ public class TestRestTemplate { * @see RestTemplate#postForObject(java.lang.String, java.lang.Object, * java.lang.Class, java.lang.Object[]) */ - public T postForObject(String url, Object request, Class responseType, - Object... urlVariables) throws RestClientException { + public T postForObject(String url, Object request, Class responseType, Object... urlVariables) + throws RestClientException { return this.restTemplate.postForObject(url, request, responseType, urlVariables); } @@ -417,8 +409,8 @@ public class TestRestTemplate { * @see RestTemplate#postForObject(java.lang.String, java.lang.Object, * java.lang.Class, java.util.Map) */ - public T postForObject(String url, Object request, Class responseType, - Map urlVariables) throws RestClientException { + public T postForObject(String url, Object request, Class responseType, Map urlVariables) + throws RestClientException { return this.restTemplate.postForObject(url, request, responseType, urlVariables); } @@ -437,10 +429,8 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#postForObject(java.net.URI, java.lang.Object, java.lang.Class) */ - public T postForObject(URI url, Object request, Class responseType) - throws RestClientException { - return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request, - responseType); + public T postForObject(URI url, Object request, Class responseType) throws RestClientException { + return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request, responseType); } /** @@ -462,8 +452,8 @@ public class TestRestTemplate { * @see RestTemplate#postForEntity(java.lang.String, java.lang.Object, * java.lang.Class, java.lang.Object[]) */ - public ResponseEntity postForEntity(String url, Object request, - Class responseType, Object... urlVariables) throws RestClientException { + public ResponseEntity postForEntity(String url, Object request, Class responseType, + Object... urlVariables) throws RestClientException { return this.restTemplate.postForEntity(url, request, responseType, urlVariables); } @@ -486,9 +476,8 @@ public class TestRestTemplate { * @see RestTemplate#postForEntity(java.lang.String, java.lang.Object, * java.lang.Class, java.util.Map) */ - public ResponseEntity postForEntity(String url, Object request, - Class responseType, Map urlVariables) - throws RestClientException { + public ResponseEntity postForEntity(String url, Object request, Class responseType, + Map urlVariables) throws RestClientException { return this.restTemplate.postForEntity(url, request, responseType, urlVariables); } @@ -507,10 +496,9 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#postForEntity(java.net.URI, java.lang.Object, java.lang.Class) */ - public ResponseEntity postForEntity(URI url, Object request, - Class responseType) throws RestClientException { - return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request, - responseType); + public ResponseEntity postForEntity(URI url, Object request, Class responseType) + throws RestClientException { + return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request, responseType); } /** @@ -527,8 +515,7 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#put(java.lang.String, java.lang.Object, java.lang.Object[]) */ - public void put(String url, Object request, Object... urlVariables) - throws RestClientException { + public void put(String url, Object request, Object... urlVariables) throws RestClientException { this.restTemplate.put(url, request, urlVariables); } @@ -546,8 +533,7 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#put(java.lang.String, java.lang.Object, java.util.Map) */ - public void put(String url, Object request, Map urlVariables) - throws RestClientException { + public void put(String url, Object request, Map urlVariables) throws RestClientException { this.restTemplate.put(url, request, urlVariables); } @@ -584,8 +570,8 @@ public class TestRestTemplate { * @since 1.4.4 * @see HttpEntity */ - public T patchForObject(String url, Object request, Class responseType, - Object... uriVariables) throws RestClientException { + public T patchForObject(String url, Object request, Class responseType, Object... uriVariables) + throws RestClientException { return this.restTemplate.patchForObject(url, request, responseType, uriVariables); } @@ -607,8 +593,8 @@ public class TestRestTemplate { * @since 1.4.4 * @see HttpEntity */ - public T patchForObject(String url, Object request, Class responseType, - Map uriVariables) throws RestClientException { + public T patchForObject(String url, Object request, Class responseType, Map uriVariables) + throws RestClientException { return this.restTemplate.patchForObject(url, request, responseType, uriVariables); } @@ -627,10 +613,8 @@ public class TestRestTemplate { * @since 1.4.4 * @see HttpEntity */ - public T patchForObject(URI url, Object request, Class responseType) - throws RestClientException { - return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request, - responseType); + public T patchForObject(URI url, Object request, Class responseType) throws RestClientException { + return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request, responseType); } @@ -656,8 +640,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#delete(java.lang.String, java.util.Map) */ - public void delete(String url, Map urlVariables) - throws RestClientException { + public void delete(String url, Map urlVariables) throws RestClientException { this.restTemplate.delete(url, urlVariables); } @@ -681,8 +664,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#optionsForAllow(java.lang.String, java.lang.Object[]) */ - public Set optionsForAllow(String url, Object... urlVariables) - throws RestClientException { + public Set optionsForAllow(String url, Object... urlVariables) throws RestClientException { return this.restTemplate.optionsForAllow(url, urlVariables); } @@ -696,8 +678,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#optionsForAllow(java.lang.String, java.util.Map) */ - public Set optionsForAllow(String url, Map urlVariables) - throws RestClientException { + public Set optionsForAllow(String url, Map urlVariables) throws RestClientException { return this.restTemplate.optionsForAllow(url, urlVariables); } @@ -729,11 +710,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, * org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object[]) */ - public ResponseEntity exchange(String url, HttpMethod method, - HttpEntity requestEntity, Class responseType, Object... urlVariables) - throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public ResponseEntity exchange(String url, HttpMethod method, HttpEntity requestEntity, + Class responseType, Object... urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -753,11 +732,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, * org.springframework.http.HttpEntity, java.lang.Class, java.util.Map) */ - public ResponseEntity exchange(String url, HttpMethod method, - HttpEntity requestEntity, Class responseType, - Map urlVariables) throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public ResponseEntity exchange(String url, HttpMethod method, HttpEntity requestEntity, + Class responseType, Map urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -774,11 +751,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod, * org.springframework.http.HttpEntity, java.lang.Class) */ - public ResponseEntity exchange(URI url, HttpMethod method, - HttpEntity requestEntity, Class responseType) - throws RestClientException { - return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, - requestEntity, responseType); + public ResponseEntity exchange(URI url, HttpMethod method, HttpEntity requestEntity, + Class responseType) throws RestClientException { + return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType); } /** @@ -802,11 +777,9 @@ public class TestRestTemplate { * org.springframework.http.HttpEntity, * org.springframework.core.ParameterizedTypeReference, java.lang.Object[]) */ - public ResponseEntity exchange(String url, HttpMethod method, - HttpEntity requestEntity, ParameterizedTypeReference responseType, - Object... urlVariables) throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public ResponseEntity exchange(String url, HttpMethod method, HttpEntity requestEntity, + ParameterizedTypeReference responseType, Object... urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -830,11 +803,9 @@ public class TestRestTemplate { * org.springframework.http.HttpEntity, * org.springframework.core.ParameterizedTypeReference, java.util.Map) */ - public ResponseEntity exchange(String url, HttpMethod method, - HttpEntity requestEntity, ParameterizedTypeReference responseType, - Map urlVariables) throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public ResponseEntity exchange(String url, HttpMethod method, HttpEntity requestEntity, + ParameterizedTypeReference responseType, Map urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -857,11 +828,9 @@ public class TestRestTemplate { * org.springframework.http.HttpEntity, * org.springframework.core.ParameterizedTypeReference) */ - public ResponseEntity exchange(URI url, HttpMethod method, - HttpEntity requestEntity, ParameterizedTypeReference responseType) - throws RestClientException { - return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, - requestEntity, responseType); + public ResponseEntity exchange(URI url, HttpMethod method, HttpEntity requestEntity, + ParameterizedTypeReference responseType) throws RestClientException { + return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType); } /** @@ -879,10 +848,9 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#exchange(org.springframework.http.RequestEntity, java.lang.Class) */ - public ResponseEntity exchange(RequestEntity requestEntity, - Class responseType) throws RestClientException { - return this.restTemplate.exchange( - createRequestEntityWithRootAppliedUri(requestEntity), responseType); + public ResponseEntity exchange(RequestEntity requestEntity, Class responseType) + throws RestClientException { + return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType); } /** @@ -902,10 +870,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(org.springframework.http.RequestEntity, * org.springframework.core.ParameterizedTypeReference) */ - public ResponseEntity exchange(RequestEntity requestEntity, - ParameterizedTypeReference responseType) throws RestClientException { - return this.restTemplate.exchange( - createRequestEntityWithRootAppliedUri(requestEntity), responseType); + public ResponseEntity exchange(RequestEntity requestEntity, ParameterizedTypeReference responseType) + throws RestClientException { + return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType); } /** @@ -926,10 +893,8 @@ public class TestRestTemplate { * org.springframework.web.client.ResponseExtractor, java.lang.Object[]) */ public T execute(String url, HttpMethod method, RequestCallback requestCallback, - ResponseExtractor responseExtractor, Object... urlVariables) - throws RestClientException { - return this.restTemplate.execute(url, method, requestCallback, responseExtractor, - urlVariables); + ResponseExtractor responseExtractor, Object... urlVariables) throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables); } /** @@ -950,10 +915,8 @@ public class TestRestTemplate { * org.springframework.web.client.ResponseExtractor, java.util.Map) */ public T execute(String url, HttpMethod method, RequestCallback requestCallback, - ResponseExtractor responseExtractor, Map urlVariables) - throws RestClientException { - return this.restTemplate.execute(url, method, requestCallback, responseExtractor, - urlVariables); + ResponseExtractor responseExtractor, Map urlVariables) throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables); } /** @@ -972,8 +935,7 @@ public class TestRestTemplate { */ public T execute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor responseExtractor) throws RestClientException { - return this.restTemplate.execute(applyRootUriIfNecessary(url), method, - requestCallback, responseExtractor); + return this.restTemplate.execute(applyRootUriIfNecessary(url), method, requestCallback, responseExtractor); } /** @@ -996,26 +958,21 @@ public class TestRestTemplate { * @since 1.4.1 */ public TestRestTemplate withBasicAuth(String username, String password) { - TestRestTemplate template = new TestRestTemplate(this.builder, username, password, - this.httpClientOptions); + TestRestTemplate template = new TestRestTemplate(this.builder, username, password, this.httpClientOptions); template.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler()); return template; } @SuppressWarnings({ "rawtypes", "unchecked" }) - private RequestEntity createRequestEntityWithRootAppliedUri( - RequestEntity requestEntity) { - return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), - requestEntity.getMethod(), + private RequestEntity createRequestEntityWithRootAppliedUri(RequestEntity requestEntity) { + return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), requestEntity.getMethod(), applyRootUriIfNecessary(requestEntity.getUrl()), requestEntity.getType()); } private URI applyRootUriIfNecessary(URI uri) { UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler(); - if ((uriTemplateHandler instanceof RootUriTemplateHandler) - && uri.toString().startsWith("/")) { - return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() - + uri.toString()); + if ((uriTemplateHandler instanceof RootUriTemplateHandler) && uri.toString().startsWith("/")) { + return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() + uri.toString()); } return uri; } @@ -1045,19 +1002,16 @@ public class TestRestTemplate { /** * {@link HttpComponentsClientHttpRequestFactory} to apply customizations. */ - protected static class CustomHttpComponentsClientHttpRequestFactory - extends HttpComponentsClientHttpRequestFactory { + protected static class CustomHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory { private final String cookieSpec; private final boolean enableRedirects; - public CustomHttpComponentsClientHttpRequestFactory( - HttpClientOption[] httpClientOptions) { - Set options = new HashSet<>( - Arrays.asList(httpClientOptions)); - this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) - ? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES); + public CustomHttpComponentsClientHttpRequestFactory(HttpClientOption[] httpClientOptions) { + Set options = new HashSet<>(Arrays.asList(httpClientOptions)); + this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) ? CookieSpecs.STANDARD + : CookieSpecs.IGNORE_COOKIES); this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS); if (options.contains(HttpClientOption.SSL)) { setHttpClient(createSslHttpClient()); @@ -1067,9 +1021,7 @@ public class TestRestTemplate { private HttpClient createSslHttpClient() { try { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .build()); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); return HttpClients.custom().setSSLSocketFactory(socketFactory).build(); } catch (Exception ex) { @@ -1085,8 +1037,7 @@ public class TestRestTemplate { } protected RequestConfig getRequestConfig() { - Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec) - .setAuthenticationEnabled(false) + Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec).setAuthenticationEnabled(false) .setRedirectsEnabled(this.enableRedirects); return builder.build(); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java index 8c97bb2a3e2..bdd796624f1 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java @@ -56,8 +56,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { MergedAnnotation annotation = MergedAnnotations - .from(mergedContextConfiguration.getTestClass(), - SearchStrategy.INHERITED_ANNOTATIONS) + .from(mergedContextConfiguration.getTestClass(), SearchStrategy.INHERITED_ANNOTATIONS) .get(SpringBootTest.class); if (annotation.getEnum("webEnvironment", WebEnvironment.class).isEmbedded()) { registerTestRestTemplate(context); @@ -72,11 +71,9 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { } private void registerTestRestTemplate(BeanDefinitionRegistry registry) { - RootBeanDefinition definition = new RootBeanDefinition( - TestRestTemplateRegistrar.class); + RootBeanDefinition definition = new RootBeanDefinition(TestRestTemplateRegistrar.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - registry.registerBeanDefinition(TestRestTemplateRegistrar.class.getName(), - definition); + registry.registerBeanDefinition(TestRestTemplateRegistrar.class.getName(), definition); } @Override @@ -113,11 +110,9 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { - if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory) this.beanFactory, TestRestTemplate.class, false, - false).length == 0) { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { + if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory, + TestRestTemplate.class, false, false).length == 0) { registry.registerBeanDefinition(TestRestTemplate.class.getName(), new RootBeanDefinition(TestRestTemplateFactory.class)); } @@ -125,8 +120,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } @@ -134,8 +128,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { /** * {@link FactoryBean} used to create and configure a {@link TestRestTemplate}. */ - public static class TestRestTemplateFactory - implements FactoryBean, ApplicationContextAware { + public static class TestRestTemplateFactory implements FactoryBean, ApplicationContextAware { private static final HttpClientOption[] DEFAULT_OPTIONS = {}; @@ -144,14 +137,13 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { private TestRestTemplate template; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { RestTemplateBuilder builder = getRestTemplateBuilder(applicationContext); boolean sslEnabled = isSslEnabled(applicationContext); TestRestTemplate template = new TestRestTemplate(builder, null, null, sslEnabled ? SSL_OPTIONS : DEFAULT_OPTIONS); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - applicationContext.getEnvironment(), sslEnabled ? "https" : "http"); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(applicationContext.getEnvironment(), + sslEnabled ? "https" : "http"); template.setUriTemplateHandler(handler); this.template = template; } @@ -160,16 +152,14 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { try { AbstractServletWebServerFactory webServerFactory = context .getBean(AbstractServletWebServerFactory.class); - return webServerFactory.getSsl() != null - && webServerFactory.getSsl().isEnabled(); + return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { return false; } } - private RestTemplateBuilder getRestTemplateBuilder( - ApplicationContext applicationContext) { + private RestTemplateBuilder getRestTemplateBuilder(ApplicationContext applicationContext) { try { return applicationContext.getBean(RestTemplateBuilder.class); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerFactory.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerFactory.java index f626d122758..72734023760 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerFactory.java @@ -36,8 +36,7 @@ class TestRestTemplateContextCustomizerFactory implements ContextCustomizerFacto @Override public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { - MergedAnnotations annotations = MergedAnnotations.from(testClass, - SearchStrategy.INHERITED_ANNOTATIONS); + MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS); if (annotations.isPresent(SpringBootTest.class)) { return new TestRestTemplateContextCustomizer(); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java index fdbdcfaa32c..f38c8ade792 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,22 +39,19 @@ public class LocalHostWebConnectionHtmlUnitDriver extends WebConnectionHtmlUnitD this.environment = environment; } - public LocalHostWebConnectionHtmlUnitDriver(Environment environment, - boolean enableJavascript) { + public LocalHostWebConnectionHtmlUnitDriver(Environment environment, boolean enableJavascript) { super(enableJavascript); Assert.notNull(environment, "Environment must not be null"); this.environment = environment; } - public LocalHostWebConnectionHtmlUnitDriver(Environment environment, - BrowserVersion browserVersion) { + public LocalHostWebConnectionHtmlUnitDriver(Environment environment, BrowserVersion browserVersion) { super(browserVersion); Assert.notNull(environment, "Environment must not be null"); this.environment = environment; } - public LocalHostWebConnectionHtmlUnitDriver(Environment environment, - Capabilities capabilities) { + public LocalHostWebConnectionHtmlUnitDriver(Environment environment, Capabilities capabilities) { super(capabilities); Assert.notNull(environment, "Environment must not be null"); this.environment = environment; diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java index 2f73b6585f5..9d63e0973bd 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java @@ -56,11 +56,9 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies; class WebTestClientContextCustomizer implements ContextCustomizer { @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { MergedAnnotation annotation = MergedAnnotations - .from(mergedConfig.getTestClass(), SearchStrategy.INHERITED_ANNOTATIONS) - .get(SpringBootTest.class); + .from(mergedConfig.getTestClass(), SearchStrategy.INHERITED_ANNOTATIONS).get(SpringBootTest.class); if (annotation.getEnum("webEnvironment", WebEnvironment.class).isEmbedded()) { registerWebTestClient(context); } @@ -74,11 +72,9 @@ class WebTestClientContextCustomizer implements ContextCustomizer { } private void registerWebTestClient(BeanDefinitionRegistry registry) { - RootBeanDefinition definition = new RootBeanDefinition( - WebTestClientRegistrar.class); + RootBeanDefinition definition = new RootBeanDefinition(WebTestClientRegistrar.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - registry.registerBeanDefinition(WebTestClientRegistrar.class.getName(), - definition); + registry.registerBeanDefinition(WebTestClientRegistrar.class.getName(), definition); } @Override @@ -112,11 +108,9 @@ class WebTestClientContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { - if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory) this.beanFactory, WebTestClient.class, false, - false).length == 0) { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { + if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory, + WebTestClient.class, false, false).length == 0) { registry.registerBeanDefinition(WebTestClient.class.getName(), new RootBeanDefinition(WebTestClientFactory.class)); } @@ -124,8 +118,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } @@ -133,16 +126,14 @@ class WebTestClientContextCustomizer implements ContextCustomizer { /** * {@link FactoryBean} used to create and configure a {@link WebTestClient}. */ - public static class WebTestClientFactory - implements FactoryBean, ApplicationContextAware { + public static class WebTestClientFactory implements FactoryBean, ApplicationContextAware { private ApplicationContext applicationContext; private WebTestClient object; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -166,8 +157,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private WebTestClient createWebTestClient() { boolean sslEnabled = isSslEnabled(this.applicationContext); - String port = this.applicationContext.getEnvironment() - .getProperty("local.server.port", "8080"); + String port = this.applicationContext.getEnvironment().getProperty("local.server.port", "8080"); String baseUrl = (sslEnabled ? "https" : "http") + "://localhost:" + port; WebTestClient.Builder builder = WebTestClient.bindToServer(); customizeWebTestClientCodecs(builder, this.applicationContext); @@ -178,22 +168,18 @@ class WebTestClientContextCustomizer implements ContextCustomizer { try { AbstractReactiveWebServerFactory webServerFactory = context .getBean(AbstractReactiveWebServerFactory.class); - return webServerFactory.getSsl() != null - && webServerFactory.getSsl().isEnabled(); + return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { return false; } } - private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, - ApplicationContext context) { - Collection codecCustomizers = context - .getBeansOfType(CodecCustomizer.class).values(); + private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, ApplicationContext context) { + Collection codecCustomizers = context.getBeansOfType(CodecCustomizer.class).values(); if (!CollectionUtils.isEmpty(codecCustomizers)) { - clientBuilder.exchangeStrategies(ExchangeStrategies.builder() - .codecs((codecs) -> codecCustomizers.forEach( - (codecCustomizer) -> codecCustomizer.customize(codecs))) + clientBuilder.exchangeStrategies(ExchangeStrategies.builder().codecs( + (codecs) -> codecCustomizers.forEach((codecCustomizer) -> codecCustomizer.customize(codecs))) .build()); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java index a39ff774180..8bb872104a6 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java @@ -38,8 +38,7 @@ class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory @Override public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { - MergedAnnotations annotations = MergedAnnotations.from(testClass, - SearchStrategy.INHERITED_ANNOTATIONS); + MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS); if (isWebClientPresent() && annotations.isPresent(SpringBootTest.class)) { return new WebTestClientContextCustomizer(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java index 39a2757d584..c36d5d93850 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java @@ -66,15 +66,13 @@ public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests @Test public void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); - WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build() - .get().uri("/").exchange().expectBody(String.class) - .isEqualTo("Hello World"); + WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build().get().uri("/").exchange() + .expectBody(String.class).isEqualTo("Hello World"); } @Test public void injectWebTestClient() { - this.webClient.get().uri("/").exchange().expectBody(String.class) - .isEqualTo("Hello World"); + this.webClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("Hello World"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java index ff86b5e7d92..8b529972084 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java @@ -71,8 +71,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests { @Test public void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); - String body = new RestTemplate() - .getForObject("http://localhost:" + this.port + "/", String.class); + String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class); assertThat(body).isEqualTo("Hello World"); } @@ -89,8 +88,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests { @Test public void validateWebApplicationContextIsSet() { - assertThat(this.context).isSameAs( - WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); + assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } protected abstract static class AbstractConfig { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java index a45069855e5..6365bdf7984 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java @@ -32,20 +32,17 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException */ public class AnnotatedClassFinderTests { - private AnnotatedClassFinder finder = new AnnotatedClassFinder( - SpringBootConfiguration.class); + private AnnotatedClassFinder finder = new AnnotatedClassFinder(SpringBootConfiguration.class); @Test public void findFromClassWhenSourceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.finder.findFromClass((Class) null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromClass((Class) null)) .withMessageContaining("Source must not be null"); } @Test public void findFromPackageWhenSourceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.finder.findFromPackage((String) null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromPackage((String) null)) .withMessageContaining("Source must not be null"); } @@ -63,8 +60,7 @@ public class AnnotatedClassFinderTests { @Test public void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() { - Class config = this.finder - .findFromPackage("org.springframework.boot.test.context.example.scan"); + Class config = this.finder.findFromPackage("org.springframework.boot.test.context.example.scan"); assertThat(config).isEqualTo(ExampleConfig.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java index 8328ed37254..8d15d4dd135 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java @@ -39,8 +39,7 @@ public class FilteredClassLoaderTests { "org/springframework/boot/test/context/FilteredClassLoaderTestsResource.txt"); @Test - public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() - throws Exception { + public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader( FilteredClassLoaderTests.class.getPackage().getName())) { assertThatExceptionOfType(ClassNotFoundException.class) @@ -50,8 +49,7 @@ public class FilteredClassLoaderTests { @Test public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { - try (FilteredClassLoader classLoader = new FilteredClassLoader( - FilteredClassLoaderTests.class)) { + try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) { assertThatExceptionOfType(ClassNotFoundException.class) .isThrownBy(() -> classLoader.loadClass(getClass().getName())); } @@ -66,8 +64,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourceWhenFilteredOnResourceShouldReturnNotFound() - throws Exception { + public void loadResourceWhenFilteredOnResourceShouldReturnNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) { final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath()); assertThat(loaded).isNull(); @@ -76,49 +73,40 @@ public class FilteredClassLoaderTests { @Test public void loadResourceWhenNotFilteredShouldLoadResource() throws Exception { - try (FilteredClassLoader classLoader = new FilteredClassLoader( - (resourceName) -> false)) { + try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) { final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath()); assertThat(loaded).isNotNull(); } } @Test - public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound() - throws Exception { + public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) { - final Enumeration loaded = classLoader - .getResources(TEST_RESOURCE.getPath()); + final Enumeration loaded = classLoader.getResources(TEST_RESOURCE.getPath()); assertThat(loaded.hasMoreElements()).isFalse(); } } @Test public void loadResourcesWhenNotFilteredShouldLoadResource() throws Exception { - try (FilteredClassLoader classLoader = new FilteredClassLoader( - (resourceName) -> false)) { - final Enumeration loaded = classLoader - .getResources(TEST_RESOURCE.getPath()); + try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) { + final Enumeration loaded = classLoader.getResources(TEST_RESOURCE.getPath()); assertThat(loaded.hasMoreElements()).isTrue(); } } @Test - public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound() - throws Exception { + public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) { - final InputStream loaded = classLoader - .getResourceAsStream(TEST_RESOURCE.getPath()); + final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath()); assertThat(loaded).isNull(); } } @Test public void loadResourceAsStreamWhenNotFilteredShouldLoadResource() throws Exception { - try (FilteredClassLoader classLoader = new FilteredClassLoader( - (resourceName) -> false)) { - final InputStream loaded = classLoader - .getResourceAsStream(TEST_RESOURCE.getPath()); + try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) { + final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath()); assertThat(loaded).isNotNull(); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java index b5ccb9e8667..e31b7e537fe 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java @@ -45,54 +45,45 @@ public class ImportsContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithNoImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithNoImport.class, null); assertThat(customizer).isNull(); } @Test public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithMetaImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithMetaImport.class, null); assertThat(customizer).isNotNull(); } @Test public void contextCustomizerEqualsAndHashCode() { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(TestWithImport.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(TestWithImport.class, null); - ContextCustomizer customizer3 = this.factory - .createContextCustomizer(TestWithImportAndMetaImport.class, null); - ContextCustomizer customizer4 = this.factory - .createContextCustomizer(TestWithSameImportAndMetaImport.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer3 = this.factory.createContextCustomizer(TestWithImportAndMetaImport.class, null); + ContextCustomizer customizer4 = this.factory.createContextCustomizer(TestWithSameImportAndMetaImport.class, + null); assertThat(customizer1.hashCode()).isEqualTo(customizer1.hashCode()); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); - assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2) - .isNotEqualTo(customizer3); + assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); assertThat(customizer3).isEqualTo(customizer4); } @Test public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> this.factory - .createContextCustomizer(TestWithImportAndBeanMethod.class, null)) + .isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null)) .withMessageContaining("Test classes cannot include @Bean methods"); } @Test public void contextCustomizerImportsBeans() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, mock(MergedContextConfiguration.class)); context.refresh(); @@ -101,8 +92,8 @@ public class ImportsContextCustomizerFactoryTests { @Test public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { - assertThat(this.factory.createContextCustomizer( - TestWithImportAndSelfAnnotatingAnnotation.class, null)).isNotNull(); + assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null)) + .isNotNull(); } static class TestWithNoImport { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java index 7b91fa60202..f43c50dc13c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java @@ -45,38 +45,31 @@ public class ImportsContextCustomizerTests { @Test public void importSelectorsCouldUseAnyAnnotations() { assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class)) - .isNotEqualTo(new ImportsContextCustomizer( - SecondImportSelectorAnnotatedClass.class)); + .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); } @Test public void determinableImportSelector() { - assertThat(new ImportsContextCustomizer( - FirstDeterminableImportSelectorAnnotatedClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondDeterminableImportSelectorAnnotatedClass.class)); + assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class)) + .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); } @Test public void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() { assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondKotlinAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); } @Test public void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() { - assertThat( - new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondSpockFrameworkAnnotatedTestClass.class)); + assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) + .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); } @Test public void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondSpockLangAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); } @Import(TestImportSelector.class) @@ -152,8 +145,7 @@ public class ImportsContextCustomizerTests { } - static class TestDeterminableImportSelector - implements ImportSelector, DeterminableImports { + static class TestDeterminableImportSelector implements ImportSelector, DeterminableImports { @Override public String[] selectImports(AnnotationMetadata arg0) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java index 318276a9099..ea12624ae86 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java @@ -67,14 +67,12 @@ public class SpringBootContextLoaderMockMvcTests { @Test public void testMockHttpEndpoint() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Hello World")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World")); } @Test public void validateWebApplicationContextIsSet() { - assertThat(this.context).isSameAs( - WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); + assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java index 534ce512755..cccd2a3691c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java @@ -74,8 +74,7 @@ public class SpringBootContextLoaderTests { @Test public void environmentPropertiesAnotherSeparatorInValue() { - Map config = getEnvironmentProperties( - AnotherSeparatorInValue.class); + Map config = getEnvironmentProperties(AnotherSeparatorInValue.class); assertKey(config, "key", "my:Value"); assertKey(config, "anotherKey", "another=Value"); } @@ -90,12 +89,10 @@ public class SpringBootContextLoaderTests { } private Map getEnvironmentProperties(Class testClass) { - TestContext context = new ExposedTestContextManager(testClass) - .getExposedTestContext(); - MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils - .getField(context, "mergedContextConfiguration"); - return TestPropertySourceUtils - .convertInlinedPropertiesToMap(config.getPropertySourceProperties()); + TestContext context = new ExposedTestContextManager(testClass).getExposedTestContext(); + MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils.getField(context, + "mergedContextConfiguration"); + return TestPropertySourceUtils.convertInlinedPropertiesToMap(config.getPropertySourceProperties()); } private void assertKey(Map actual, String key, Object value) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java index 5b958945d2d..f6251bd130b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java @@ -41,8 +41,7 @@ public class SpringBootTestActiveProfileTests { @Test public void profiles() { - assertThat(this.context.getEnvironment().getActiveProfiles()) - .containsExactly("override"); + assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java index d27b6d47401..c8a0d8c469a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java @@ -40,8 +40,7 @@ public class SpringBootTestArgsTests { public void applicationArgumentsPopulated() { assertThat(this.args.getOptionNames()).containsOnly("option.foo"); assertThat(this.args.getOptionValues("option.foo")).containsOnly("foo-value"); - assertThat(this.args.getNonOptionArgs()) - .containsOnly("other.bar=other-bar-value"); + assertThat(this.args.getNonOptionArgs()).containsOnly("other.bar=other-bar-value"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentDefinedPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentDefinedPortTests.java index a858c95a3c3..29faa7ebe9b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentDefinedPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentDefinedPortTests.java @@ -29,8 +29,8 @@ import org.springframework.web.reactive.config.EnableWebFlux; * @author Stephane Nicoll */ @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { - "spring.main.web-application-type=reactive", "server.port=0", "value=123" }) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, + properties = { "spring.main.web-application-type=reactive", "server.port=0", "value=123" }) public class SpringBootTestReactiveWebEnvironmentDefinedPortTests extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java index fadc5fac45c..679747ec6cf 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java @@ -42,8 +42,7 @@ public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTest @Test public void restTemplateIsUserDefined() { - assertThat(getContext().getBean("testRestTemplate")) - .isInstanceOf(RestTemplate.class); + assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java index 0fe61e2551a..421d3907b98 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java @@ -37,13 +37,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestUserDefinedTestRestTemplateTests - extends AbstractSpringBootTestWebServerWebEnvironmentTests { +public class SpringBootTestUserDefinedTestRestTemplateTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { @Test public void restTemplateIsUserDefined() { - assertThat(getContext().getBean("testRestTemplate")) - .isInstanceOf(RestTemplate.class); + assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class); } // gh-7711 diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java index 260aa8fe374..f5b4ee494be 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java @@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, - properties = { "server.port=0", "value=123" }) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" }) @ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class), @ContextConfiguration(classes = ChildConfiguration.class) }) public class SpringBootTestWebEnvironmentContextHierarchyTests { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java index f30dc955be2..1cbb3c3f4b6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java @@ -30,10 +30,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; * @author Andy Wilkinson */ @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, - properties = { "server.port=0", "value=123" }) -public class SpringBootTestWebEnvironmentDefinedPortTests - extends AbstractSpringBootTestWebServerWebEnvironmentTests { +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" }) +public class SpringBootTestWebEnvironmentDefinedPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { @Configuration(proxyBeanMethods = false) @EnableWebMvc diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java index 03b86c194e7..c9de8d0b648 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java @@ -75,8 +75,7 @@ public class SpringBootTestWebEnvironmentMockTests { @Test public void resourcePath() { - assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", - "src/main/webapp"); + assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/main/webapp"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java index 3086b79118f..d0cda0129ab 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java @@ -48,8 +48,7 @@ public class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests { @Test public void resourcePath() { - assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", - "src/mymain/mywebapp"); + assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/mymain/mywebapp"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java index 5f19ede5993..f81d0329f51 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java @@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "server.port=12345" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.port=12345" }) public class SpringBootTestWebEnvironmentRandomPortCustomPortTests { @Autowired diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java index 4e2280e8c7c..2b326609ca1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestWebEnvironmentRandomPortTests - extends AbstractSpringBootTestWebServerWebEnvironmentTests { +public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { @Test public void testRestTemplateShouldUseBuilder() { @@ -54,8 +53,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests @Bean public RestTemplateBuilder restTemplateBuilder() { - return new RestTemplateBuilder() - .additionalMessageConverters(new MyConverter()); + return new RestTemplateBuilder().additionalMessageConverters(new MyConverter()); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java index a08988699a0..446a1d2d030 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java @@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ @DirtiesContext @SpringBootTest -@ContextConfiguration( - classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) +@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) public class SpringBootTestWithContextConfigurationIntegrationTests { @Autowired diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java index a4735a0a281..20945e3e1c1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java @@ -37,11 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = { - "boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" }) +@SpringBootTest(webEnvironment = WebEnvironment.NONE, + properties = { "boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" }) @TestPropertySource( - properties = { "property-source-inlined=bar", "a=property-source-inlined", - "c=property-source-inlined" }, + properties = { "property-source-inlined=bar", "a=property-source-inlined", "c=property-source-inlined" }, locations = "classpath:/test-property-source-annotation.properties") public class SpringBootTestWithTestPropertySourceTests { @@ -71,14 +70,12 @@ public class SpringBootTestWithTestPropertySourceTests { @Test public void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() { - assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation) - .isEqualTo("boot-test-inlined"); + assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation).isEqualTo("boot-test-inlined"); } @Test public void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() { - assertThat(this.config.propertySourceInlinedOverridesBootTestInlined) - .isEqualTo("property-source-inlined"); + assertThat(this.config.propertySourceInlinedOverridesBootTestInlined).isEqualTo("property-source-inlined"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java index 7209900ba9a..f7c17ea6d84 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java @@ -61,51 +61,44 @@ public class ApplicationContextAssertProviderTests { @Test public void getWhenTypeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get(null, - ApplicationContext.class, this.mockContextSupplier)) + assertThatIllegalArgumentException().isThrownBy( + () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("Type must not be null"); } @Test public void getWhenTypeIsClassShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get(null, - ApplicationContext.class, this.mockContextSupplier)) + assertThatIllegalArgumentException().isThrownBy( + () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("Type must not be null"); } @Test public void getWhenContextTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get( - TestAssertProviderApplicationContextClass.class, + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("Type must be an interface"); } @Test public void getWhenContextTypeIsClassShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get( - TestAssertProviderApplicationContext.class, null, - this.mockContextSupplier)) + assertThatIllegalArgumentException().isThrownBy(() -> ApplicationContextAssertProvider + .get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier)) .withMessageContaining("ContextType must not be null"); } @Test public void getWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get( - TestAssertProviderApplicationContext.class, + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, StaticApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("ContextType must be an interface"); } @Test public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat((Object) context).isNotNull(); context.getBean("foo"); verify(this.mockContext).getBean("foo"); @@ -113,63 +106,54 @@ public class ApplicationContextAssertProviderTests { @Test public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat((Object) context).isNotNull(); - assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")) - .withCause(this.startupFailure).withMessageContaining("failed to start"); + assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")).withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test public void getSourceContextWhenContextStartsShouldReturnSourceContext() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext); } @Test public void getSourceContextWhenContextFailsShouldThrowException() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext) .withCause(this.startupFailure).withMessageContaining("failed to start"); } @Test public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); - assertThat(context.getSourceApplicationContext(ApplicationContext.class)) - .isSameAs(this.mockContext); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); + assertThat(context.getSourceApplicationContext(ApplicationContext.class)).isSameAs(this.mockContext); } @Test public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); - assertThatIllegalStateException().isThrownBy( - () -> context.getSourceApplicationContext(ApplicationContext.class)) + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); + assertThatIllegalStateException() + .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) .withCause(this.startupFailure).withMessageContaining("failed to start"); } @Test public void getStartupFailureWhenContextStartsShouldReturnNull() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.getStartupFailure()).isNull(); } @Test public void getStartupFailureWhenContextFailsToStartShouldReturnException() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure); } @Test public void assertThatWhenContextStartsShouldReturnAssertions() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); ApplicationContextAssert contextAssert = assertThat(context); assertThat(contextAssert.getApplicationContext()).isSameAs(context); assertThat(contextAssert.getStartupFailure()).isNull(); @@ -177,8 +161,7 @@ public class ApplicationContextAssertProviderTests { @Test public void assertThatWhenContextFailsShouldReturnAssertions() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); ApplicationContextAssert contextAssert = assertThat(context); assertThat(contextAssert.getApplicationContext()).isSameAs(context); assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure); @@ -186,37 +169,28 @@ public class ApplicationContextAssertProviderTests { @Test public void toStringWhenContextStartsShouldReturnSimpleString() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); - assertThat(context.toString()) - .startsWith( - "Started application [ConfigurableApplicationContext.MockitoMock") - .endsWith( - "id = [null], applicationName = [null], beanDefinitionCount = 0]"); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); + assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock") + .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); } @Test public void toStringWhenContextFailsToStartShouldReturnSimpleString() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat(context.toString()).isEqualTo("Unstarted application context " - + "org.springframework.context.ApplicationContext" - + "[startupFailure=java.lang.RuntimeException]"); + + "org.springframework.context.ApplicationContext" + "[startupFailure=java.lang.RuntimeException]"); } @Test public void closeShouldCloseContext() { - ApplicationContextAssertProvider context = get( - this.mockContextSupplier); + ApplicationContextAssertProvider context = get(this.mockContextSupplier); context.close(); verify(this.mockContext).close(); } - private ApplicationContextAssertProvider get( - Supplier contextSupplier) { - return ApplicationContextAssertProvider.get( - TestAssertProviderApplicationContext.class, ApplicationContext.class, - contextSupplier); + private ApplicationContextAssertProvider get(Supplier contextSupplier) { + return ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, + ApplicationContext.class, contextSupplier); } private interface TestAssertProviderApplicationContext diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java index ef1c70e875d..f980e299f94 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java @@ -61,15 +61,13 @@ public class ApplicationContextAssertTests { @Test public void createWhenApplicationContextIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ApplicationContextAssert<>(null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContextAssert<>(null, null)) .withMessageContaining("ApplicationContext must not be null"); } @Test public void createWhenHasApplicationContextShouldSetActual() { - assertThat(getAssert(this.context).getSourceApplicationContext()) - .isSameAs(this.context); + assertThat(getAssert(this.context).getSourceApplicationContext()).isSameAs(this.context); } @Test @@ -94,8 +92,7 @@ public class ApplicationContextAssertTests { public void hasBeanWhenNotStartedShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -106,8 +103,8 @@ public class ApplicationContextAssertTests { @Test public void hasSingleBeanWhenHasNoBeansShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) .withMessageContaining("to have a single bean of type"); } @@ -115,26 +112,25 @@ public class ApplicationContextAssertTests { public void hasSingleBeanWhenHasMultipleShouldFail() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) .withMessageContaining("but found:"); } @Test public void hasSingleBeanWhenFailedToStartShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) .withMessageContaining("to have a single bean of type") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test public void hasSingleBeanWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) .withMessageContaining("but found:"); } @@ -153,33 +149,31 @@ public class ApplicationContextAssertTests { @Test public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) .withMessageContaining("but found"); } @Test public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) .withMessageContaining("not to have any beans of type") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test public void doesNotHaveBeanOfTypeWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) .withMessageContaining("but found"); } @Test public void doesNotHaveBeanOfTypeWithLimitedScopeWhenInParentShouldPass() { this.parent.registerSingleton("foo", Foo.class); - assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class, - Scope.NO_ANCESTORS); + assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class, Scope.NO_ANCESTORS); } @Test @@ -191,26 +185,22 @@ public class ApplicationContextAssertTests { public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy( - () -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) .withMessageContaining("but found"); } @Test public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy( - () -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) - .withMessageContaining("not to have any beans of name") - .withMessageContaining("failed to start"); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name").withMessageContaining("failed to start"); } @Test public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo", - "bar"); + assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo", "bar"); } @Test @@ -221,11 +211,9 @@ public class ApplicationContextAssertTests { @Test public void getBeanNamesWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy( - () -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) .withMessageContaining("not to have any beans of name") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -250,8 +238,7 @@ public class ApplicationContextAssertTests { @Test public void getBeanOfTypeWhenHasPrimaryBeanShouldReturnPrimary() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - PrimaryFooConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrimaryFooConfig.class); assertThat(getAssert(context)).getBean(Foo.class).isInstanceOf(Bar.class); context.close(); } @@ -261,8 +248,7 @@ public class ApplicationContextAssertTests { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) .withMessageContaining("to contain bean of type") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -274,8 +260,7 @@ public class ApplicationContextAssertTests { @Test public void getBeanOfTypeWhenInParentWithLimitedScopeShouldReturnNullAssert() { this.parent.registerSingleton("foo", Foo.class); - assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS) - .isNull(); + assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNull(); } @Test @@ -291,8 +276,7 @@ public class ApplicationContextAssertTests { public void getBeanOfTypeWithLimitedScopeWhenHasMultipleBeansIncludingParentShouldReturnBeanAssert() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS) - .isNotNull(); + assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNotNull(); } @Test @@ -311,8 +295,7 @@ public class ApplicationContextAssertTests { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) .withMessageContaining("to contain a bean of name") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -329,27 +312,24 @@ public class ApplicationContextAssertTests { @Test public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(getAssert(this.context)).getBean("foo", String.class)) + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class)) .withMessageContaining("of type"); } @Test public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", - Foo.class)) + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class)) .withMessageContaining("to contain a bean of name") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test public void getBeansWhenHasBeansShouldReturnMapAssert() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2) - .containsKeys("foo", "bar"); + assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar"); } @Test @@ -362,24 +342,21 @@ public class ApplicationContextAssertTests { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) .withMessageContaining("to get beans of type") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test public void getBeansShouldIncludeBeansFromParentScope() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2) - .containsKeys("foo", "bar"); + assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar"); } @Test public void getBeansWithLimitedScopeShouldNotIncludeBeansFromParentScope() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS) - .hasSize(1).containsKeys("bar"); + assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS).hasSize(1).containsKeys("bar"); } @Test @@ -411,8 +388,7 @@ public class ApplicationContextAssertTests { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) .withMessageContaining("to have not failed") - .withMessageContaining(String.format( - "but context failed to start:%n java.lang.RuntimeException")); + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -420,8 +396,7 @@ public class ApplicationContextAssertTests { assertThat(getAssert(this.context)).hasNotFailed(); } - private AssertableApplicationContext getAssert( - ConfigurableApplicationContext applicationContext) { + private AssertableApplicationContext getAssert(ConfigurableApplicationContext applicationContext) { return AssertableApplicationContext.get(() -> applicationContext); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java index 09cb21c0f05..64d1e33ad70 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java @@ -39,12 +39,10 @@ public class SpringBootTestContextBootstrapperTests { @Test public void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() { assertThatIllegalStateException() - .isThrownBy(() -> buildTestContext( - SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) + .isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) .withMessageContaining("@WebAppConfiguration should only be used with " + "@SpringBootTest when @SpringBootTest is configured with a mock web " - + "environment. Please remove @WebAppConfiguration or reconfigure " - + "@SpringBootTest."); + + "environment. Please remove @WebAppConfiguration or reconfigure " + "@SpringBootTest."); } @Test @@ -58,10 +56,8 @@ public class SpringBootTestContextBootstrapperTests { BootstrapContext bootstrapContext = mock(BootstrapContext.class); bootstrapper.setBootstrapContext(bootstrapContext); given((Class) bootstrapContext.getTestClass()).willReturn(testClass); - CacheAwareContextLoaderDelegate contextLoaderDelegate = mock( - CacheAwareContextLoaderDelegate.class); - given(bootstrapContext.getCacheAwareContextLoaderDelegate()) - .willReturn(contextLoaderDelegate); + CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(CacheAwareContextLoaderDelegate.class); + given(bootstrapContext.getCacheAwareContextLoaderDelegate()).willReturn(contextLoaderDelegate); bootstrapper.buildTestContext(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java index c244cb36362..1ef87351b57 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java @@ -47,15 +47,13 @@ public class SpringBootTestContextBootstrapperWithInitializersTests { @Test public void foundConfiguration() { - Object bean = this.context - .getBean(SpringBootTestContextBootstrapperExampleConfig.class); + Object bean = this.context.getBean(SpringBootTestContextBootstrapperExampleConfig.class); assertThat(bean).isNotNull(); } // gh-8483 - public static class CustomInitializer - implements ApplicationContextInitializer { + public static class CustomInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java index b3942a7b133..8cdbbe05fdc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; * * @author Phillip Webb */ -public class TestDefaultTestExecutionListenersPostProcessor - implements DefaultTestExecutionListenersPostProcessor { +public class TestDefaultTestExecutionListenersPostProcessor implements DefaultTestExecutionListenersPostProcessor { @Override public Set> postProcessDefaultTestExecutionListeners( diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java index b841c170207..e02e786d34c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java @@ -41,68 +41,57 @@ public class TestTypeExcludeFilterTests { @Test public void matchesJUnit4TestClass() throws Exception { - assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory)) + .isTrue(); } @Test public void matchesJUnitJupiterTestClass() throws Exception { - assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class), this.metadataReaderFactory)).isTrue(); } @Test public void matchesJUnitJupiterRepeatedTestClass() throws Exception { - assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory)) + .isTrue(); } @Test public void matchesJUnitJupiterTestFactoryClass() throws Exception { - assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory)) + .isTrue(); } @Test public void matchesNestedConfiguration() throws Exception { - assertThat(this.filter.match(getMetadataReader(NestedConfig.class), + assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue(); + } + + @Test + public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception { + assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), this.metadataReaderFactory)).isTrue(); } @Test - public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() - throws Exception { - assertThat(this.filter.match( - getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), - this.metadataReaderFactory)).isTrue(); - } - - @Test - public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() - throws Exception { - assertThat(this.filter.match( - getMetadataReader( - AbstractJupiterTestWithConfigAndExtendWith.Config.class), + public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception { + assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class), this.metadataReaderFactory)).isTrue(); } @Test public void matchesTestConfiguration() throws Exception { - assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), this.metadataReaderFactory)).isTrue(); } @Test public void doesNotMatchRegularConfiguration() throws Exception { - assertThat(this.filter.match(getMetadataReader(SampleConfig.class), - this.metadataReaderFactory)).isFalse(); + assertThat(this.filter.match(getMetadataReader(SampleConfig.class), this.metadataReaderFactory)).isFalse(); } @Test - public void matchesNestedConfigurationClassWithoutTestNgAnnotation() - throws Exception { - assertThat(this.filter.match( - getMetadataReader(AbstractTestNgTestWithConfig.Config.class), + public void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception { + assertThat(this.filter.match(getMetadataReader(AbstractTestNgTestWithConfig.Config.class), this.metadataReaderFactory)).isTrue(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java index c49c41409f7..329ed7bff45 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java @@ -64,8 +64,7 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(System.getProperties()).containsEntry(key, - "value")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "value")); assertThat(System.getProperties().containsKey(key)).isFalse(); } @@ -73,8 +72,7 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(context).hasFailed()); assertThat(System.getProperties().containsKey(key)).isFalse(); } @@ -86,8 +84,7 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(System.getProperties()) - .containsEntry(key, "newValue")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue")); assertThat(System.getProperties().getProperty(key)).isEqualTo("value"); } finally { @@ -102,8 +99,7 @@ public abstract class AbstractApplicationContextRunnerTests { - Environment environment = context.getEnvironment(); - assertThat(environment.getProperty("test.foo")).isEqualTo("1"); - assertThat(environment.getProperty("test.bar")).isEqualTo("2"); - }); + get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2").run((context) -> { + Environment environment = context.getEnvironment(); + assertThat(environment.getProperty("test.foo")).isEqualTo("1"); + assertThat(environment.getProperty("test.bar")).isEqualTo("2"); + }); } @Test public void runWithPropertyValuesWhenHasExistingShouldReplaceValue() { - get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2") - .run((context) -> { - Environment environment = context.getEnvironment(); - assertThat(environment.getProperty("test.foo")).isEqualTo("2"); - }); + get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2").run((context) -> { + Environment environment = context.getEnvironment(); + assertThat(environment.getProperty("test.foo")).isEqualTo("2"); + }); } @Test public void runWithConfigurationsShouldRegisterConfigurations() { - get().withUserConfiguration(FooConfig.class) - .run((context) -> assertThat(context).hasBean("foo")); + get().withUserConfiguration(FooConfig.class).run((context) -> assertThat(context).hasBean("foo")); } @Test public void runWithUserNamedBeanShouldRegisterBean() { - get().withBean("foo", String.class, () -> "foo") - .run((context) -> assertThat(context).hasBean("foo")); + get().withBean("foo", String.class, () -> "foo").run((context) -> assertThat(context).hasBean("foo")); } @Test public void runWithUserBeanShouldRegisterBeanWithDefaultName() { - get().withBean(String.class, () -> "foo") - .run((context) -> assertThat(context).hasBean("string")); + get().withBean(String.class, () -> "foo").run((context) -> assertThat(context).hasBean("string")); } @Test @@ -159,8 +150,8 @@ public abstract class AbstractApplicationContextRunnerTests "overridden").run((context) -> { + get().withUserConfiguration(FooConfig.class).withBean("foo", String.class, () -> "overridden") + .run((context) -> { assertThat(context).hasBean("foo"); assertThat(context.getBean("foo")).isEqualTo("overridden"); }); @@ -168,37 +159,32 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(context).hasBean("foo").hasBean("bar")); } @Test public void runWithFailedContextShouldReturnFailedAssertableContext() { - get().withUserConfiguration(FailingConfig.class) - .run((context) -> assertThat(context).hasFailed()); + get().withUserConfiguration(FailingConfig.class).run((context) -> assertThat(context).hasFailed()); } @Test public void runWithClassLoaderShouldSetClassLoaderOnContext() { get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) .run((context) -> assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), - context.getClassLoader()))); + .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader()))); } @Test public void runWithClassLoaderShouldSetClassLoaderOnConditionContext() { get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) .withUserConfiguration(ConditionalConfig.class) - .run((context) -> assertThat(context) - .hasSingleBean(ConditionalConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class)); } @Test public void thrownRuleWorksWithCheckedException() { - get().run((context) -> assertThatIOException() - .isThrownBy(() -> throwCheckedException("Expected message")) + get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message")) .withMessageContaining("Expected message")); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java index 8258c6a2265..b8c3ee54280 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java @@ -35,8 +35,7 @@ public class WebApplicationContextRunnerTests extends @Test public void contextShouldHaveMockServletContext() { - get().run((context) -> assertThat(context.getServletContext()) - .isInstanceOf(MockServletContext.class)); + get().run((context) -> assertThat(context.getServletContext()).isInstanceOf(MockServletContext.class)); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java index e354452d802..225b956955f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java @@ -55,8 +55,7 @@ public abstract class AbstractJsonMarshalTesterTests { private static final ExampleObject OBJECT = createExampleObject("Spring", 123); - private static final ResolvableType TYPE = ResolvableType - .forClass(ExampleObject.class); + private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Test public void writeShouldReturnJsonContent() throws Exception { @@ -91,15 +90,14 @@ public abstract class AbstractJsonMarshalTesterTests { @Test public void createWhenResourceLoadClassIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> createTester(null, ResolvableType.forClass(ExampleObject.class))) + assertThatIllegalArgumentException() + .isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class))) .withMessageContaining("ResourceLoadClass must not be null"); } @Test public void createWhenTypeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> createTester(getClass(), null)) + assertThatIllegalArgumentException().isThrownBy(() -> createTester(getClass(), null)) .withMessageContaining("Type must not be null"); } @@ -182,8 +180,7 @@ public abstract class AbstractJsonMarshalTesterTests { return createTester(AbstractJsonMarshalTesterTests.class, type); } - protected abstract AbstractJsonMarshalTester createTester( - Class resourceLoadClass, ResolvableType type); + protected abstract AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type); /** * Access to field backed by {@link ResolvableType}. diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java index 26876ad7ef1..4580c9f036a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java @@ -40,10 +40,10 @@ public class DuplicateJsonObjectContextCustomizerFactoryTests { @Test public void warningForMultipleVersions() { - new DuplicateJsonObjectContextCustomizerFactory() - .createContextCustomizer(null, null).customizeContext(null, null); - assertThat(this.output.toString()).contains( - "Found multiple occurrences of org.json.JSONObject on the class path:"); + new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null, + null); + assertThat(this.output.toString()) + .contains("Found multiple occurrences of org.json.JSONObject on the class path:"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java index f139f640059..82e34b528b3 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class ExampleObject { return false; } ExampleObject other = (ExampleObject) obj; - return ObjectUtils.nullSafeEquals(this.name, other.name) - && ObjectUtils.nullSafeEquals(this.age, other.age); + return ObjectUtils.nullSafeEquals(this.name, other.name) && ObjectUtils.nullSafeEquals(this.age, other.age); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java index b9bc7b7c9bc..489b0f92d98 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class ExampleObjectWithView { return false; } ExampleObjectWithView other = (ExampleObjectWithView) obj; - return ObjectUtils.nullSafeEquals(this.name, other.name) - && ObjectUtils.nullSafeEquals(this.age, other.age); + return ObjectUtils.nullSafeEquals(this.name, other.name) && ObjectUtils.nullSafeEquals(this.age, other.age); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java index 3f0e9c5fd35..12e5d7c6a60 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java @@ -55,16 +55,14 @@ public class GsonTesterIntegrationTests { @Test public void typicalTest() throws Exception { String example = JSON; - assertThat(this.simpleJson.parse(example).getObject().getName()) - .isEqualTo("Spring"); + assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring"); } @Test public void typicalListTest() throws Exception { String example = "[" + JSON + "]"; assertThat(this.listJson.parse(example)).asList().hasSize(1); - assertThat(this.listJson.parse(example).getObject().get(0).getName()) - .isEqualTo("Spring"); + assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring"); } @Test @@ -72,15 +70,13 @@ public class GsonTesterIntegrationTests { Map map = new LinkedHashMap<>(); map.put("a", 1); map.put("b", 2); - assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a") - .isEqualTo(1); + assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1); } @Test public void stringLiteral() throws Exception { String stringWithSpecialCharacters = "myString"; - assertThat(this.stringJson.write(stringWithSpecialCharacters)) - .extractingJsonPathStringValue("@") + assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") .isEqualTo(stringWithSpecialCharacters); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index cb78c70449d..f08166da0fe 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java @@ -36,15 +36,14 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { @Test public void initFieldsWhenTestIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create())) + assertThatIllegalArgumentException().isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create())) .withMessageContaining("TestInstance must not be null"); } @Test public void initFieldsWhenMarshallerIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) .withMessageContaining("Marshaller must not be null"); } @@ -61,8 +60,7 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { } @Override - protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, - ResolvableType type) { + protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type) { return new GsonTester<>(resourceLoadClass, type, new GsonBuilder().create()); } @@ -70,9 +68,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { public GsonTester base; - public GsonTester baseSet = new GsonTester<>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new GsonBuilder().create()); + public GsonTester baseSet = new GsonTester<>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create()); } @@ -80,9 +77,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { public GsonTester> test; - public GsonTester testSet = new GsonTester<>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new GsonBuilder().create()); + public GsonTester testSet = new GsonTester<>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create()); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java index 12a9530ef8b..a2d37fae8e6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java @@ -63,16 +63,14 @@ public class JacksonTesterIntegrationTests { @Test public void typicalTest() throws Exception { String example = JSON; - assertThat(this.simpleJson.parse(example).getObject().getName()) - .isEqualTo("Spring"); + assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring"); } @Test public void typicalListTest() throws Exception { String example = "[" + JSON + "]"; assertThat(this.listJson.parse(example)).asList().hasSize(1); - assertThat(this.listJson.parse(example).getObject().get(0).getName()) - .isEqualTo("Spring"); + assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring"); } @Test @@ -80,15 +78,13 @@ public class JacksonTesterIntegrationTests { Map map = new LinkedHashMap<>(); map.put("a", 1); map.put("b", 2); - assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a") - .isEqualTo(1); + assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1); } @Test public void stringLiteral() throws Exception { String stringWithSpecialCharacters = "myString"; - assertThat(this.stringJson.write(stringWithSpecialCharacters)) - .extractingJsonPathStringValue("@") + assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") .isEqualTo(stringWithSpecialCharacters); } @@ -101,8 +97,7 @@ public class JacksonTesterIntegrationTests { // configures json-path to use Jackson for evaluating the path expressions and // restores the symmetry. See gh-15727 String stringWithSpecialCharacters = "\u0006\u007F"; - assertThat(this.stringJson.write(stringWithSpecialCharacters)) - .extractingJsonPathStringValue("@") + assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") .isEqualTo(stringWithSpecialCharacters); } @@ -112,8 +107,8 @@ public class JacksonTesterIntegrationTests { ExampleObjectWithView object = new ExampleObjectWithView(); object.setName("Spring"); object.setAge(123); - JsonContent content = this.jsonWithView - .forView(ExampleObjectWithView.TestView.class).write(object); + JsonContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) + .write(object); assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring"); assertThat(content).doesNotHaveJsonPathValue("age"); } @@ -122,8 +117,8 @@ public class JacksonTesterIntegrationTests { public void readWithResourceAndView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); ByteArrayResource resource = new ByteArrayResource(JSON.getBytes()); - ObjectContent content = this.jsonWithView - .forView(ExampleObjectWithView.TestView.class).read(resource); + ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) + .read(resource); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isEqualTo(0); } @@ -132,8 +127,8 @@ public class JacksonTesterIntegrationTests { public void readWithReaderAndView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); Reader reader = new StringReader(JSON); - ObjectContent content = this.jsonWithView - .forView(ExampleObjectWithView.TestView.class).read(reader); + ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) + .read(reader); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isEqualTo(0); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java index 475f2288027..9c9d4db511c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java @@ -35,16 +35,14 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { @Test public void initFieldsWhenTestIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper())) + assertThatIllegalArgumentException().isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper())) .withMessageContaining("TestInstance must not be null"); } @Test public void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), - (ObjectMapper) null)) + .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) .withMessageContaining("Marshaller must not be null"); } @@ -61,8 +59,7 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { } @Override - protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, - ResolvableType type) { + protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type) { return new JacksonTester<>(resourceLoadClass, type, new ObjectMapper()); } @@ -70,9 +67,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { public JacksonTester base; - public JacksonTester baseSet = new JacksonTester<>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new ObjectMapper()); + public JacksonTester baseSet = new JacksonTester<>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new ObjectMapper()); } @@ -80,9 +76,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { public JacksonTester> test; - public JacksonTester testSet = new JacksonTester<>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new ObjectMapper()); + public JacksonTester testSet = new JacksonTester<>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new ObjectMapper()); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index 1b10fee68a1..89f90b37332 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java @@ -58,8 +58,7 @@ public class JsonContentAssertTests { private static final String SIMPSONS = loadJson("simpsons.json"); - private static JSONComparator COMPARATOR = new DefaultComparator( - JSONCompareMode.LENIENT); + private static JSONComparator COMPARATOR = new DefaultComparator(JSONCompareMode.LENIENT); @TempDir public Path tempDir; @@ -78,8 +77,7 @@ public class JsonContentAssertTests { @Test public void isEqualToWhenNullActualShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(null)).isEqualTo(SOURCE)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(null)).isEqualTo(SOURCE)); } @Test @@ -95,8 +93,8 @@ public class JsonContentAssertTests { @Test public void isEqualToWhenResourcePathIsNotMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); } @Test @@ -106,8 +104,8 @@ public class JsonContentAssertTests { @Test public void isEqualToWhenBytesAreNotMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); } @Test @@ -117,8 +115,8 @@ public class JsonContentAssertTests { @Test public void isEqualToWhenFileIsNotMatchingShouldFail() throws Exception { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); } @Test @@ -129,8 +127,7 @@ public class JsonContentAssertTests { @Test public void isEqualToWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualTo(createInputStream(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createInputStream(DIFFERENT))); } @Test @@ -140,8 +137,8 @@ public class JsonContentAssertTests { @Test public void isEqualToWhenResourceIsNotMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); } @Test @@ -168,8 +165,8 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); } @Test @@ -180,8 +177,7 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson("different.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass())); } @Test @@ -191,8 +187,8 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenBytesAreNotMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); } @Test @@ -202,8 +198,8 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenFileIsNotMatchingShouldFail() throws Exception { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); } @Test @@ -214,8 +210,7 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(createInputStream(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT))); } @Test @@ -226,8 +221,7 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(createResource(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT))); } @Test @@ -237,8 +231,8 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); } @Test @@ -249,8 +243,7 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json")); } @Test @@ -261,8 +254,7 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson("lenient-same.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass())); } @Test @@ -273,8 +265,7 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes())); } @Test @@ -285,8 +276,7 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenFileIsNotMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(LENIENT_SAME))); } @Test @@ -297,8 +287,7 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); } @Test @@ -309,8 +298,7 @@ public class JsonContentAssertTests { @Test public void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME))); } @Test @@ -321,86 +309,73 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, - JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT)); } @Test public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson("different.json", JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT)); } @Test public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", - getClass(), JSONCompareMode.LENIENT)); + () -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT)); } @Test public void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); } @Test public void isEqualToJsonWhenFileIsMatchingAndLenientShouldPass() throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT)); } @Test public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson( - createInputStream(DIFFERENT), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT)); } @Test public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), - JSONCompareMode.LENIENT)); + () -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT)); } @Test @@ -410,8 +385,8 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); } @Test @@ -422,21 +397,18 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson("different.json", COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR)); } @Test public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), - COMPARATOR); + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR); } @Test public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson("different.json", getClass(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR)); } @Test @@ -447,48 +419,40 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); } @Test - public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() - throws Exception { + public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), COMPARATOR); } @Test - public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(createFile(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR)); } @Test public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), - COMPARATOR); + assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR); } @Test public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); } @Test public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), - COMPARATOR); + assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), COMPARATOR); } @Test public void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isEqualToJson(createResource(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR)); } @Test @@ -509,8 +473,8 @@ public class JsonContentAssertTests { @Test public void isNotEqualToWhenResourcePathIsMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); } @Test @@ -520,8 +484,8 @@ public class JsonContentAssertTests { @Test public void isNotEqualToWhenBytesAreMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); } @Test @@ -531,8 +495,8 @@ public class JsonContentAssertTests { @Test public void isNotEqualToWhenFileIsMatchingShouldFail() throws Exception { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); } @Test @@ -543,8 +507,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualTo(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(LENIENT_SAME))); } @Test @@ -555,8 +518,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualTo(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createResource(LENIENT_SAME))); } @Test @@ -566,8 +528,8 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenStringIsMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); } @Test @@ -582,8 +544,8 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenResourcePathIsMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); } @Test @@ -594,8 +556,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson("lenient-same.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass())); } @Test @@ -606,8 +567,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes())); } @Test @@ -618,8 +578,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenFileIsMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME))); } @Test @@ -630,8 +589,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME))); } @Test @@ -642,8 +600,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME))); } @Test @@ -653,8 +610,8 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); } @Test @@ -665,8 +622,7 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson("source.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json")); } @Test @@ -677,21 +633,18 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson("source.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass())); } @Test public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() { - assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", - getClass()); + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass()); } @Test public void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(SOURCE.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes())); } @Test @@ -702,47 +655,40 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenFileIsMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createFile(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(SOURCE))); } @Test - public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() - throws Exception { + public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME)); } @Test public void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createInputStream(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE))); } @Test public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() { - assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); } @Test public void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createResource(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE))); } @Test public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() { - assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); } @Test public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); } @Test @@ -752,89 +698,74 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT)); } @Test public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", JSONCompareMode.LENIENT); } @Test public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", - getClass(), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) + .isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT)); } @Test public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT); } @Test public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson( - LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT)); } @Test public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() - throws Exception { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson( - createFile(LENIENT_SAME), JSONCompareMode.LENIENT)); + public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception { + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT); } @Test public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson( - createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) + .isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT); } @Test public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson( - createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) + .isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT); } @Test public void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(LENIENT_SAME, COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR)); } @Test @@ -845,8 +776,7 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson("lenient-same.json", COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR)); } @Test @@ -856,22 +786,19 @@ public class JsonContentAssertTests { @Test public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR)); } @Test public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), - COMPARATOR); + assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), COMPARATOR); } @Test public void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); } @Test @@ -880,43 +807,36 @@ public class JsonContentAssertTests { } @Test - public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() - throws Exception { + public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() - throws Exception { + public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), COMPARATOR); } @Test public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR)); } @Test public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), - COMPARATOR); + assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), COMPARATOR); } @Test public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); } @Test public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), - COMPARATOR); + assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), COMPARATOR); } @Test @@ -936,16 +856,14 @@ public class JsonContentAssertTests { @Test public void hasJsonPathValueForIndefinitePathWithResults() { - assertThat(forJson(SIMPSONS)) - .hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); + assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test public void hasJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy( - () -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) .withMessageContaining("No value at JSON path \"" + expression + "\""); } @@ -957,34 +875,31 @@ public class JsonContentAssertTests { @Test public void doesNotHaveJsonPathValueForAnEmptyArray() { String expression = "$.emptyArray"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression - + "\" but found: []"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []"); } @Test public void doesNotHaveJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression - + "\" but found: {}"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}"); } @Test public void doesNotHaveJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining( + "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() { - assertThat(forJson(SIMPSONS)) - .doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); + assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test @@ -1004,26 +919,24 @@ public class JsonContentAssertTests { @Test public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() { - assertThat(forJson(SIMPSONS)) - .hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); + assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test public void hasEmptyJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) - .withMessageContaining("Expected an empty value at JSON path \"" - + expression + "\" but found: [{\"name\":\"Bart\"}]"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) + .withMessageContaining( + "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test public void hasEmptyJsonPathValueForWhitespace() { String expression = "$.whitespace"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) - .withMessageContaining("Expected an empty value at JSON path \"" - + expression + "\" but found: ' '"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) + .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); } @Test @@ -1053,48 +966,39 @@ public class JsonContentAssertTests { @Test public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() { - assertThat(forJson(SIMPSONS)) - .doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); + assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)) - .doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test public void doesNotHaveEmptyJsonPathValueForAnEmptyString() { String expression = "$.emptyString"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)) - .doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" - + expression + "\" but found: ''"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); } @Test public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)) - .doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)) - .doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" - + expression + "\" but found: {}"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); } @Test @@ -1110,10 +1014,9 @@ public class JsonContentAssertTests { @Test public void hasJsonPathStringValueForNonString() { String expression = "$.bool"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) - .withMessageContaining("Expected a string at JSON path \"" + expression - + "\" but found: true"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true"); } @Test @@ -1124,10 +1027,9 @@ public class JsonContentAssertTests { @Test public void hasJsonPathNumberValueForNonNumber() { String expression = "$.bool"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) - .withMessageContaining("Expected a number at JSON path \"" + expression - + "\" but found: true"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true"); } @Test @@ -1138,10 +1040,9 @@ public class JsonContentAssertTests { @Test public void hasJsonPathBooleanValueForNonBoolean() { String expression = "$.num"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) - .withMessageContaining("Expected a boolean at JSON path \"" + expression - + "\" but found: 5"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); } @Test @@ -1157,10 +1058,9 @@ public class JsonContentAssertTests { @Test public void hasJsonPathArrayValueForNonArray() { String expression = "$.str"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) - .withMessageContaining("Expected an array at JSON path \"" + expression - + "\" but found: 'foo'"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1177,10 +1077,8 @@ public class JsonContentAssertTests { public void hasJsonPathMapValueForNonMap() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy( - () -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) - .withMessageContaining("Expected a map at JSON path \"" + expression - + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1195,8 +1093,7 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathStringValue() { - assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str") - .isEqualTo("foo"); + assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo"); } @Test @@ -1206,18 +1103,15 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathStringValueForEmptyString() { - assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString") - .isEmpty(); + assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString").isEmpty(); } @Test public void extractingJsonPathStringValueForWrongType() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)) - .extractingJsonPathStringValue(expression)) - .withMessageContaining("Expected a string at JSON path \"" + expression - + "\" but found: 5"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: 5"); } @Test @@ -1234,10 +1128,8 @@ public class JsonContentAssertTests { public void extractingJsonPathNumberValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)) - .extractingJsonPathNumberValue(expression)) - .withMessageContaining("Expected a number at JSON path \"" + expression - + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1254,16 +1146,13 @@ public class JsonContentAssertTests { public void extractingJsonPathBooleanValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)) - .extractingJsonPathBooleanValue(expression)) - .withMessageContaining("Expected a boolean at JSON path \"" + expression - + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); } @Test public void extractingJsonPathArrayValue() { - assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr") - .containsExactly(42); + assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42); } @Test @@ -1279,16 +1168,14 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathArrayValueForWrongType() { String expression = "$.str"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) - .withMessageContaining("Expected an array at JSON path \"" + expression - + "\" but found: 'foo'"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test public void extractingJsonPathMapValue() { - assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap") - .contains(entry("red", "rojo")); + assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo")); } @Test @@ -1304,10 +1191,9 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathMapValueForWrongType() { String expression = "$.str"; - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) - .withMessageContaining("Expected a map at JSON path \"" + expression - + "\" but found: 'foo'"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1331,8 +1217,7 @@ public class JsonContentAssertTests { private static String loadJson(String path) { try { - ClassPathResource resource = new ClassPathResource(path, - JsonContentAssertTests.class); + ClassPathResource resource = new ClassPathResource(path, JsonContentAssertTests.class); return new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (Exception ex) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java index 3f45f1ee201..ab2e3e74215 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java @@ -33,29 +33,27 @@ public class JsonContentTests { private static final String JSON = "{\"name\":\"spring\", \"age\":100}"; - private static final ResolvableType TYPE = ResolvableType - .forClass(ExampleObject.class); + private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Test public void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JsonContent(null, TYPE, JSON, - Configuration.defaultConfiguration())) + .isThrownBy( + () -> new JsonContent(null, TYPE, JSON, Configuration.defaultConfiguration())) .withMessageContaining("ResourceLoadClass must not be null"); } @Test public void createWhenJsonIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new JsonContent(getClass(), TYPE, null, - Configuration.defaultConfiguration())) + assertThatIllegalArgumentException().isThrownBy( + () -> new JsonContent(getClass(), TYPE, null, Configuration.defaultConfiguration())) .withMessageContaining("JSON must not be null"); } @Test public void createWhenConfigurationIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JsonContent(getClass(), TYPE, JSON, null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new JsonContent(getClass(), TYPE, JSON, null)) .withMessageContaining("Configuration must not be null"); } @@ -86,8 +84,7 @@ public class JsonContentTests { public void toStringWhenHasTypeShouldReturnString() { JsonContent content = new JsonContent<>(getClass(), TYPE, JSON, Configuration.defaultConfiguration()); - assertThat(content.toString()) - .isEqualTo("JsonContent " + JSON + " created from " + TYPE); + assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java index df63069cba4..51aa1d10b14 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java @@ -37,15 +37,14 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests { @Test public void initFieldsWhenTestIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create())) + assertThatIllegalArgumentException().isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create())) .withMessageContaining("TestInstance must not be null"); } @Test public void initFieldsWhenMarshallerIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) .withMessageContaining("Marshaller must not be null"); } @@ -62,8 +61,7 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests { } @Override - protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, - ResolvableType type) { + protected AbstractJsonMarshalTester createTester(Class resourceLoadClass, ResolvableType type) { return new JsonbTester<>(resourceLoadClass, type, JsonbBuilder.create()); } @@ -71,9 +69,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests { public JsonbTester base; - public JsonbTester baseSet = new JsonbTester<>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - JsonbBuilder.create()); + public JsonbTester baseSet = new JsonbTester<>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create()); } @@ -81,9 +78,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests { public JsonbTester> test; - public JsonbTester testSet = new JsonbTester<>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - JsonbBuilder.create()); + public JsonbTester testSet = new JsonbTester<>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create()); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java index 33666a09c1e..fd8e8c46b0a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java @@ -60,8 +60,7 @@ public class ObjectContentAssertTests { @Test public void asArrayForNonArrayShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forObject(SOURCE)).asArray()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asArray()); } @Test @@ -72,8 +71,7 @@ public class ObjectContentAssertTests { @Test public void asMapForNonMapShouldFail() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forObject(SOURCE)).asMap()); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asMap()); } private AssertProvider> forObject(Object source) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index ce56c467491..c71fee903ca 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java @@ -32,13 +32,11 @@ public class ObjectContentTests { private static final ExampleObject OBJECT = new ExampleObject(); - private static final ResolvableType TYPE = ResolvableType - .forClass(ExampleObject.class); + private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Test public void createWhenObjectIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ObjectContent(TYPE, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectContent(TYPE, null)) .withMessageContaining("Object must not be null"); } @@ -63,8 +61,7 @@ public class ObjectContentTests { @Test public void toStringWhenHasTypeShouldReturnString() { ObjectContent content = new ObjectContent<>(TYPE, OBJECT); - assertThat(content.toString()) - .isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE); + assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java index eda3530b5ab..33203f2866f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java @@ -45,18 +45,15 @@ public class DefinitionsParserTests { public void parseSingleMockBean() { this.parser.parse(SingleMockBean.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); } @Test public void parseRepeatMockBean() { this.parser.parse(RepeatMockBean.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); - assertThat(getMockDefinition(1).getTypeToMock().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); + assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test @@ -66,8 +63,7 @@ public class DefinitionsParserTests { MockDefinition definition = getMockDefinition(0); assertThat(definition.getName()).isEqualTo("Name"); assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class); - assertThat(definition.getExtraInterfaces()) - .containsExactly(ExampleExtraInterface.class); + assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class); assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); assertThat(definition.isSerializable()).isTrue(); assertThat(definition.getReset()).isEqualTo(MockReset.NONE); @@ -79,14 +75,12 @@ public class DefinitionsParserTests { this.parser.parse(MockBeanOnClassAndField.class); assertThat(getDefinitions()).hasSize(2); MockDefinition classDefinition = getMockDefinition(0); - assertThat(classDefinition.getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); + assertThat(classDefinition.getTypeToMock().resolve()).isEqualTo(ExampleService.class); assertThat(classDefinition.getQualifier()).isNull(); MockDefinition fieldDefinition = getMockDefinition(1); - assertThat(fieldDefinition.getTypeToMock().resolve()) - .isEqualTo(ExampleServiceCaller.class); - QualifierDefinition qualifier = QualifierDefinition.forElement( - ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); + assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); + QualifierDefinition qualifier = QualifierDefinition + .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); } @@ -94,14 +88,12 @@ public class DefinitionsParserTests { public void parseMockBeanInferClassToMock() { this.parser.parse(MockBeanInferClassToMock.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); } @Test public void parseMockBeanMissingClassToMock() { - assertThatIllegalStateException() - .isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) + assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) .withMessageContaining("Unable to deduce type to mock"); } @@ -109,37 +101,29 @@ public class DefinitionsParserTests { public void parseMockBeanMultipleClasses() { this.parser.parse(MockBeanMultipleClasses.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); - assertThat(getMockDefinition(1).getTypeToMock().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); + assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test public void parseMockBeanMultipleClassesWithName() { - assertThatIllegalStateException() - .isThrownBy( - () -> this.parser.parse(MockBeanMultipleClassesWithName.class)) - .withMessageContaining( - "The name attribute can only be used when mocking a single class"); + assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class)) + .withMessageContaining("The name attribute can only be used when mocking a single class"); } @Test public void parseSingleSpyBean() { this.parser.parse(SingleSpyBean.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); } @Test public void parseRepeatSpyBean() { this.parser.parse(RepeatSpyBean.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); - assertThat(getSpyDefinition(1).getTypeToSpy().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test @@ -148,8 +132,7 @@ public class DefinitionsParserTests { assertThat(getDefinitions()).hasSize(1); SpyDefinition definition = getSpyDefinition(0); assertThat(definition.getName()).isEqualTo("Name"); - assertThat(definition.getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(definition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); assertThat(definition.getReset()).isEqualTo(MockReset.NONE); assertThat(definition.getQualifier()).isNull(); } @@ -160,28 +143,24 @@ public class DefinitionsParserTests { assertThat(getDefinitions()).hasSize(2); SpyDefinition classDefinition = getSpyDefinition(0); assertThat(classDefinition.getQualifier()).isNull(); - assertThat(classDefinition.getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); SpyDefinition fieldDefinition = getSpyDefinition(1); - QualifierDefinition qualifier = QualifierDefinition.forElement( - ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); + QualifierDefinition qualifier = QualifierDefinition + .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); - assertThat(fieldDefinition.getTypeToSpy().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test public void parseSpyBeanInferClassToMock() { this.parser.parse(SpyBeanInferClassToMock.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); } @Test public void parseSpyBeanMissingClassToMock() { - assertThatIllegalStateException() - .isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) + assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) .withMessageContaining("Unable to deduce type to spy"); } @@ -189,18 +168,14 @@ public class DefinitionsParserTests { public void parseSpyBeanMultipleClasses() { this.parser.parse(SpyBeanMultipleClasses.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); - assertThat(getSpyDefinition(1).getTypeToSpy().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test public void parseSpyBeanMultipleClassesWithName() { - assertThatIllegalStateException() - .isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) - .withMessageContaining( - "The name attribute can only be used when spying a single class"); + assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) + .withMessageContaining("The name attribute can only be used when spying a single class"); } private MockDefinition getMockDefinition(int index) { @@ -225,10 +200,8 @@ public class DefinitionsParserTests { } - @MockBean(name = "Name", classes = ExampleService.class, - extraInterfaces = ExampleExtraInterface.class, - answer = Answers.RETURNS_SMART_NULLS, serializable = true, - reset = MockReset.NONE) + @MockBean(name = "Name", classes = ExampleService.class, extraInterfaces = ExampleExtraInterface.class, + answer = Answers.RETURNS_SMART_NULLS, serializable = true, reset = MockReset.NONE) static class MockBeanAttributes { } @@ -247,8 +220,7 @@ public class DefinitionsParserTests { } - @MockBean(name = "name", - classes = { ExampleService.class, ExampleServiceCaller.class }) + @MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class }) static class MockBeanMultipleClassesWithName { } @@ -270,8 +242,7 @@ public class DefinitionsParserTests { } - @SpyBeans({ @SpyBean(RealExampleService.class), - @SpyBean(ExampleServiceCaller.class) }) + @SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) }) static class RepeatSpyBean { } @@ -295,8 +266,7 @@ public class DefinitionsParserTests { } - @SpyBean(name = "name", - classes = { RealExampleService.class, ExampleServiceCaller.class }) + @SpyBean(name = "name", classes = { RealExampleService.class, ExampleServiceCaller.class }) static class SpyBeanMultipleClassesWithName { } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java index 4f3172c6271..53eb20a9816 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java @@ -53,8 +53,7 @@ public class MockBeanOnContextHierarchyIntegrationTests { ApplicationContext context = this.childConfig.getContext(); ApplicationContext parentContext = context.getParent(); assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1); - assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)) - .hasSize(0); + assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1); assertThat(context.getBean(ExampleService.class)).isNotNull(); @@ -74,8 +73,7 @@ public class MockBeanOnContextHierarchyIntegrationTests { private ApplicationContext context; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java index 468aa9e5dc1..e20da695328 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java @@ -62,8 +62,7 @@ public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { @Test public void onlyQualifiedBeanIsReplaced() { assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); - ExampleService anotherService = this.applicationContext.getBean("anotherService", - ExampleService.class); + ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); assertThat(anotherService.greeting()).isEqualTo("Another"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java index 53ffe10f6fd..3db91e84387 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java @@ -36,20 +36,18 @@ import static org.mockito.Mockito.mock; */ public class MockDefinitionTests { - private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType - .forClass(ExampleService.class); + private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType.forClass(ExampleService.class); @Test public void classToMockMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new MockDefinition(null, null, null, null, false, null, null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) .withMessageContaining("TypeToMock must not be null"); } @Test public void createWithDefaults() { - MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, - null, false, null, null); + MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null); assertThat(definition.getName()).isNull(); assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); assertThat(definition.getExtraInterfaces()).isEmpty(); @@ -63,12 +61,11 @@ public class MockDefinitionTests { public void createExplicit() { QualifierDefinition qualifier = mock(QualifierDefinition.class); MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, - new Class[] { ExampleExtraInterface.class }, - Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, qualifier); + new Class[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, + qualifier); assertThat(definition.getName()).isEqualTo("name"); assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); - assertThat(definition.getExtraInterfaces()) - .containsExactly(ExampleExtraInterface.class); + assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class); assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); assertThat(definition.isSerializable()).isTrue(); assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE); @@ -79,11 +76,10 @@ public class MockDefinitionTests { @Test public void createMock() { MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, - new Class[] { ExampleExtraInterface.class }, - Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null); + new Class[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, + null); ExampleService mock = definition.createMock(); - MockCreationSettings settings = Mockito.mockingDetails(mock) - .getMockCreationSettings(); + MockCreationSettings settings = Mockito.mockingDetails(mock).getMockCreationSettings(); assertThat(mock).isInstanceOf(ExampleService.class); assertThat(mock).isInstanceOf(ExampleExtraInterface.class); assertThat(settings.getMockName().toString()).isEqualTo("name"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java index b8c221491bc..f96c7886c31 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java @@ -39,8 +39,7 @@ public class MockResetTests { @Test public void withSettingsOfNoneAttachesReset() { - ExampleService mock = mock(ExampleService.class, - MockReset.withSettings(MockReset.NONE)); + ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.NONE)); assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE); } @@ -58,15 +57,13 @@ public class MockResetTests { @Test public void withSettingsAttachesReset() { - ExampleService mock = mock(ExampleService.class, - MockReset.withSettings(MockReset.BEFORE)); + ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.BEFORE)); assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); } @Test public void apply() { - ExampleService mock = mock(ExampleService.class, - MockReset.apply(MockReset.AFTER, withSettings())); + ExampleService mock = mock(ExampleService.class, MockReset.apply(MockReset.AFTER, withSettings())); assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java index f02026e98de..c4d43584c0e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java @@ -40,28 +40,23 @@ public class MockitoContextCustomizerFactoryTests { @Test public void getContextCustomizerWithoutAnnotationReturnsCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoMockBeanAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerWithAnnotationReturnsCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithMockBeanAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerUsesMocksAsCacheKey() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithMockBeanAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); - ContextCustomizer same = this.factory - .createContextCustomizer(WithSameMockBeanAnnotation.class, null); + ContextCustomizer same = this.factory.createContextCustomizer(WithSameMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); - ContextCustomizer different = this.factory - .createContextCustomizer(WithDifferentMockBeanAnnotation.class, null); + ContextCustomizer different = this.factory.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null); assertThat(different).isNotNull(); assertThat(customizer.hashCode()).isEqualTo(same.hashCode()); assertThat(customizer.hashCode()).isNotEqualTo(different.hashCode()); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java index 0ed44b93398..8fa8c891aad 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java @@ -43,18 +43,15 @@ public class MockitoContextCustomizerTests { MockDefinition d1 = createTestMockDefinition(ExampleService.class); MockDefinition d2 = createTestMockDefinition(ExampleServiceCaller.class); MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS); - MockitoContextCustomizer c2 = new MockitoContextCustomizer( - new LinkedHashSet<>(Arrays.asList(d1, d2))); - MockitoContextCustomizer c3 = new MockitoContextCustomizer( - new LinkedHashSet<>(Arrays.asList(d2, d1))); + MockitoContextCustomizer c2 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d1, d2))); + MockitoContextCustomizer c3 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d2, d1))); assertThat(c2.hashCode()).isEqualTo(c3.hashCode()); assertThat(c1).isEqualTo(c1).isNotEqualTo(c2); assertThat(c2).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c1); } private MockDefinition createTestMockDefinition(Class typeToMock) { - return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, - false, null, null); + return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, false, null, null); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java index f9009c0f816..2d64d28c6a7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java @@ -48,10 +48,8 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleBeans.class); assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example2]"); + .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + "but found [example1, example2]"); } @Test @@ -60,25 +58,20 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example3]"); + .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + "but found [example1, example3]"); } @Test public void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); - RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition( - TestFactoryBean.class); - factoryBeanDefinition.setAttribute("factoryBeanObjectType", - SomeInterface.class.getName()); + RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class); + factoryBeanDefinition.setAttribute("factoryBeanObjectType", SomeInterface.class.getName()); context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition); context.register(MockedFactoryBean.class); context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()) - .isTrue(); + assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()).isTrue(); } @Test @@ -87,16 +80,11 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MockPrimaryBean.class); context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock) - .isMock()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()) - .isTrue(); - assertThat(Mockito - .mockingDetails(context.getBean("examplePrimary", ExampleService.class)) - .isMock()).isTrue(); - assertThat(Mockito - .mockingDetails(context.getBean("exampleQualified", ExampleService.class)) - .isMock()).isFalse(); + assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock).isMock()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()) + .isFalse(); } @Test @@ -105,16 +93,10 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MockQualifiedBean.class); context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock) - .isMock()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()) - .isFalse(); - assertThat(Mockito - .mockingDetails(context.getBean("examplePrimary", ExampleService.class)) - .isMock()).isFalse(); - assertThat(Mockito - .mockingDetails(context.getBean("exampleQualified", ExampleService.class)) - .isMock()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock).isMock()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isFalse(); + assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isFalse(); + assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()).isTrue(); } @Test @@ -123,17 +105,10 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(SpyPrimaryBean.class); context.refresh(); - assertThat( - Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy()) - .isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()) - .isTrue(); - assertThat(Mockito - .mockingDetails(context.getBean("examplePrimary", ExampleService.class)) - .isSpy()).isTrue(); - assertThat(Mockito - .mockingDetails(context.getBean("exampleQualified", ExampleService.class)) - .isSpy()).isFalse(); + assertThat(Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isFalse(); } @Test @@ -142,16 +117,10 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(SpyQualifiedBean.class); context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy) - .isSpy()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()) - .isFalse(); - assertThat(Mockito - .mockingDetails(context.getBean("examplePrimary", ExampleService.class)) - .isSpy()).isFalse(); - assertThat(Mockito - .mockingDetails(context.getBean("exampleQualified", ExampleService.class)) - .isSpy()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy).isSpy()).isTrue(); + assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isFalse(); + assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isFalse(); + assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isTrue(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java index 27d5504f507..716324fb416 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java @@ -59,8 +59,7 @@ public class MockitoTestExecutionListenerTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - given(this.applicationContext.getBean(MockitoPostProcessor.class)) - .willReturn(this.postProcessor); + given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); } @Test @@ -75,30 +74,25 @@ public class MockitoTestExecutionListenerTests { public void prepareTestInstanceShouldInjectMockBean() throws Exception { WithMockBean instance = new WithMockBean(); this.listener.prepareTestInstance(mockTestContext(instance)); - verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), - any(MockDefinition.class)); + verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class)); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); } @Test - public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() - throws Exception { + public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception { WithMockBean instance = new WithMockBean(); this.listener.beforeTestMethod(mockTestContext(instance)); verifyNoMoreInteractions(this.postProcessor); } @Test - public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() - throws Exception { + public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception { WithMockBean instance = new WithMockBean(); TestContext mockTestContext = mockTestContext(instance); - given(mockTestContext.getAttribute( - DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) - .willReturn(Boolean.TRUE); + given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) + .willReturn(Boolean.TRUE); this.listener.beforeTestMethod(mockTestContext); - verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), - (MockDefinition) any()); + verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), (MockDefinition) any()); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java index ca4b6a36447..03a07a809e0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java @@ -85,10 +85,8 @@ public class QualifierDefinitionTests { Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier"); QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field); qualifierDefinition.matches(this.beanFactory, "bean"); - verify(this.beanFactory).isAutowireCandidate(eq("bean"), - this.descriptorCaptor.capture()); - assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()) - .isEqualTo(field); + verify(this.beanFactory).isAutowireCandidate(eq("bean"), this.descriptorCaptor.capture()); + assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()).isEqualTo(field); } @Test @@ -106,24 +104,23 @@ public class QualifierDefinitionTests { .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); QualifierDefinition directQualifier2 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); - QualifierDefinition differentDirectQualifier1 = QualifierDefinition.forElement( - ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); - QualifierDefinition differentDirectQualifier2 = QualifierDefinition.forElement( - ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); + QualifierDefinition differentDirectQualifier1 = QualifierDefinition + .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); + QualifierDefinition differentDirectQualifier2 = QualifierDefinition + .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); QualifierDefinition customQualifier1 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); QualifierDefinition customQualifier2 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); assertThat(directQualifier1.hashCode()).isEqualTo(directQualifier2.hashCode()); - assertThat(differentDirectQualifier1.hashCode()) - .isEqualTo(differentDirectQualifier2.hashCode()); + assertThat(differentDirectQualifier1.hashCode()).isEqualTo(differentDirectQualifier2.hashCode()); assertThat(customQualifier1.hashCode()).isEqualTo(customQualifier2.hashCode()); - assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1) - .isEqualTo(differentDirectQualifier2).isNotEqualTo(directQualifier2); - assertThat(directQualifier1).isEqualTo(directQualifier1) - .isEqualTo(directQualifier2).isNotEqualTo(differentDirectQualifier1); - assertThat(customQualifier1).isEqualTo(customQualifier1) - .isEqualTo(customQualifier2).isNotEqualTo(differentDirectQualifier1); + assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1).isEqualTo(differentDirectQualifier2) + .isNotEqualTo(directQualifier2); + assertThat(directQualifier1).isEqualTo(directQualifier1).isEqualTo(directQualifier2) + .isNotEqualTo(differentDirectQualifier1); + assertThat(customQualifier1).isEqualTo(customQualifier1).isEqualTo(customQualifier2) + .isNotEqualTo(differentDirectQualifier1); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java index 6208873ddd6..53eff34a0f7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java @@ -54,8 +54,7 @@ public class SpyBeanOnContextHierarchyIntegrationTests { ApplicationContext context = this.childConfig.getContext(); ApplicationContext parentContext = context.getParent(); assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1); - assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)) - .hasSize(0); + assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1); assertThat(context.getBean(ExampleService.class)).isNotNull(); @@ -75,8 +74,7 @@ public class SpyBeanOnContextHierarchyIntegrationTests { private ApplicationContext context; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java index a3c34a47df4..2484cdf1b5a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java @@ -61,8 +61,7 @@ public class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { @Test public void onlyQualifiedBeanIsReplaced() { assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); - ExampleService anotherService = this.applicationContext.getBean("anotherService", - ExampleService.class); + ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); assertThat(anotherService.greeting()).isEqualTo("Another"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java index 18e4f05943f..d7808285b37 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java @@ -57,8 +57,7 @@ public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { } @Configuration(proxyBeanMethods = false) - @Import({ ExampleGenericServiceCaller.class, - SimpleExampleIntegerGenericService.class }) + @Import({ ExampleGenericServiceCaller.class, SimpleExampleIntegerGenericService.class }) static class SpyBeanOnTestFieldForExistingBeanConfig { @Bean diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java index 089a0005959..4b5d093e68d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java @@ -50,8 +50,8 @@ public class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegration @Test public void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say two"); - assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings() - .getMockName().toString()).isEqualTo("two"); + assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings().getMockName().toString()) + .isEqualTo("two"); verify(this.spy).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java index 5e2740b65dd..b2a4b6ee2aa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java @@ -55,8 +55,7 @@ public class SpyBeanWithAopProxyAndNotProxyTargetAwareTests { public void verifyShouldUseProxyTarget() { this.dateService.getDate(false); verify(this.dateService, times(1)).getDate(false); - assertThatExceptionOfType(UnfinishedVerificationException.class) - .isThrownBy(() -> reset(this.dateService)); + assertThatExceptionOfType(UnfinishedVerificationException.class).isThrownBy(() -> reset(this.dateService)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java index 9ddc11b9bca..1c425a692bb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java @@ -45,8 +45,7 @@ public class SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests { public void testSpying() { MockingDetails mockingDetails = Mockito.mockingDetails(this.spy); assertThat(mockingDetails.isSpy()).isTrue(); - assertThat(mockingDetails.getMockCreationSettings().getMockName().toString()) - .isEqualTo("two"); + assertThat(mockingDetails.getMockCreationSettings().getMockName().toString()).isEqualTo("two"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java index 62593dff5a9..e65abb3f96c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java @@ -37,20 +37,17 @@ import static org.mockito.Mockito.mock; */ public class SpyDefinitionTests { - private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType - .forClass(RealExampleService.class); + private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType.forClass(RealExampleService.class); @Test public void classToSpyMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) .withMessageContaining("TypeToSpy must not be null"); } @Test public void createWithDefaults() { - SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, - null); + SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, null); assertThat(definition.getName()).isNull(); assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); assertThat(definition.getReset()).isEqualTo(MockReset.AFTER); @@ -61,8 +58,7 @@ public class SpyDefinitionTests { @Test public void createExplicit() { QualifierDefinition qualifier = mock(QualifierDefinition.class); - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, false, qualifier); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, false, qualifier); assertThat(definition.getName()).isEqualTo("name"); assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE); @@ -72,11 +68,9 @@ public class SpyDefinitionTests { @Test public void createSpy() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); RealExampleService spy = definition.createSpy(new RealExampleService("hello")); - MockCreationSettings settings = Mockito.mockingDetails(spy) - .getMockCreationSettings(); + MockCreationSettings settings = Mockito.mockingDetails(spy).getMockCreationSettings(); assertThat(spy).isInstanceOf(ExampleService.class); assertThat(settings.getMockName().toString()).isEqualTo("name"); assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.CALLS_REAL_METHODS); @@ -85,25 +79,21 @@ public class SpyDefinitionTests { @Test public void createSpyWhenNullInstanceShouldThrowException() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null)) .withMessageContaining("Instance must not be null"); } @Test public void createSpyWhenWrongInstanceShouldThrowException() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); - assertThatIllegalArgumentException() - .isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); + assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) .withMessageContaining("must be an instance of"); } @Test public void createSpyTwice() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); Object instance = new RealExampleService("hello"); instance = definition.createSpy(instance); definition.createSpy(instance); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java index 3f8ef732b01..6ef1f381f5e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class ExampleGenericServiceCaller { } public String sayGreeting() { - return "I say " + this.integerService.greeting() + " " - + this.stringService.greeting(); + return "I say " + this.integerService.greeting() + " " + this.stringService.greeting(); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java index ad3cbfd5746..e4ffa8ed061 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ public class ExampleGenericStringServiceCaller { private final ExampleGenericService stringService; - public ExampleGenericStringServiceCaller( - ExampleGenericService stringService) { + public ExampleGenericStringServiceCaller(ExampleGenericService stringService) { this.stringService = stringService; } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java index 86c5bd3d7bd..29b9e2365b0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,7 @@ package org.springframework.boot.test.mock.mockito.example; * * @author Phillip Webb */ -public class SimpleExampleIntegerGenericService - implements ExampleGenericService { +public class SimpleExampleIntegerGenericService implements ExampleGenericService { @Override public Integer greeting() { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java index 65f24be418e..88b16817fa9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java @@ -64,8 +64,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { testResource("/inpublic", "/public"); } - private void testResource(String path, String expectedLocation) - throws MalformedURLException { + private void testResource(String path, String expectedLocation) throws MalformedURLException { URL resource = this.servletContext.getResource(path); assertThat(resource).isNotNull(); assertThat(resource.getPath()).contains(expectedLocation); @@ -74,8 +73,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { // gh-2654 @Test public void getRootUrlExistsAndIsEmpty() throws Exception { - SpringBootMockServletContext context = new SpringBootMockServletContext( - "src/test/doesntexist") { + SpringBootMockServletContext context = new SpringBootMockServletContext("src/test/doesntexist") { @Override protected String getResourceLocation(String path) { // Don't include the Spring Boot defaults for this test @@ -86,8 +84,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { assertThat(resource).isNotEqualTo(nullValue()); File file = new File(URLDecoder.decode(resource.getPath(), "UTF-8")); assertThat(file).exists().isDirectory(); - String[] contents = file - .list((dir, name) -> !(".".equals(name) || "..".equals(name))); + String[] contents = file.list((dir, name) -> !(".".equals(name) || "..".equals(name))); assertThat(contents).isNotEqualTo(nullValue()); assertThat(contents.length).isEqualTo(0); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java index 4d8ff8db3c1..68d9774e5f5 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java @@ -43,8 +43,7 @@ public class OutputCaptureTests { System.out.println("Hello"); this.outputCapture.reset(); System.out.println("World"); - assertThat(this.outputCapture.toString()).doesNotContain("Hello") - .contains("World"); + assertThat(this.outputCapture.toString()).doesNotContain("Hello").contains("World"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputCaptureTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputCaptureTests.java index 3bb471196cf..ea3a5e3143c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputCaptureTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputCaptureTests.java @@ -80,8 +80,7 @@ class OutputCaptureTests { @Test void popWhenEmptyThrowsException() { - assertThatExceptionOfType(NoSuchElementException.class) - .isThrownBy(this.output::pop); + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(this.output::pop); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputExtensionExtendWithTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputExtensionExtendWithTests.java index a021da6f47c..2cae90d697e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputExtensionExtendWithTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputExtensionExtendWithTests.java @@ -40,8 +40,7 @@ class OutputExtensionExtendWithTests { void captureShouldReturnAllCapturedOutput(CapturedOutput output) { System.out.println("Hello World"); System.err.println("Error!!!"); - assertThat(output).contains("Before all").contains("Hello World") - .contains("Error!!!"); + assertThat(output).contains("Before all").contains("Hello World").contains("Error!!!"); } static class BeforeAllExtension implements BeforeAllCallback { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java index 0625b73f2ad..6c0af1308ab 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java @@ -46,8 +46,7 @@ public class ApplicationContextTestUtilsTests { @Test public void closeContextAndParent() { ConfigurableApplicationContext mock = mock(ConfigurableApplicationContext.class); - ConfigurableApplicationContext parent = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext parent = mock(ConfigurableApplicationContext.class); given(mock.getParent()).willReturn(parent); given(parent.getParent()).willReturn(null); ApplicationContextTestUtils.closeAll(mock); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java index 94efa8ab17c..d23d6467c9e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java @@ -39,8 +39,7 @@ public class TestPropertyValuesTests { @Test public void applyToEnvironmentShouldAttachConfigurationPropertySource() { TestPropertyValues.of("foo.bar=baz").applyTo(this.environment); - PropertySource source = this.environment.getPropertySources() - .get("configurationProperties"); + PropertySource source = this.environment.getPropertySources().get("configurationProperties"); assertThat(source).isNotNull(); } @@ -53,12 +52,10 @@ public class TestPropertyValuesTests { @Test public void applyToSystemPropertySource() { - TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, - Type.SYSTEM_ENVIRONMENT); + TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); - assertThat(this.environment.getPropertySources().contains( - "test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) - .isTrue(); + assertThat(this.environment.getPropertySources() + .contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue(); } @Test @@ -70,10 +67,8 @@ public class TestPropertyValuesTests { @Test public void applyToExistingNameAndDifferentTypeShouldOverrideExistingOne() { - TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, - Type.MAP, "other"); - TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, - Type.SYSTEM_ENVIRONMENT, "other"); + TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP, "other"); + TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT, "other"); assertThat(this.environment.getPropertySources().get("other")) .isInstanceOf(SystemEnvironmentPropertySource.class); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); @@ -82,8 +77,7 @@ public class TestPropertyValuesTests { @Test public void applyToExistingNameAndSameTypeShouldMerge() { - TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, - Type.MAP); + TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP); TestPropertyValues.of("foo.bar=new").applyTo(this.environment, Type.MAP); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("new"); assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi"); @@ -91,8 +85,8 @@ public class TestPropertyValuesTests { @Test public void andShouldChainAndAddSingleKeyValue() { - TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing") - .applyTo(this.environment, Type.MAP); + TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing").applyTo(this.environment, + Type.MAP); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz"); assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi"); assertThat(this.environment.getProperty("bling.blah")).isEqualTo("bing"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java index d97ae9773b8..0bd059bd36e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java @@ -76,8 +76,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { this.environment.setProperty("management.server.port", "8081"); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("8080"); - assertThat(this.environment.getProperty("management.server.port")) - .isEqualTo("8081"); + assertThat(this.environment.getProperty("management.server.port")).isEqualTo("8081"); } @Test @@ -85,8 +84,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { addTestPropertySource("0", "8080"); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); - assertThat(this.environment.getProperty("management.server.port")) - .isEqualTo("8080"); + assertThat(this.environment.getProperty("management.server.port")).isEqualTo("8080"); } @Test @@ -115,8 +113,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { // mgmt port is 8080 which means it's on the same port as main server since that // is null in app properties addTestPropertySource("0", null); - this.propertySources.addLast(new MapPropertySource("other", - Collections.singletonMap("management.server.port", "8080"))); + this.propertySources + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo(""); @@ -125,8 +123,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { @Test public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() { addTestPropertySource("0", null); - this.propertySources.addLast(new MapPropertySource("other", - Collections.singletonMap("management.server.port", "8081"))); + this.propertySources + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -135,19 +133,18 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { @Test public void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() { addTestPropertySource("0", null); - this.propertySources.addLast(new MapPropertySource("other", - Collections.singletonMap("management.server.port", "-1"))); + this.propertySources + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); - assertThat(this.environment.getProperty("management.server.port")) - .isEqualTo("-1"); + assertThat(this.environment.getProperty("management.server.port")).isEqualTo("-1"); } @Test public void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() { addTestPropertySource("0", null); - this.propertySources.addLast(new MapPropertySource("other", - Collections.singletonMap("management.server.port", 8081))); + this.propertySources + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -159,8 +156,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { MapPropertySource testPropertySource = (MapPropertySource) this.propertySources .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); testPropertySource.getSource().put("port", "9090"); - this.propertySources.addLast(new MapPropertySource("other", - Collections.singletonMap("management.server.port", "${port}"))); + this.propertySources + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -169,10 +166,10 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { @Test public void postProcessWhenManagementServerPortPlaceholderAbsentShouldFail() { addTestPropertySource("0", null); - this.propertySources.addLast(new MapPropertySource("other", - Collections.singletonMap("management.server.port", "${port}"))); - assertThatIllegalArgumentException().isThrownBy( - () -> this.postProcessor.postProcessEnvironment(this.environment, null)) + this.propertySources + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); } @@ -198,8 +195,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { source.put("server.port", "${port}"); source.put("management.server.port", "9090"); this.propertySources.addLast(new MapPropertySource("other", source)); - assertThatIllegalArgumentException().isThrownBy( - () -> this.postProcessor.postProcessEnvironment(this.environment, null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index 140cc247d60..a6aca9e317c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java @@ -42,23 +42,21 @@ public class LocalHostUriTemplateHandlerTests { @Test public void createWhenEnvironmentIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostUriTemplateHandler(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostUriTemplateHandler(null)) .withMessageContaining("Environment must not be null"); } @Test public void createWhenSchemeIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) .withMessageContaining("Scheme must not be null"); } @Test public void createWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), - "http", null)) + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null)) .withMessageContaining("Handler must not be null"); } @@ -66,24 +64,21 @@ public class LocalHostUriTemplateHandlerTests { public void getRootUriShouldUseLocalServerPort() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "1234"); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - environment); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:1234"); } @Test public void getRootUriWhenLocalServerPortMissingShouldUsePort8080() { MockEnvironment environment = new MockEnvironment(); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - environment); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080"); } @Test public void getRootUriUsesCustomScheme() { MockEnvironment environment = new MockEnvironment(); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, - "https"); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https"); assertThat(handler.getRootUri()).isEqualTo("https://localhost:8080"); } @@ -91,8 +86,7 @@ public class LocalHostUriTemplateHandlerTests { public void getRootUriShouldUseContextPath() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("server.servlet.context-path", "/foo"); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - environment); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080/foo"); } @@ -102,10 +96,8 @@ public class LocalHostUriTemplateHandlerTests { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); Map uriVariables = new HashMap<>(); URI uri = URI.create("https://www.example.com"); - given(uriTemplateHandler.expand("https://localhost:8080/", uriVariables)) - .willReturn(uri); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, - "https", uriTemplateHandler); + given(uriTemplateHandler.expand("https://localhost:8080/", uriVariables)).willReturn(uri); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https", uriTemplateHandler); assertThat(handler.expand("/", uriVariables)).isEqualTo(uri); verify(uriTemplateHandler).expand("https://localhost:8080/", uriVariables); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java index 6854a85a43b..98ecf641847 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java @@ -55,8 +55,7 @@ public class MockServerRestTemplateCustomizerTests { @Test public void createWhenExpectationManagerClassIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new MockServerRestTemplateCustomizer(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new MockServerRestTemplateCustomizer(null)) .withMessageContaining("ExpectationManager must not be null"); } @@ -73,8 +72,7 @@ public class MockServerRestTemplateCustomizerTests { public void detectRootUriShouldDefaultToTrue() { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer( UnorderedRequestExpectationManager.class); - customizer.customize( - new RestTemplateBuilder().rootUri("https://example.com").build()); + customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(customizer.getServer()).extracting("expectationManager") .hasAtLeastOneElementOfType(RootUriRequestExpectationManager.class); } @@ -82,8 +80,7 @@ public class MockServerRestTemplateCustomizerTests { @Test public void setDetectRootUriShouldDisableRootUriDetection() { this.customizer.setDetectRootUri(false); - this.customizer.customize( - new RestTemplateBuilder().rootUri("https://example.com").build()); + this.customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(this.customizer.getServer()).extracting("expectationManager") .hasAtLeastOneElementOfType(SimpleRequestExpectationManager.class); @@ -100,9 +97,8 @@ public class MockServerRestTemplateCustomizerTests { @Test public void getServerWhenNoServersAreBoundShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.customizer::getServer) - .withMessageContaining( - "Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); + .withMessageContaining("Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); } @Test @@ -110,17 +106,15 @@ public class MockServerRestTemplateCustomizerTests { this.customizer.customize(new RestTemplate()); this.customizer.customize(new RestTemplate()); assertThatIllegalStateException().isThrownBy(this.customizer::getServer) - .withMessageContaining( - "Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); + .withMessageContaining("Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); } @Test public void getServerWhenSingleServerIsBoundShouldReturnServer() { RestTemplate template = new RestTemplate(); this.customizer.customize(template); - assertThat(this.customizer.getServer()) - .isEqualTo(this.customizer.getServer(template)); + assertThat(this.customizer.getServer()).isEqualTo(this.customizer.getServer(template)); } @Test @@ -130,8 +124,7 @@ public class MockServerRestTemplateCustomizerTests { this.customizer.customize(template1); this.customizer.customize(template2); assertThat(this.customizer.getServer(template1)).isNotNull(); - assertThat(this.customizer.getServer(template2)).isNotNull() - .isNotSameAs(this.customizer.getServer(template1)); + assertThat(this.customizer.getServer(template2)).isNotNull().isNotSameAs(this.customizer.getServer(template1)); } @Test @@ -158,14 +151,10 @@ public class MockServerRestTemplateCustomizerTests { RestTemplate template2 = new RestTemplate(); this.customizer.customize(template1); this.customizer.customize(template2); - RequestExpectationManager manager1 = this.customizer.getExpectationManagers() - .get(template1); - RequestExpectationManager manager2 = this.customizer.getExpectationManagers() - .get(template2); - assertThat(this.customizer.getServer(template1)).extracting("expectationManager") - .containsOnly(manager1); - assertThat(this.customizer.getServer(template2)).extracting("expectationManager") - .containsOnly(manager2); + RequestExpectationManager manager1 = this.customizer.getExpectationManagers().get(template1); + RequestExpectationManager manager2 = this.customizer.getExpectationManagers().get(template2); + assertThat(this.customizer.getServer(template1)).extracting("expectationManager").containsOnly(manager1); + assertThat(this.customizer.getServer(template2)).extracting("expectationManager").containsOnly(manager2); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java index 09e2069498d..4f0ecc7bc8b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ class NoTestRestTemplateBeanChecker implements ImportSelector, BeanFactoryAware @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory) beanFactory, TestRestTemplate.class)).isEmpty(); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, + TestRestTemplate.class)).isEmpty(); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java index 23140882bbb..c4765df68eb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java @@ -69,16 +69,13 @@ public class RootUriRequestExpectationManagerTests { @Test public void createWhenRootUriIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> new RootUriRequestExpectationManager(null, this.delegate)) + assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(null, this.delegate)) .withMessageContaining("RootUri must not be null"); } @Test public void createWhenExpectationManagerIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null)) .withMessageContaining("ExpectationManager must not be null"); } @@ -91,8 +88,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() - throws Exception { + public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI("https://spring.io/test")); this.manager.validateRequest(request); @@ -100,8 +96,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() - throws Exception { + public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); this.manager.validateRequest(request); @@ -112,17 +107,13 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() - throws Exception { + public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); given(this.delegate.validateRequest(any(ClientHttpRequest.class))) - .willThrow(new AssertionError( - "Request URI expected: was:")); - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> this.manager.validateRequest(request)) - .withMessageContaining( - "Request URI expected:"); + .willThrow(new AssertionError("Request URI expected: was:")); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.manager.validateRequest(request)) + .withMessageContaining("Request URI expected:"); } @Test @@ -134,24 +125,22 @@ public class RootUriRequestExpectationManagerTests { @Test public void bindToShouldReturnMockRestServiceServer() { RestTemplate restTemplate = new RestTemplateBuilder().build(); - MockRestServiceServer bound = RootUriRequestExpectationManager - .bindTo(restTemplate); + MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate); assertThat(bound).isNotNull(); } @Test public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() { RestTemplate restTemplate = new RestTemplateBuilder().build(); - MockRestServiceServer bound = RootUriRequestExpectationManager - .bindTo(restTemplate, this.delegate); + MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate, this.delegate); assertThat(bound).isNotNull(); } @Test public void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager() { RestTemplate restTemplate = new RestTemplateBuilder().rootUri(this.uri).build(); - RequestExpectationManager actual = RootUriRequestExpectationManager - .forRestTemplate(restTemplate, this.delegate); + RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate, + this.delegate); assertThat(actual).isInstanceOf(RootUriRequestExpectationManager.class); assertThat(actual).extracting("rootUri").containsExactly(this.uri); } @@ -159,32 +148,27 @@ public class RootUriRequestExpectationManagerTests { @Test public void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager() { RestTemplate restTemplate = new RestTemplateBuilder().build(); - RequestExpectationManager actual = RootUriRequestExpectationManager - .forRestTemplate(restTemplate, this.delegate); + RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate, + this.delegate); assertThat(actual).isSameAs(this.delegate); } @Test public void boundRestTemplateShouldPrefixRootUri() { - RestTemplate restTemplate = new RestTemplateBuilder() - .rootUri("https://example.com").build(); - MockRestServiceServer server = RootUriRequestExpectationManager - .bindTo(restTemplate); + RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build(); + MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); restTemplate.getForEntity("/hello", String.class); } @Test public void boundRestTemplateWhenUrlIncludesDomainShouldNotPrefixRootUri() { - RestTemplate restTemplate = new RestTemplateBuilder() - .rootUri("https://example.com").build(); - MockRestServiceServer server = RootUriRequestExpectationManager - .bindTo(restTemplate); + RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build(); + MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> restTemplate.getForEntity("https://spring.io/hello", String.class)) - .withMessageContaining( - "expected: but was:"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> restTemplate.getForEntity("https://spring.io/hello", String.class)) + .withMessageContaining("expected: but was:"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java index 1053e68c715..42807606eb1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java @@ -68,8 +68,7 @@ public class TestRestTemplateContextCustomizerIntegrationTests { static class TestServlet extends GenericServlet { @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { try (PrintWriter writer = response.getWriter()) { writer.println("hello"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java index f1d628e3600..990c18d6185 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java @@ -41,16 +41,11 @@ public class TestRestTemplateContextCustomizerTests { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void whenContextIsNotABeanDefinitionRegistryTestRestTemplateIsRegistered() { - new ApplicationContextRunner(TestApplicationContext::new) - .withInitializer((context) -> { - MergedContextConfiguration configuration = mock( - MergedContextConfiguration.class); - given(configuration.getTestClass()) - .willReturn((Class) TestClass.class); - new TestRestTemplateContextCustomizer().customizeContext(context, - configuration); - }).run((context) -> assertThat(context) - .hasSingleBean(TestRestTemplate.class)); + new ApplicationContextRunner(TestApplicationContext::new).withInitializer((context) -> { + MergedContextConfiguration configuration = mock(MergedContextConfiguration.class); + given(configuration.getTestClass()).willReturn((Class) TestClass.class); + new TestRestTemplateContextCustomizer().customizeContext(context, configuration); + }).run((context) -> assertThat(context).hasSingleBean(TestRestTemplate.class)); } @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @@ -72,8 +67,7 @@ public class TestRestTemplateContextCustomizerTests { } @Override - public ConfigurableListableBeanFactory getBeanFactory() - throws IllegalStateException { + public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException { return this.beanFactory; } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java index ebc0d644ec4..08f2f14fe0b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java @@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@SpringBootTest( - classes = TestRestTemplateContextCustomizerWithFactoryBeanTests.TestClassWithFactoryBean.class, +@SpringBootTest(classes = TestRestTemplateContextCustomizerWithFactoryBeanTests.TestClassWithFactoryBean.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class TestRestTemplateContextCustomizerWithFactoryBeanTests { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java index 92ab01159c0..4e143cd23b0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java @@ -74,8 +74,7 @@ public class TestRestTemplateContextCustomizerWithOverrideIntegrationTests { static class TestServlet extends GenericServlet { @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { try (PrintWriter writer = response.getWriter()) { writer.println("hello"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index e2feb5b0099..e4d7c0745bc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -85,8 +85,7 @@ public class TestRestTemplateTests { @Test public void doNotReplaceCustomRequestFactory() { - RestTemplateBuilder builder = new RestTemplateBuilder() - .requestFactory(OkHttp3ClientHttpRequestFactory.class); + RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(OkHttp3ClientHttpRequestFactory.class); TestRestTemplate testRestTemplate = new TestRestTemplate(builder); assertThat(testRestTemplate.getRestTemplate().getRequestFactory()) .isInstanceOf(OkHttp3ClientHttpRequestFactory.class); @@ -95,15 +94,11 @@ public class TestRestTemplateTests { @Test public void useTheSameRequestFactoryClassWithBasicAuth() { OkHttp3ClientHttpRequestFactory customFactory = new OkHttp3ClientHttpRequestFactory(); - RestTemplateBuilder builder = new RestTemplateBuilder() - .requestFactory(() -> customFactory); - TestRestTemplate testRestTemplate = new TestRestTemplate(builder) - .withBasicAuth("test", "test"); + RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(() -> customFactory); + TestRestTemplate testRestTemplate = new TestRestTemplate(builder).withBasicAuth("test", "test"); RestTemplate restTemplate = testRestTemplate.getRestTemplate(); - assertThat(restTemplate.getRequestFactory().getClass().getName()) - .contains("BasicAuth"); - Object requestFactory = ReflectionTestUtils - .getField(restTemplate.getRequestFactory(), "requestFactory"); + assertThat(restTemplate.getRequestFactory().getClass().getName()).contains("BasicAuth"); + Object requestFactory = ReflectionTestUtils.getField(restTemplate.getRequestFactory(), "requestFactory"); assertThat(requestFactory).isEqualTo(customFactory).hasSameClassAs(customFactory); } @@ -118,8 +113,7 @@ public class TestRestTemplateTests { public void getRootUriRootUriSetViaLocalHostUriTemplateHandler() { String rootUri = "https://example.com"; TestRestTemplate template = new TestRestTemplate(); - LocalHostUriTemplateHandler templateHandler = mock( - LocalHostUriTemplateHandler.class); + LocalHostUriTemplateHandler templateHandler = mock(LocalHostUriTemplateHandler.class); given(templateHandler.getRootUri()).willReturn(rootUri); template.setUriTemplateHandler(templateHandler); assertThat(template.getRootUri()).isEqualTo(rootUri); @@ -132,16 +126,14 @@ public class TestRestTemplateTests { @Test public void authenticated() { - RestTemplate restTemplate = new TestRestTemplate("user", "password") - .getRestTemplate(); + RestTemplate restTemplate = new TestRestTemplate("user", "password").getRestTemplate(); ClientHttpRequestFactory factory = restTemplate.getRequestFactory(); assertThat(factory.getClass().getName()).contains("BasicAuthentication"); } @Test public void options() { - TestRestTemplate template = new TestRestTemplate( - HttpClientOption.ENABLE_REDIRECTS); + TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template .getRestTemplate().getRequestFactory(); RequestConfig config = factory.getRequestConfig(); @@ -151,10 +143,8 @@ public class TestRestTemplateTests { @Test public void restOperationsAreAvailable() { RestTemplate delegate = mock(RestTemplate.class); - given(delegate.getRequestFactory()) - .willReturn(new SimpleClientHttpRequestFactory()); - given(delegate.getUriTemplateHandler()) - .willReturn(new DefaultUriBuilderFactory()); + given(delegate.getRequestFactory()).willReturn(new SimpleClientHttpRequestFactory()); + given(delegate.getUriTemplateHandler()).willReturn(new DefaultUriBuilderFactory()); RestTemplateBuilder builder = mock(RestTemplateBuilder.class); given(builder.build()).willReturn(delegate); TestRestTemplate restTemplate = new TestRestTemplate(builder); @@ -162,14 +152,13 @@ public class TestRestTemplateTests { @Override public void doWith(Method method) throws IllegalArgumentException { - Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, - method.getName(), method.getParameterTypes()); + Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, method.getName(), + method.getParameterTypes()); assertThat(equivalent).as("Method %s not found", method).isNotNull(); assertThat(Modifier.isPublic(equivalent.getModifiers())) .as("Method %s should have been public", equivalent).isTrue(); try { - equivalent.invoke(restTemplate, - mockArguments(method.getParameterTypes())); + equivalent.invoke(restTemplate, mockArguments(method.getParameterTypes())); } catch (Exception ex) { throw new IllegalStateException(ex); @@ -215,36 +204,29 @@ public class TestRestTemplateTests { public void withBasicAuthAddsBasicAuthClientFactoryWhenNotAlreadyPresent() { TestRestTemplate original = new TestRestTemplate(); TestRestTemplate basicAuth = original.withBasicAuth("user", "password"); - assertThat(getConverterClasses(original)) - .containsExactlyElementsOf(getConverterClasses(basicAuth)); - assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName()) - .contains("BasicAuth"); - assertThat(ReflectionTestUtils.getField( - basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) - .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); + assertThat(getConverterClasses(original)).containsExactlyElementsOf(getConverterClasses(basicAuth)); + assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName()).contains("BasicAuth"); + assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) + .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); assertThat(basicAuth.getRestTemplate().getInterceptors()).isEmpty(); assertBasicAuthorizationCredentials(basicAuth, "user", "password"); } @Test public void withBasicAuthReplacesBasicAuthClientFactoryWhenAlreadyPresent() { - TestRestTemplate original = new TestRestTemplate("foo", "bar") - .withBasicAuth("replace", "replace"); + TestRestTemplate original = new TestRestTemplate("foo", "bar").withBasicAuth("replace", "replace"); TestRestTemplate basicAuth = original.withBasicAuth("user", "password"); - assertThat(getConverterClasses(basicAuth)) - .containsExactlyElementsOf(getConverterClasses(original)); - assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName()) - .contains("BasicAuth"); - assertThat(ReflectionTestUtils.getField( - basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) - .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); + assertThat(getConverterClasses(basicAuth)).containsExactlyElementsOf(getConverterClasses(original)); + assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName()).contains("BasicAuth"); + assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) + .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); assertThat(basicAuth.getRestTemplate().getInterceptors()).isEmpty(); assertBasicAuthorizationCredentials(basicAuth, "user", "password"); } private List> getConverterClasses(TestRestTemplate testRestTemplate) { - return testRestTemplate.getRestTemplate().getMessageConverters().stream() - .map(Object::getClass).collect(Collectors.toList()); + return testRestTemplate.getRestTemplate().getMessageConverters().stream().map(Object::getClass) + .collect(Collectors.toList()); } @Test @@ -252,11 +234,9 @@ public class TestRestTemplateTests { TestRestTemplate originalTemplate = new TestRestTemplate("foo", "bar"); ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); originalTemplate.getRestTemplate().setErrorHandler(errorHandler); - TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", - "password"); - assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()) - .isInstanceOf(Class.forName( - "org.springframework.boot.test.web.client.TestRestTemplate$NoOpResponseErrorHandler")); + TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password"); + assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()).isInstanceOf( + Class.forName("org.springframework.boot.test.web.client.TestRestTemplate$NoOpResponseErrorHandler")); } @Test @@ -265,55 +245,47 @@ public class TestRestTemplateTests { } @Test - public void exchangeWithRequestEntityAndClassHandlesRelativeUris() - throws IOException { + public void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .exchange(new RequestEntity(HttpMethod.GET, relativeUri), - String.class)); + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), String.class)); } @Test - public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() - throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .exchange(new RequestEntity(HttpMethod.GET, relativeUri), - new ParameterizedTypeReference() { - })); + public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange( + new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { + })); } @Test public void exchangeHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling( - (testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, - HttpMethod.GET, new HttpEntity<>(new byte[0]), String.class)); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, + HttpMethod.GET, new HttpEntity<>(new byte[0]), String.class)); } @Test - public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() - throws IOException { - verifyRelativeUriHandling( - (testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, - HttpMethod.GET, new HttpEntity<>(new byte[0]), - new ParameterizedTypeReference() { - })); + public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException { + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, + HttpMethod.GET, new HttpEntity<>(new byte[0]), new ParameterizedTypeReference() { + })); } @Test public void executeHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .execute(relativeUri, HttpMethod.GET, null, null)); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.execute(relativeUri, HttpMethod.GET, null, null)); } @Test public void getForEntityHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .getForEntity(relativeUri, String.class)); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.getForEntity(relativeUri, String.class)); } @Test public void getForObjectHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .getForObject(relativeUri, String.class)); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.getForObject(relativeUri, String.class)); } @Test @@ -328,59 +300,51 @@ public class TestRestTemplateTests { @Test public void patchForObjectHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .patchForObject(relativeUri, "hello", String.class)); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.patchForObject(relativeUri, "hello", String.class)); } @Test public void postForEntityHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .postForEntity(relativeUri, "hello", String.class)); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.postForEntity(relativeUri, "hello", String.class)); } @Test public void postForLocationHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .postForLocation(relativeUri, "hello")); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.postForLocation(relativeUri, "hello")); } @Test public void postForObjectHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .postForObject(relativeUri, "hello", String.class)); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.postForObject(relativeUri, "hello", String.class)); } @Test public void putHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .put(relativeUri, "hello")); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.put(relativeUri, "hello")); } - private void verifyRelativeUriHandling(TestRestTemplateCallback callback) - throws IOException { + private void verifyRelativeUriHandling(TestRestTemplateCallback callback) throws IOException { ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class); MockClientHttpRequest request = new MockClientHttpRequest(); request.setResponse(new MockClientHttpResponse(new byte[0], HttpStatus.OK)); - URI absoluteUri = URI - .create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D"); - given(requestFactory.createRequest(eq(absoluteUri), any(HttpMethod.class))) - .willReturn(request); + URI absoluteUri = URI.create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D"); + given(requestFactory.createRequest(eq(absoluteUri), any(HttpMethod.class))).willReturn(request); TestRestTemplate template = new TestRestTemplate(); template.getRestTemplate().setRequestFactory(requestFactory); - LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler( - new MockEnvironment()); + LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler(new MockEnvironment()); template.setUriTemplateHandler(uriTemplateHandler); - callback.doWithTestRestTemplate(template, - URI.create("/a/b/c.txt?param=%7Bsomething%7D")); + callback.doWithTestRestTemplate(template, URI.create("/a/b/c.txt?param=%7Bsomething%7D")); verify(requestFactory).createRequest(eq(absoluteUri), any(HttpMethod.class)); } - private void assertBasicAuthorizationCredentials(TestRestTemplate testRestTemplate, - String username, String password) { - ClientHttpRequestFactory requestFactory = testRestTemplate.getRestTemplate() - .getRequestFactory(); - Object authentication = ReflectionTestUtils.getField(requestFactory, - "authentication"); + private void assertBasicAuthorizationCredentials(TestRestTemplate testRestTemplate, String username, + String password) { + ClientHttpRequestFactory requestFactory = testRestTemplate.getRestTemplate().getRequestFactory(); + Object authentication = ReflectionTestUtils.getField(requestFactory, "authentication"); assertThat(authentication).hasFieldOrPropertyWithValue("username", username); assertThat(authentication).hasFieldOrPropertyWithValue("password", password); @@ -398,8 +362,7 @@ public class TestRestTemplateTests { } @Override - public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) - throws IOException { + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { return null; } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java index f21acec3979..d5b514e1121 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java @@ -55,8 +55,7 @@ public class LocalHostWebClientTests { @Test public void createWhenEnvironmentIsNullWillThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebClient(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null)) .withMessageContaining("Environment must not be null"); } @@ -68,13 +67,11 @@ public class LocalHostWebClientTests { client.setWebConnection(connection); client.getPage("/test"); verify(connection).getResponse(this.requestCaptor.capture()); - assertThat(this.requestCaptor.getValue().getUrl()) - .isEqualTo(new URL("http://localhost:8080/test")); + assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8080/test")); } @Test - public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() - throws Exception { + public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "8181"); WebClient client = new LocalHostWebClient(environment); @@ -82,8 +79,7 @@ public class LocalHostWebClientTests { client.setWebConnection(connection); client.getPage("/test"); verify(connection).getResponse(this.requestCaptor.capture()); - assertThat(this.requestCaptor.getValue().getUrl()) - .isEqualTo(new URL("http://localhost:8181/test")); + assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8181/test")); } private WebConnection mockConnection() throws IOException { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java index 3d438db477b..52e78017283 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java @@ -58,23 +58,20 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { @Test public void createWhenEnvironmentIsNullWillThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null)) .withMessageContaining("Environment must not be null"); } @Test public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true)) + assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true)) .withMessageContaining("Environment must not be null"); } @Test public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, - BrowserVersion.CHROME)) + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME)) .withMessageContaining("Environment must not be null"); } @@ -83,38 +80,33 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { Capabilities capabilities = mock(Capabilities.class); given(capabilities.getBrowserName()).willReturn("htmlunit"); given(capabilities.getVersion()).willReturn("chrome"); - assertThatIllegalArgumentException().isThrownBy( - () -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) .withMessageContaining("Environment must not be null"); } @Test public void getWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception { MockEnvironment environment = new MockEnvironment(); - LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver( - environment); + LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); - verify(this.webClient).getPage(any(WebWindow.class), - requestToUrl(new URL("http://localhost:8080/test"))); + verify(this.webClient).getPage(any(WebWindow.class), requestToUrl(new URL("http://localhost:8080/test"))); } @Test public void getWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "8181"); - LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver( - environment); + LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); - verify(this.webClient).getPage(any(WebWindow.class), - requestToUrl(new URL("http://localhost:8181/test"))); + verify(this.webClient).getPage(any(WebWindow.class), requestToUrl(new URL("http://localhost:8181/test"))); } private WebRequest requestToUrl(URL url) { return argThat(new WebRequestUrlArgumentMatcher(url)); } - public class TestLocalHostWebConnectionHtmlUnitDriver - extends LocalHostWebConnectionHtmlUnitDriver { + public class TestLocalHostWebConnectionHtmlUnitDriver extends LocalHostWebConnectionHtmlUnitDriver { public TestLocalHostWebConnectionHtmlUnitDriver(Environment environment) { super(environment); @@ -127,8 +119,7 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { } - private static final class WebRequestUrlArgumentMatcher - implements ArgumentMatcher { + private static final class WebRequestUrlArgumentMatcher implements ArgumentMatcher { private final URL expectedUrl; diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java index bd6b9f4ba92..82f74ee8215 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ class NoWebTestClientBeanChecker implements ImportSelector, BeanFactoryAware { @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory) beanFactory, WebTestClient.class)).isEmpty(); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, + WebTestClient.class)).isEmpty(); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java index c0f57eb0163..16d679a0143 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java @@ -39,8 +39,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Phillip Webb */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.main.web-application-type=reactive") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") @DirtiesContext public class WebTestClientContextCustomizerIntegrationTests { @@ -49,8 +48,7 @@ public class WebTestClientContextCustomizerIntegrationTests { @Test public void test() { - this.webTestClient.get().uri("/").exchange().expectBody(String.class) - .isEqualTo("hello"); + this.webTestClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("hello"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java index acc9d040cd6..f2213f5c758 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java @@ -43,8 +43,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.main.web-application-type=reactive") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") @DirtiesContext public class WebTestClientContextCustomizerWithOverrideIntegrationTests { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java b/spring-boot-project/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java index 64c047cdfc4..cabd3fc1377 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,7 @@ public class FindMainClass extends Task { if (!StringUtils.hasText(mainClass)) { mainClass = findMainClass(); if (!StringUtils.hasText(mainClass)) { - throw new BuildException( - "Could not determine main class given @classesRoot " - + this.classesRoot); + throw new BuildException("Could not determine main class given @classesRoot " + this.classesRoot); } } handle(mainClass); @@ -63,17 +61,14 @@ public class FindMainClass extends Task { private String findMainClass() { if (this.classesRoot == null) { - throw new BuildException( - "one of @mainClass or @classesRoot must be specified"); + throw new BuildException("one of @mainClass or @classesRoot must be specified"); } if (!this.classesRoot.exists()) { - throw new BuildException( - "@classesRoot " + this.classesRoot + " does not exist"); + throw new BuildException("@classesRoot " + this.classesRoot + " does not exist"); } try { if (this.classesRoot.isDirectory()) { - return MainClassFinder.findSingleMainClass(this.classesRoot, - SPRING_BOOT_APPLICATION_CLASS_NAME); + return MainClassFinder.findSingleMainClass(this.classesRoot, SPRING_BOOT_APPLICATION_CLASS_NAME); } return MainClassFinder.findSingleMainClass(new JarFile(this.classesRoot), "/", SPRING_BOOT_APPLICATION_CLASS_NAME); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java index d16c8173b44..2190c3953e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ import javax.tools.StandardLocation; "org.springframework.boot.autoconfigure.AutoConfigureOrder" }) public class AutoConfigureAnnotationProcessor extends AbstractProcessor { - protected static final String PROPERTIES_PATH = "META-INF/" - + "spring-autoconfigure-metadata.properties"; + protected static final String PROPERTIES_PATH = "META-INF/" + "spring-autoconfigure-metadata.properties"; private final Map annotations; @@ -79,30 +78,23 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } protected void addAnnotations(Map annotations) { - annotations.put("Configuration", - "org.springframework.context.annotation.Configuration"); - annotations.put("ConditionalOnClass", - "org.springframework.boot.autoconfigure.condition.ConditionalOnClass"); - annotations.put("ConditionalOnBean", - "org.springframework.boot.autoconfigure.condition.ConditionalOnBean"); + annotations.put("Configuration", "org.springframework.context.annotation.Configuration"); + annotations.put("ConditionalOnClass", "org.springframework.boot.autoconfigure.condition.ConditionalOnClass"); + annotations.put("ConditionalOnBean", "org.springframework.boot.autoconfigure.condition.ConditionalOnBean"); annotations.put("ConditionalOnSingleCandidate", "org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate"); annotations.put("ConditionalOnWebApplication", "org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication"); - annotations.put("AutoConfigureBefore", - "org.springframework.boot.autoconfigure.AutoConfigureBefore"); - annotations.put("AutoConfigureAfter", - "org.springframework.boot.autoconfigure.AutoConfigureAfter"); - annotations.put("AutoConfigureOrder", - "org.springframework.boot.autoconfigure.AutoConfigureOrder"); + annotations.put("AutoConfigureBefore", "org.springframework.boot.autoconfigure.AutoConfigureBefore"); + annotations.put("AutoConfigureAfter", "org.springframework.boot.autoconfigure.AutoConfigureAfter"); + annotations.put("AutoConfigureOrder", "org.springframework.boot.autoconfigure.AutoConfigureOrder"); } private void addValueExtractors(Map attributes) { attributes.put("Configuration", ValueExtractor.allFrom("value")); attributes.put("ConditionalOnClass", new OnClassConditionValueExtractor()); attributes.put("ConditionalOnBean", new OnBeanConditionValueExtractor()); - attributes.put("ConditionalOnSingleCandidate", - new OnBeanConditionValueExtractor()); + attributes.put("ConditionalOnSingleCandidate", new OnBeanConditionValueExtractor()); attributes.put("ConditionalOnWebApplication", ValueExtractor.allFrom("type")); attributes.put("AutoConfigureBefore", ValueExtractor.allFrom("value", "name")); attributes.put("AutoConfigureAfter", ValueExtractor.allFrom("value", "name")); @@ -115,8 +107,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } @Override - public boolean process(Set annotations, - RoundEnvironment roundEnv) { + public boolean process(Set annotations, RoundEnvironment roundEnv) { for (Map.Entry entry : this.annotations.entrySet()) { process(roundEnv, entry.getKey(), entry.getValue()); } @@ -131,36 +122,30 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { return false; } - private void process(RoundEnvironment roundEnv, String propertyKey, - String annotationName) { - TypeElement annotationType = this.processingEnv.getElementUtils() - .getTypeElement(annotationName); + private void process(RoundEnvironment roundEnv, String propertyKey, String annotationName) { + TypeElement annotationType = this.processingEnv.getElementUtils().getTypeElement(annotationName); if (annotationType != null) { for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) { Element enclosingElement = element.getEnclosingElement(); - if (enclosingElement != null - && enclosingElement.getKind() == ElementKind.PACKAGE) { + if (enclosingElement != null && enclosingElement.getKind() == ElementKind.PACKAGE) { processElement(element, propertyKey, annotationName); } } } } - private void processElement(Element element, String propertyKey, - String annotationName) { + private void processElement(Element element, String propertyKey, String annotationName) { try { String qualifiedName = Elements.getQualifiedName(element); AnnotationMirror annotation = getAnnotation(element, annotationName); if (qualifiedName != null && annotation != null) { List values = getValues(propertyKey, annotation); - this.properties.put(qualifiedName + "." + propertyKey, - toCommaDelimitedString(values)); + this.properties.put(qualifiedName + "." + propertyKey, toCommaDelimitedString(values)); this.properties.put(qualifiedName, ""); } } catch (Exception ex) { - throw new IllegalStateException( - "Error processing configuration meta-data on " + element, ex); + throw new IllegalStateException("Error processing configuration meta-data on " + element, ex); } } @@ -194,8 +179,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { private void writeProperties() throws IOException { if (!this.properties.isEmpty()) { - FileObject file = this.processingEnv.getFiler() - .createResource(StandardLocation.CLASS_OUTPUT, "", PROPERTIES_PATH); + FileObject file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", + PROPERTIES_PATH); try (OutputStream outputStream = file.openOutputStream()) { this.properties.store(outputStream, null); } @@ -263,8 +248,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { @Override public List getValues(AnnotationMirror annotation) { Map attributes = new LinkedHashMap<>(); - annotation.getElementValues().forEach((key, value) -> attributes - .put(key.getSimpleName().toString(), value)); + annotation.getElementValues() + .forEach((key, value) -> attributes.put(key.getSimpleName().toString(), value)); if (attributes.containsKey("name")) { return Collections.emptyList(); } @@ -290,8 +275,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } private int compare(Object o1, Object o2) { - return Comparator.comparing(this::isSpringClass) - .thenComparing(String.CASE_INSENSITIVE_ORDER) + return Comparator.comparing(this::isSpringClass).thenComparing(String.CASE_INSENSITIVE_ORDER) .compare(o1.toString(), o2.toString()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java index b303408c7f8..1d421033baf 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ final class Elements { TypeElement enclosingElement = getEnclosingTypeElement(element.asType()); if (enclosingElement != null) { return getQualifiedName(enclosingElement) + "$" - + ((DeclaredType) element.asType()).asElement().getSimpleName() - .toString(); + + ((DeclaredType) element.asType()).asElement().getSimpleName().toString(); } if (element instanceof TypeElement) { return ((TypeElement) element).getQualifiedName().toString(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java index 25e4be75286..c498b6f6189 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,31 +52,22 @@ public class AutoConfigureAnnotationProcessorTests { Properties properties = compile(TestClassConfiguration.class); assertThat(properties).hasSize(6); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.ConditionalOnClass", + "org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnClass", "java.io.InputStream,org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration$Nested,org.springframework.foo"); assertThat(properties) - .containsKey("org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration"); - assertThat(properties) - .containsKey("org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.Configuration"); - assertThat(properties) - .doesNotContainKey("org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration$Nested"); + .containsKey("org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration"); + assertThat(properties).containsKey( + "org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.Configuration"); + assertThat(properties).doesNotContainKey( + "org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration$Nested"); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.ConditionalOnBean", + "org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnBean", "java.io.OutputStream"); - assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.ConditionalOnSingleCandidate", - "java.io.OutputStream"); - assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.ConditionalOnWebApplication", - "SERVLET"); + assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor." + + "TestClassConfiguration.ConditionalOnSingleCandidate", "java.io.OutputStream"); + assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor." + + "TestClassConfiguration.ConditionalOnWebApplication", "SERVLET"); } @Test @@ -93,38 +84,29 @@ public class AutoConfigureAnnotationProcessorTests { Properties properties = compile(TestMethodConfiguration.class); List matching = new ArrayList<>(); for (Object key : properties.keySet()) { - if (key.toString().startsWith( - "org.springframework.boot.autoconfigureprocessor.TestMethodConfiguration")) { + if (key.toString().startsWith("org.springframework.boot.autoconfigureprocessor.TestMethodConfiguration")) { matching.add(key.toString()); } } assertThat(matching).hasSize(2) - .contains("org.springframework.boot.autoconfigureprocessor." - + "TestMethodConfiguration") - .contains("org.springframework.boot.autoconfigureprocessor." - + "TestMethodConfiguration.Configuration"); + .contains("org.springframework.boot.autoconfigureprocessor." + "TestMethodConfiguration") + .contains("org.springframework.boot.autoconfigureprocessor." + "TestMethodConfiguration.Configuration"); } @Test public void annotatedClassWithOrder() throws Exception { Properties properties = compile(TestOrderedClassConfiguration.class); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.ConditionalOnClass", + "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.ConditionalOnClass", "java.io.InputStream,java.io.OutputStream"); + assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor." + + "TestOrderedClassConfiguration.AutoConfigureBefore", "test.before1,test.before2"); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.AutoConfigureBefore", - "test.before1,test.before2"); - assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.AutoConfigureAfter", + "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.AutoConfigureAfter", "java.io.ObjectInputStream"); - assertThat(properties) - .containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.AutoConfigureOrder", - "123"); + assertThat(properties).containsEntry( + "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.AutoConfigureOrder", + "123"); } private Properties compile(Class... types) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java index 152f2ce5674..556fb978282 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import javax.annotation.processing.SupportedAnnotationTypes; * * @author Madhura Bhave */ -@SupportedAnnotationTypes({ - "org.springframework.boot.autoconfigureprocessor.TestConfiguration", +@SupportedAnnotationTypes({ "org.springframework.boot.autoconfigureprocessor.TestConfiguration", "org.springframework.boot.autoconfigureprocessor.TestConditionalOnClass", "org.springframework.boot.autoconfigure.condition.TestConditionalOnBean", "org.springframework.boot.autoconfigure.condition.TestConditionalOnSingleCandidate", @@ -38,8 +37,7 @@ import javax.annotation.processing.SupportedAnnotationTypes; "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureBefore", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureAfter", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureOrder" }) -public class TestAutoConfigureAnnotationProcessor - extends AutoConfigureAnnotationProcessor { +public class TestAutoConfigureAnnotationProcessor extends AutoConfigureAnnotationProcessor { private final File outputLocation; @@ -52,10 +50,8 @@ public class TestAutoConfigureAnnotationProcessor put(annotations, "Configuration", TestConfiguration.class); put(annotations, "ConditionalOnClass", TestConditionalOnClass.class); put(annotations, "ConditionalOnBean", TestConditionalOnBean.class); - put(annotations, "ConditionalOnSingleCandidate", - TestConditionalOnSingleCandidate.class); - put(annotations, "ConditionalOnWebApplication", - TestConditionalOnWebApplication.class); + put(annotations, "ConditionalOnSingleCandidate", TestConditionalOnSingleCandidate.class); + put(annotations, "ConditionalOnWebApplication", TestConditionalOnWebApplication.class); put(annotations, "AutoConfigureBefore", TestAutoConfigureBefore.class); put(annotations, "AutoConfigureAfter", TestAutoConfigureAfter.class); put(annotations, "AutoConfigureOrder", TestAutoConfigureOrder.class); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntry.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntry.java index 75cc9809cb0..e332b20f689 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntry.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntry.java @@ -40,8 +40,7 @@ class CompoundConfigurationTableEntry extends ConfigurationTableEntry { } void addConfigurationKeys(ConfigurationMetadataProperty... properties) { - Stream.of(properties).map(ConfigurationMetadataProperty::getId) - .forEach(this.configurationKeys::add); + Stream.of(properties).map(ConfigurationMetadataProperty::getId).forEach(this.configurationKeys::add); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/ConfigurationMetadataDocumentWriter.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/ConfigurationMetadataDocumentWriter.java index 2c1d6be82f4..deaa895b5e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/ConfigurationMetadataDocumentWriter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/ConfigurationMetadataDocumentWriter.java @@ -38,15 +38,14 @@ import org.springframework.boot.configurationmetadata.ConfigurationMetadataRepos */ public class ConfigurationMetadataDocumentWriter { - public void writeDocument(Path outputDirectory, DocumentOptions options, - InputStream... metadata) throws IOException { + public void writeDocument(Path outputDirectory, DocumentOptions options, InputStream... metadata) + throws IOException { assertValidOutputDirectory(outputDirectory); if (!Files.exists(outputDirectory)) { Files.createDirectory(outputDirectory); } assertMetadata(metadata); - List tables = createConfigTables( - getMetadataProperties(metadata), options); + List tables = createConfigTables(getMetadataProperties(metadata), options); for (ConfigurationTable table : tables) { writeConfigurationTable(table, outputDirectory); } @@ -57,8 +56,7 @@ public class ConfigurationMetadataDocumentWriter { throw new IllegalArgumentException("output path should not be null"); } if (Files.exists(outputDirPath) && !Files.isDirectory(outputDirPath)) { - throw new IllegalArgumentException( - "output path already exists and is not a directory"); + throw new IllegalArgumentException("output path already exists and is not a directory"); } } @@ -68,47 +66,40 @@ public class ConfigurationMetadataDocumentWriter { } } - private Map getMetadataProperties( - InputStream... metadata) throws IOException { + private Map getMetadataProperties(InputStream... metadata) + throws IOException { ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder .create(metadata); return builder.build().getAllProperties(); } - private List createConfigTables( - Map metadataProperties, + private List createConfigTables(Map metadataProperties, DocumentOptions options) { List tables = new ArrayList<>(); - List unmappedKeys = metadataProperties.values().stream() - .filter((property) -> !property.isDeprecated()) + List unmappedKeys = metadataProperties.values().stream().filter((property) -> !property.isDeprecated()) .map(ConfigurationMetadataProperty::getId).collect(Collectors.toList()); - Map overrides = getOverrides( - metadataProperties, unmappedKeys, options); - options.getMetadataSections().forEach( - (id, keyPrefixes) -> tables.add(createConfigTable(metadataProperties, - unmappedKeys, overrides, id, keyPrefixes))); + Map overrides = getOverrides(metadataProperties, unmappedKeys, + options); + options.getMetadataSections().forEach((id, keyPrefixes) -> tables + .add(createConfigTable(metadataProperties, unmappedKeys, overrides, id, keyPrefixes))); if (!unmappedKeys.isEmpty()) { throw new IllegalStateException( - "The following keys were not written to the documentation: " - + String.join(", ", unmappedKeys)); + "The following keys were not written to the documentation: " + String.join(", ", unmappedKeys)); } if (!overrides.isEmpty()) { - throw new IllegalStateException( - "The following keys were not written to the documentation: " - + String.join(", ", overrides.keySet())); + throw new IllegalStateException("The following keys were not written to the documentation: " + + String.join(", ", overrides.keySet())); } return tables; } private Map getOverrides( - Map metadataProperties, - List unmappedKeys, DocumentOptions options) { + Map metadataProperties, List unmappedKeys, + DocumentOptions options) { Map overrides = new HashMap<>(); options.getOverrides().forEach((keyPrefix, description) -> { - CompoundConfigurationTableEntry entry = new CompoundConfigurationTableEntry( - keyPrefix, description); - List matchingKeys = unmappedKeys.stream() - .filter((key) -> key.startsWith(keyPrefix)) + CompoundConfigurationTableEntry entry = new CompoundConfigurationTableEntry(keyPrefix, description); + List matchingKeys = unmappedKeys.stream().filter((key) -> key.startsWith(keyPrefix)) .collect(Collectors.toList()); for (String matchingKey : matchingKeys) { entry.addConfigurationKeys(metadataProperties.get(matchingKey)); @@ -119,21 +110,17 @@ public class ConfigurationMetadataDocumentWriter { return overrides; } - private ConfigurationTable createConfigTable( - Map metadataProperties, - List unmappedKeys, - Map overrides, String id, + private ConfigurationTable createConfigTable(Map metadataProperties, + List unmappedKeys, Map overrides, String id, List keyPrefixes) { ConfigurationTable table = new ConfigurationTable(id); for (String keyPrefix : keyPrefixes) { List matchingOverrides = overrides.keySet().stream() - .filter((overrideKey) -> overrideKey.startsWith(keyPrefix)) - .collect(Collectors.toList()); + .filter((overrideKey) -> overrideKey.startsWith(keyPrefix)).collect(Collectors.toList()); matchingOverrides.forEach((match) -> table.addEntry(overrides.remove(match))); } List matchingKeys = unmappedKeys.stream() - .filter((key) -> keyPrefixes.stream().anyMatch(key::startsWith)) - .collect(Collectors.toList()); + .filter((key) -> keyPrefixes.stream().anyMatch(key::startsWith)).collect(Collectors.toList()); for (String matchingKey : matchingKeys) { ConfigurationMetadataProperty property = metadataProperties.get(matchingKey); table.addEntry(new SingleConfigurationTableEntry(property)); @@ -142,8 +129,7 @@ public class ConfigurationMetadataDocumentWriter { return table; } - private void writeConfigurationTable(ConfigurationTable table, Path outputDirectory) - throws IOException { + private void writeConfigurationTable(ConfigurationTable table, Path outputDirectory) throws IOException { Path outputFilePath = outputDirectory.resolve(table.getId() + ".adoc"); Files.deleteIfExists(outputFilePath); Files.createFile(outputFilePath); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/DocumentOptions.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/DocumentOptions.java index 07bae06b7a2..18e5d6cf258 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/DocumentOptions.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/DocumentOptions.java @@ -32,8 +32,7 @@ public final class DocumentOptions { private final Map overrides; - private DocumentOptions(Map> metadataSections, - Map overrides) { + private DocumentOptions(Map> metadataSections, Map overrides) { this.metadataSections = metadataSections; this.overrides = overrides; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntry.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntry.java index 7ee111539d9..e3427a8b824 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntry.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/main/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntry.java @@ -34,8 +34,7 @@ class SingleConfigurationTableEntry extends ConfigurationTableEntry { SingleConfigurationTableEntry(ConfigurationMetadataProperty property) { this.key = property.getId(); - if (property.getType() != null - && property.getType().startsWith("java.util.Map")) { + if (property.getType() != null && property.getType().startsWith("java.util.Map")) { this.key += ".*"; } this.description = property.getDescription(); @@ -63,8 +62,7 @@ class SingleConfigurationTableEntry extends ConfigurationTableEntry { private void writeDefaultValue(AsciidocBuilder builder) { String defaultValue = (this.defaultValue != null) ? this.defaultValue : ""; - defaultValue = defaultValue.replace("\\", "\\\\").replace("|", - "{vbar}" + System.lineSeparator()); + defaultValue = defaultValue.replace("\\", "\\\\").replace("|", "{vbar}" + System.lineSeparator()); if (defaultValue.isEmpty()) { builder.appendln("|"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java index ac50091b536..422a6b155e3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java @@ -42,15 +42,14 @@ public class CompoundConfigurationTableEntryTests { ConfigurationMetadataProperty thirdProp = new ConfigurationMetadataProperty(); thirdProp.setId("spring.test.third"); thirdProp.setType("java.lang.String"); - CompoundConfigurationTableEntry entry = new CompoundConfigurationTableEntry( - "spring.test", "This is a description."); + CompoundConfigurationTableEntry entry = new CompoundConfigurationTableEntry("spring.test", + "This is a description."); entry.addConfigurationKeys(firstProp, secondProp, thirdProp); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); assertThat(builder.toString()).isEqualTo( - "|`+spring.test.first+` +" + NEWLINE + "`+spring.test.second+` +" - + NEWLINE + "`+spring.test.third+` +" + NEWLINE + NEWLINE + "|" - + NEWLINE + "|+++This is a description.+++" + NEWLINE); + "|`+spring.test.first+` +" + NEWLINE + "`+spring.test.second+` +" + NEWLINE + "`+spring.test.third+` +" + + NEWLINE + NEWLINE + "|" + NEWLINE + "|+++This is a description.+++" + NEWLINE); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java index 2e80928ff81..735341049a5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java @@ -46,14 +46,11 @@ public class ConfigurationTableTests { second.setType("java.lang.String"); table.addEntry(new SingleConfigurationTableEntry(first)); table.addEntry(new SingleConfigurationTableEntry(second)); - assertThat(table.toAsciidocTable()) - .isEqualTo("[cols=\"1,1,2\", options=\"header\"]" + NEWLINE + "|===" - + NEWLINE + "|Key|Default Value|Description" + NEWLINE + NEWLINE - + "|`+spring.test.other+`" + NEWLINE + "|`+other value+`" - + NEWLINE + "|+++This is another description.+++" + NEWLINE - + NEWLINE + "|`+spring.test.prop+`" + NEWLINE + "|`+something+`" - + NEWLINE + "|+++This is a description.+++" + NEWLINE + NEWLINE - + "|===" + NEWLINE); + assertThat(table.toAsciidocTable()).isEqualTo("[cols=\"1,1,2\", options=\"header\"]" + NEWLINE + "|===" + + NEWLINE + "|Key|Default Value|Description" + NEWLINE + NEWLINE + "|`+spring.test.other+`" + NEWLINE + + "|`+other value+`" + NEWLINE + "|+++This is another description.+++" + NEWLINE + NEWLINE + + "|`+spring.test.prop+`" + NEWLINE + "|`+something+`" + NEWLINE + "|+++This is a description.+++" + + NEWLINE + NEWLINE + "|===" + NEWLINE); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java index 717c075898d..2e9a06de839 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java @@ -41,8 +41,8 @@ public class SingleConfigurationTableEntryTests { SingleConfigurationTableEntry entry = new SingleConfigurationTableEntry(property); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); - assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE - + "|`+something+`" + NEWLINE + "|+++This is a description.+++" + NEWLINE); + assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE + "|`+something+`" + NEWLINE + + "|+++This is a description.+++" + NEWLINE); } @Test @@ -54,8 +54,8 @@ public class SingleConfigurationTableEntryTests { SingleConfigurationTableEntry entry = new SingleConfigurationTableEntry(property); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); - assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE + "|" - + NEWLINE + "|+++This is a description.+++" + NEWLINE); + assertThat(builder.toString()).isEqualTo( + "|`+spring.test.prop+`" + NEWLINE + "|" + NEWLINE + "|+++This is a description.+++" + NEWLINE); } @Test @@ -68,9 +68,8 @@ public class SingleConfigurationTableEntryTests { SingleConfigurationTableEntry entry = new SingleConfigurationTableEntry(property); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); - assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE - + "|`+first{vbar}" + NEWLINE + "second+`" + NEWLINE - + "|+++This is a description.+++" + NEWLINE); + assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE + "|`+first{vbar}" + NEWLINE + + "second+`" + NEWLINE + "|+++This is a description.+++" + NEWLINE); } @Test @@ -83,9 +82,8 @@ public class SingleConfigurationTableEntryTests { SingleConfigurationTableEntry entry = new SingleConfigurationTableEntry(property); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); - assertThat(builder.toString()) - .isEqualTo("|`+spring.test.prop+`" + NEWLINE + "|`+first\\\\second+`" - + NEWLINE + "|+++This is a description.+++" + NEWLINE); + assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE + "|`+first\\\\second+`" + NEWLINE + + "|+++This is a description.+++" + NEWLINE); } @Test @@ -97,8 +95,8 @@ public class SingleConfigurationTableEntryTests { SingleConfigurationTableEntry entry = new SingleConfigurationTableEntry(property); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); - assertThat(builder.toString()).isEqualTo("|`+spring.test.prop.*+`" + NEWLINE + "|" - + NEWLINE + "|+++This is a description.+++" + NEWLINE); + assertThat(builder.toString()).isEqualTo( + "|`+spring.test.prop.*+`" + NEWLINE + "|" + NEWLINE + "|+++This is a description.+++" + NEWLINE); } @Test @@ -112,9 +110,8 @@ public class SingleConfigurationTableEntryTests { SingleConfigurationTableEntry entry = new SingleConfigurationTableEntry(property); AsciidocBuilder builder = new AsciidocBuilder(); entry.write(builder); - assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE - + "|`+first," + NEWLINE + "second," + NEWLINE + "third+`" + NEWLINE - + "|+++This is a description.+++" + NEWLINE); + assertThat(builder.toString()).isEqualTo("|`+spring.test.prop+`" + NEWLINE + "|`+first," + NEWLINE + "second," + + NEWLINE + "third+`" + NEWLINE + "|+++This is a description.+++" + NEWLINE); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java index 9560a308250..9e3abf6fe1a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java @@ -53,8 +53,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @return this builder * @throws IOException in case of I/O errors */ - public ConfigurationMetadataRepositoryJsonBuilder withJsonResource( - InputStream inputStream) throws IOException { + public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream) throws IOException { return withJsonResource(inputStream, this.defaultCharset); } @@ -70,8 +69,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @return this builder * @throws IOException in case of I/O errors */ - public ConfigurationMetadataRepositoryJsonBuilder withJsonResource( - InputStream inputStream, Charset charset) throws IOException { + public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream, Charset charset) + throws IOException { if (inputStream == null) { throw new IllegalArgumentException("InputStream must not be null."); } @@ -92,8 +91,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { return result; } - private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) - throws IOException { + private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) throws IOException { try { RawConfigurationMetadata metadata = this.reader.read(in, charset); return create(metadata); @@ -103,16 +101,14 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { } } - private SimpleConfigurationMetadataRepository create( - RawConfigurationMetadata metadata) { + private SimpleConfigurationMetadataRepository create(RawConfigurationMetadata metadata) { SimpleConfigurationMetadataRepository repository = new SimpleConfigurationMetadataRepository(); repository.add(metadata.getSources()); for (ConfigurationMetadataItem item : metadata.getItems()) { ConfigurationMetadataSource source = metadata.getSource(item); repository.add(item, source); } - Map allProperties = repository - .getAllProperties(); + Map allProperties = repository.getAllProperties(); for (ConfigurationMetadataHint hint : metadata.getHints()) { ConfigurationMetadataProperty property = allProperties.get(hint.getId()); if (property != null) { @@ -134,14 +130,12 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { return repository; } - private void addValueHints(ConfigurationMetadataProperty property, - ConfigurationMetadataHint hint) { + private void addValueHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getValueHints().addAll(hint.getValueHints()); property.getHints().getValueProviders().addAll(hint.getValueProviders()); } - private void addMapHints(ConfigurationMetadataProperty property, - ConfigurationMetadataHint hint) { + private void addMapHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getKeyHints().addAll(hint.getValueHints()); property.getHints().getKeyProviders().addAll(hint.getValueProviders()); } @@ -153,8 +147,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. * @throws IOException on error */ - public static ConfigurationMetadataRepositoryJsonBuilder create( - InputStream... inputStreams) throws IOException { + public static ConfigurationMetadataRepositoryJsonBuilder create(InputStream... inputStreams) throws IOException { ConfigurationMetadataRepositoryJsonBuilder builder = create(); for (InputStream inputStream : inputStreams) { builder = builder.withJsonResource(inputStream); @@ -176,8 +169,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @param defaultCharset the default charset to use * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. */ - public static ConfigurationMetadataRepositoryJsonBuilder create( - Charset defaultCharset) { + public static ConfigurationMetadataRepositoryJsonBuilder create(Charset defaultCharset) { return new ConfigurationMetadataRepositoryJsonBuilder(defaultCharset); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java index e915e4e5659..f9bb2eb8184 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,8 +90,8 @@ public class Deprecation implements Serializable { @Override public String toString() { - return "Deprecation{" + "level='" + this.level + '\'' + ", reason='" + this.reason - + '\'' + ", replacement='" + this.replacement + '\'' + '}'; + return "Deprecation{" + "level='" + this.level + '\'' + ", reason='" + this.reason + '\'' + ", replacement='" + + this.replacement + '\'' + '}'; } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java index 606e7d7c0cf..7635891f2ba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ class JsonReader { private final SentenceExtractor sentenceExtractor = new SentenceExtractor(); - public RawConfigurationMetadata read(InputStream in, Charset charset) - throws IOException { + public RawConfigurationMetadata read(InputStream in, Charset charset) throws IOException { try { JSONObject json = readJson(in, charset); List groups = parseAllSources(json); @@ -60,8 +59,7 @@ class JsonReader { } } - private List parseAllSources(JSONObject root) - throws Exception { + private List parseAllSources(JSONObject root) throws Exception { List result = new ArrayList<>(); if (!root.has("groups")) { return result; @@ -74,8 +72,7 @@ class JsonReader { return result; } - private List parseAllItems(JSONObject root) - throws Exception { + private List parseAllItems(JSONObject root) throws Exception { List result = new ArrayList<>(); if (!root.has("properties")) { return result; @@ -88,8 +85,7 @@ class JsonReader { return result; } - private List parseAllHints(JSONObject root) - throws Exception { + private List parseAllHints(JSONObject root) throws Exception { List result = new ArrayList<>(); if (!root.has("hints")) { return result; @@ -139,8 +135,7 @@ class JsonReader { valueHint.setValue(readItemValue(value.get("value"))); String description = value.optString("description", null); valueHint.setDescription(description); - valueHint.setShortDescription( - this.sentenceExtractor.getFirstSentence(description)); + valueHint.setShortDescription(this.sentenceExtractor.getFirstSentence(description)); hint.getValueHints().add(valueHint); } } @@ -155,8 +150,7 @@ class JsonReader { Iterator keys = parameters.keys(); while (keys.hasNext()) { String key = (String) keys.next(); - valueProvider.getParameters().put(key, - readItemValue(parameters.get(key))); + valueProvider.getParameters().put(key, readItemValue(parameters.get(key))); } } hint.getValueProviders().add(valueProvider); @@ -169,13 +163,11 @@ class JsonReader { if (object.has("deprecation")) { JSONObject deprecationJsonObject = object.getJSONObject("deprecation"); Deprecation deprecation = new Deprecation(); - deprecation.setLevel(parseDeprecationLevel( - deprecationJsonObject.optString("level", null))); + deprecation.setLevel(parseDeprecationLevel(deprecationJsonObject.optString("level", null))); String reason = deprecationJsonObject.optString("reason", null); deprecation.setReason(reason); deprecation.setShortReason(this.sentenceExtractor.getFirstSentence(reason)); - deprecation - .setReplacement(deprecationJsonObject.optString("replacement", null)); + deprecation.setReplacement(deprecationJsonObject.optString("replacement", null)); return deprecation; } return object.optBoolean("deprecated") ? new Deprecation() : null; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java index 8317a09baba..4052de5beb7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java @@ -34,8 +34,7 @@ class RawConfigurationMetadata { private final List hints; - RawConfigurationMetadata(List sources, - List items, + RawConfigurationMetadata(List sources, List items, List hints) { this.sources = new ArrayList<>(sources); this.items = new ArrayList<>(items); @@ -56,9 +55,7 @@ class RawConfigurationMetadata { return this.sources.stream() .filter((candidate) -> item.getSourceType().equals(candidate.getType()) && item.getId().startsWith(candidate.getGroupId())) - .max(Comparator - .comparingInt((candidate) -> candidate.getGroupId().length())) - .orElse(null); + .max(Comparator.comparingInt((candidate) -> candidate.getGroupId().length())).orElse(null); } public List getItems() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java index a3e07f4557b..5becb4d6906 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import java.util.Map; * @since 1.3.0 */ @SuppressWarnings("serial") -public class SimpleConfigurationMetadataRepository - implements ConfigurationMetadataRepository, Serializable { +public class SimpleConfigurationMetadataRepository implements ConfigurationMetadataRepository, Serializable { private final Map allGroups = new HashMap<>(); @@ -73,8 +72,7 @@ public class SimpleConfigurationMetadataRepository * @param property the property to add * @param source the source */ - public void add(ConfigurationMetadataProperty property, - ConfigurationMetadataSource source) { + public void add(ConfigurationMetadataProperty property, ConfigurationMetadataSource source) { if (source != null) { putIfAbsent(source.getProperties(), property.getId(), property); } @@ -93,11 +91,9 @@ public class SimpleConfigurationMetadataRepository } else { // Merge properties - group.getProperties().forEach((name, value) -> putIfAbsent( - existingGroup.getProperties(), name, value)); + group.getProperties().forEach((name, value) -> putIfAbsent(existingGroup.getProperties(), name, value)); // Merge sources - group.getSources().forEach((name, - value) -> putIfAbsent(existingGroup.getSources(), name, value)); + group.getSources().forEach((name, value) -> putIfAbsent(existingGroup.getSources(), name, value)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java index 675d1ea1bed..0608fdc51f6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,7 @@ public class ValueHint implements Serializable { @Override public String toString() { - return "ValueHint{" + "value=" + this.value + ", description='" + this.description - + '\'' + '}'; + return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}'; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java index 36bd2c40a81..d6064f877fb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,7 @@ public class ValueProvider implements Serializable { @Override public String toString() { - return "ValueProvider{" + "name='" + this.name + ", parameters=" + this.parameters - + '}'; + return "ValueProvider{" + "name='" + this.name + ", parameters=" + this.parameters + '}'; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java index 4e216fd1f55..46836be95c0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,16 +31,15 @@ import static org.assertj.core.api.Assertions.assertThat; */ public abstract class AbstractConfigurationMetadataTests { - protected void assertSource(ConfigurationMetadataSource actual, String groupId, - String type, String sourceType) { + protected void assertSource(ConfigurationMetadataSource actual, String groupId, String type, String sourceType) { assertThat(actual).isNotNull(); assertThat(actual.getGroupId()).isEqualTo(groupId); assertThat(actual.getType()).isEqualTo(type); assertThat(actual.getSourceType()).isEqualTo(sourceType); } - protected void assertProperty(ConfigurationMetadataProperty actual, String id, - String name, Class type, Object defaultValue) { + protected void assertProperty(ConfigurationMetadataProperty actual, String id, String name, Class type, + Object defaultValue) { assertThat(actual).isNotNull(); assertThat(actual.getId()).isEqualTo(id); assertThat(actual.getName()).isEqualTo(name); @@ -55,8 +54,7 @@ public abstract class AbstractConfigurationMetadataTests { } protected InputStream getInputStreamFor(String name) throws IOException { - Resource r = new ClassPathResource( - "metadata/configuration-metadata-" + name + ".json"); + Resource r = new ClassPathResource("metadata/configuration-metadata-" + name + ".json"); return r.getInputStream(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index c53298f093b..aa496c37cdb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -30,25 +30,21 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Stephane Nicoll */ -public class ConfigurationMetadataRepositoryJsonBuilderTests - extends AbstractConfigurationMetadataTests { +public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests { @Test public void nullResource() throws IOException { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create() - .withJsonResource(null)); + .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null)); } @Test public void simpleRepository() throws IOException { try (InputStream foo = getInputStreamFor("foo")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo).build(); validateFoo(repo); assertThat(repo.getAllGroups()).hasSize(1); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter"); assertThat(repo.getAllProperties()).hasSize(3); } } @@ -56,63 +52,54 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @Test public void hintsOnMaps() throws IOException { try (InputStream map = getInputStreamFor("map")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(map).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(map).build(); validateMap(repo); assertThat(repo.getAllGroups()).hasSize(1); - contains(repo.getAllProperties(), "spring.map.first", "spring.map.second", - "spring.map.keys", "spring.map.values"); + contains(repo.getAllProperties(), "spring.map.first", "spring.map.second", "spring.map.keys", + "spring.map.values"); assertThat(repo.getAllProperties()).hasSize(4); } } @Test public void severalRepositoriesNoConflict() throws IOException { - try (InputStream foo = getInputStreamFor("foo"); - InputStream bar = getInputStreamFor("bar")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo, bar).build(); + try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) { + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, bar).build(); validateFoo(repo); validateBar(repo); assertThat(repo.getAllGroups()).hasSize(2); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.bar.name", "spring.bar.description", - "spring.bar.counter"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.bar.name", "spring.bar.description", "spring.bar.counter"); assertThat(repo.getAllProperties()).hasSize(6); } } @Test public void repositoryWithRoot() throws IOException { - try (InputStream foo = getInputStreamFor("foo"); - InputStream root = getInputStreamFor("root")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo, root).build(); + try (InputStream foo = getInputStreamFor("foo"); InputStream root = getInputStreamFor("root")) { + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, root).build(); validateFoo(repo); assertThat(repo.getAllGroups()).hasSize(2); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.root.name", "spring.root2.name"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.root.name", "spring.root2.name"); assertThat(repo.getAllProperties()).hasSize(5); } } @Test public void severalRepositoriesIdenticalGroups() throws IOException { - try (InputStream foo = getInputStreamFor("foo"); - InputStream foo2 = getInputStreamFor("foo2")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo, foo2).build(); + try (InputStream foo = getInputStreamFor("foo"); InputStream foo2 = getInputStreamFor("foo2")) { + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, foo2).build(); assertThat(repo.getAllGroups()).hasSize(1); ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo"); - contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", - "org.springframework.boot.FooProperties"); + contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", "org.springframework.boot.FooProperties"); assertThat(group.getSources()).hasSize(3); - contains(group.getProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); + contains(group.getProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.foo.enabled", "spring.foo.type"); assertThat(group.getProperties()).hasSize(5); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.foo.enabled", "spring.foo.type"); assertThat(repo.getAllProperties()).hasSize(5); } } @@ -120,8 +107,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @Test public void emptyGroups() throws IOException { try (InputStream in = getInputStreamFor("empty-groups")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(in).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build(); validateEmptyGroup(repo); assertThat(repo.getAllGroups()).hasSize(1); contains(repo.getAllProperties(), "name", "title"); @@ -132,39 +118,28 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @Test public void multiGroups() throws IOException { try (InputStream in = getInputStreamFor("multi-groups")) { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(in).build(); - assertThat(repo.getAllGroups()).containsOnlyKeys("test.group.one.retry", - "test.group.two.retry", "test.group.one.retry.specific"); - ConfigurationMetadataGroup one = repo.getAllGroups() - .get("test.group.one.retry"); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build(); + assertThat(repo.getAllGroups()).containsOnlyKeys("test.group.one.retry", "test.group.two.retry", + "test.group.one.retry.specific"); + ConfigurationMetadataGroup one = repo.getAllGroups().get("test.group.one.retry"); assertThat(one.getSources()).containsOnlyKeys("com.example.Retry"); - assertThat(one.getProperties()) - .containsOnlyKeys("test.group.one.retry.enabled"); - ConfigurationMetadataGroup two = repo.getAllGroups() - .get("test.group.two.retry"); + assertThat(one.getProperties()).containsOnlyKeys("test.group.one.retry.enabled"); + ConfigurationMetadataGroup two = repo.getAllGroups().get("test.group.two.retry"); assertThat(two.getSources()).containsOnlyKeys("com.example.Retry"); - assertThat(two.getProperties()) - .containsOnlyKeys("test.group.two.retry.enabled"); - ConfigurationMetadataGroup oneSpecific = repo.getAllGroups() - .get("test.group.one.retry.specific"); + assertThat(two.getProperties()).containsOnlyKeys("test.group.two.retry.enabled"); + ConfigurationMetadataGroup oneSpecific = repo.getAllGroups().get("test.group.one.retry.specific"); assertThat(oneSpecific.getSources()).containsOnlyKeys("com.example.Retry"); - assertThat(oneSpecific.getProperties()) - .containsOnlyKeys("test.group.one.retry.specific.enabled"); + assertThat(oneSpecific.getProperties()).containsOnlyKeys("test.group.one.retry.specific.enabled"); } } @Test public void builderInstancesAreIsolated() throws IOException { - try (InputStream foo = getInputStreamFor("foo"); - InputStream bar = getInputStreamFor("bar")) { - ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder - .create(); - ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo) - .build(); + try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) { + ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create(); + ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo).build(); validateFoo(firstRepo); - ConfigurationMetadataRepository secondRepo = builder.withJsonResource(bar) - .build(); + ConfigurationMetadataRepository secondRepo = builder.withJsonResource(bar).build(); validateFoo(secondRepo); validateBar(secondRepo); // first repo not impacted by second build @@ -178,78 +153,63 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests private void validateFoo(ConfigurationMetadataRepository repo) { ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo"); - contains(group.getSources(), "org.acme.Foo", - "org.springframework.boot.FooProperties"); + contains(group.getSources(), "org.acme.Foo", "org.springframework.boot.FooProperties"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Foo"); contains(source.getProperties(), "spring.foo.name", "spring.foo.description"); assertThat(source.getProperties()).hasSize(2); - ConfigurationMetadataSource source2 = group.getSources() - .get("org.springframework.boot.FooProperties"); + ConfigurationMetadataSource source2 = group.getSources().get("org.springframework.boot.FooProperties"); contains(source2.getProperties(), "spring.foo.name", "spring.foo.counter"); assertThat(source2.getProperties()).hasSize(2); validatePropertyHints(repo.getAllProperties().get("spring.foo.name"), 0, 0); - validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, - 0); + validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, 0); validatePropertyHints(repo.getAllProperties().get("spring.foo.counter"), 1, 1); } private void validateBar(ConfigurationMetadataRepository repo) { ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.bar"); - contains(group.getSources(), "org.acme.Bar", - "org.springframework.boot.BarProperties"); + contains(group.getSources(), "org.acme.Bar", "org.springframework.boot.BarProperties"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Bar"); contains(source.getProperties(), "spring.bar.name", "spring.bar.description"); assertThat(source.getProperties()).hasSize(2); - ConfigurationMetadataSource source2 = group.getSources() - .get("org.springframework.boot.BarProperties"); + ConfigurationMetadataSource source2 = group.getSources().get("org.springframework.boot.BarProperties"); contains(source2.getProperties(), "spring.bar.name", "spring.bar.counter"); assertThat(source2.getProperties()).hasSize(2); validatePropertyHints(repo.getAllProperties().get("spring.bar.name"), 0, 0); - validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, - 2); + validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, 2); validatePropertyHints(repo.getAllProperties().get("spring.bar.counter"), 0, 0); } private void validateMap(ConfigurationMetadataRepository repo) { ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.map"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Map"); - contains(source.getProperties(), "spring.map.first", "spring.map.second", - "spring.map.keys", "spring.map.values"); + contains(source.getProperties(), "spring.map.first", "spring.map.second", "spring.map.keys", + "spring.map.values"); assertThat(source.getProperties()).hasSize(4); - ConfigurationMetadataProperty first = repo.getAllProperties() - .get("spring.map.first"); + ConfigurationMetadataProperty first = repo.getAllProperties().get("spring.map.first"); assertThat(first.getHints().getKeyHints()).hasSize(2); assertThat(first.getHints().getValueProviders()).hasSize(0); assertThat(first.getHints().getKeyHints().get(0).getValue()).isEqualTo("one"); - assertThat(first.getHints().getKeyHints().get(0).getDescription()) - .isEqualTo("First."); + assertThat(first.getHints().getKeyHints().get(0).getDescription()).isEqualTo("First."); assertThat(first.getHints().getKeyHints().get(1).getValue()).isEqualTo("two"); - assertThat(first.getHints().getKeyHints().get(1).getDescription()) - .isEqualTo("Second."); - ConfigurationMetadataProperty second = repo.getAllProperties() - .get("spring.map.second"); + assertThat(first.getHints().getKeyHints().get(1).getDescription()).isEqualTo("Second."); + ConfigurationMetadataProperty second = repo.getAllProperties().get("spring.map.second"); assertThat(second.getHints().getValueHints()).hasSize(2); assertThat(second.getHints().getValueProviders()).hasSize(0); assertThat(second.getHints().getValueHints().get(0).getValue()).isEqualTo("42"); - assertThat(second.getHints().getValueHints().get(0).getDescription()) - .isEqualTo("Choose me."); + assertThat(second.getHints().getValueHints().get(0).getDescription()).isEqualTo("Choose me."); assertThat(second.getHints().getValueHints().get(1).getValue()).isEqualTo("24"); assertThat(second.getHints().getValueHints().get(1).getDescription()).isNull(); - ConfigurationMetadataProperty keys = repo.getAllProperties() - .get("spring.map.keys"); + ConfigurationMetadataProperty keys = repo.getAllProperties().get("spring.map.keys"); assertThat(keys.getHints().getValueHints()).hasSize(0); assertThat(keys.getHints().getValueProviders()).hasSize(1); assertThat(keys.getHints().getValueProviders().get(0).getName()).isEqualTo("any"); - ConfigurationMetadataProperty values = repo.getAllProperties() - .get("spring.map.values"); + ConfigurationMetadataProperty values = repo.getAllProperties().get("spring.map.values"); assertThat(values.getHints().getValueHints()).hasSize(0); assertThat(values.getHints().getValueProviders()).hasSize(1); - assertThat(values.getHints().getValueProviders().get(0).getName()) - .isEqualTo("handle-as"); - assertThat(values.getHints().getValueProviders().get(0).getParameters()) - .hasSize(1); - assertThat(values.getHints().getValueProviders().get(0).getParameters() - .get("target")).isEqualTo("java.lang.Integer"); + assertThat(values.getHints().getValueProviders().get(0).getName()).isEqualTo("handle-as"); + assertThat(values.getHints().getValueProviders().get(0).getParameters()).hasSize(1); + assertThat(values.getHints().getValueProviders().get(0).getParameters().get("target")) + .isEqualTo("java.lang.Integer"); } private void validateEmptyGroup(ConfigurationMetadataRepository repo) { @@ -265,11 +225,9 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests validatePropertyHints(repo.getAllProperties().get("title"), 0, 0); } - private void validatePropertyHints(ConfigurationMetadataProperty property, - int valueHints, int valueProviders) { + private void validatePropertyHints(ConfigurationMetadataProperty property, int valueHints, int valueProviders) { assertThat(property.getHints().getValueHints().size()).isEqualTo(valueHints); - assertThat(property.getHints().getValueProviders().size()) - .isEqualTo(valueProviders); + assertThat(property.getHints().getValueProviders().size()).isEqualTo(valueProviders); } private void contains(Map source, String... keys) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index 7d9343f76fa..e202e35eaa2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -47,8 +47,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { @Test public void invalidMetadata() throws IOException { - assertThatIllegalStateException().isThrownBy(() -> readFor("invalid")) - .withCauseInstanceOf(JSONException.class); + assertThatIllegalStateException().isThrownBy(() -> readFor("invalid")).withCauseInstanceOf(JSONException.class); } @Test @@ -83,8 +82,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { assertProperty(item, "spring.foo.name", "name", String.class, null); assertItem(item, "org.acme.Foo"); ConfigurationMetadataItem item2 = items.get(1); - assertProperty(item2, "spring.foo.description", "description", String.class, - "FooBar"); + assertProperty(item2, "spring.foo.description", "description", String.class, "FooBar"); assertThat(item2.getDescription()).isEqualTo("Foo description."); assertThat(item2.getShortDescription()).isEqualTo("Foo description."); assertThat(item2.getSourceMethod()).isNull(); @@ -95,16 +93,14 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { assertThat(hint.getValueHints()).hasSize(1); ValueHint valueHint = hint.getValueHints().get(0); assertThat(valueHint.getValue()).isEqualTo(42); - assertThat(valueHint.getDescription()).isEqualTo( - "Because that's the answer to any question, choose it. \nReally."); - assertThat(valueHint.getShortDescription()) - .isEqualTo("Because that's the answer to any question, choose it."); + assertThat(valueHint.getDescription()) + .isEqualTo("Because that's the answer to any question, choose it. \nReally."); + assertThat(valueHint.getShortDescription()).isEqualTo("Because that's the answer to any question, choose it."); assertThat(hint.getValueProviders()).hasSize(1); ValueProvider valueProvider = hint.getValueProviders().get(0); assertThat(valueProvider.getName()).isEqualTo("handle-as"); assertThat(valueProvider.getParameters()).hasSize(1); - assertThat(valueProvider.getParameters().get("target")) - .isEqualTo(Integer.class.getName()); + assertThat(valueProvider.getParameters().get("target")).isEqualTo(Integer.class.getName()); } @Test @@ -127,8 +123,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { ValueProvider valueProvider = hint.getValueProviders().get(0); assertThat(valueProvider.getName()).isEqualTo("handle-as"); assertThat(valueProvider.getParameters()).hasSize(1); - assertThat(valueProvider.getParameters().get("target")) - .isEqualTo(String.class.getName()); + assertThat(valueProvider.getParameters().get("target")).isEqualTo(String.class.getName()); ValueProvider valueProvider2 = hint.getValueProviders().get(1); assertThat(valueProvider2.getName()).isEqualTo("any"); assertThat(valueProvider2.getParameters()).isEmpty(); @@ -154,17 +149,13 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { ConfigurationMetadataItem item = items.get(0); assertProperty(item, "server.port", "server.port", Integer.class, null); assertThat(item.isDeprecated()).isTrue(); - assertThat(item.getDeprecation().getReason()) - .isEqualTo("Server namespace has moved to spring.server"); - assertThat(item.getDeprecation().getShortReason()) - .isEqualTo("Server namespace has moved to spring.server"); - assertThat(item.getDeprecation().getReplacement()) - .isEqualTo("server.spring.port"); + assertThat(item.getDeprecation().getReason()).isEqualTo("Server namespace has moved to spring.server"); + assertThat(item.getDeprecation().getShortReason()).isEqualTo("Server namespace has moved to spring.server"); + assertThat(item.getDeprecation().getReplacement()).isEqualTo("server.spring.port"); assertThat(item.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING); ConfigurationMetadataItem item2 = items.get(1); - assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, - null); + assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, null); assertThat(item2.isDeprecated()).isTrue(); assertThat(item2.getDeprecation().getReason()).isNull(); assertThat(item2.getDeprecation().getShortReason()).isNull(); @@ -172,31 +163,25 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { assertThat(item.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING); ConfigurationMetadataItem item3 = items.get(2); - assertProperty(item3, "spring.server.name", "spring.server.name", String.class, - null); + assertProperty(item3, "spring.server.name", "spring.server.name", String.class, null); assertThat(item3.isDeprecated()).isFalse(); assertThat(item3.getDeprecation()).isNull(); ConfigurationMetadataItem item4 = items.get(3); - assertProperty(item4, "spring.server-name", "spring.server-name", String.class, - null); + assertProperty(item4, "spring.server-name", "spring.server-name", String.class, null); assertThat(item4.isDeprecated()).isTrue(); assertThat(item4.getDeprecation().getReason()).isNull(); assertThat(item2.getDeprecation().getShortReason()).isNull(); - assertThat(item4.getDeprecation().getReplacement()) - .isEqualTo("spring.server.name"); + assertThat(item4.getDeprecation().getReplacement()).isEqualTo("spring.server.name"); assertThat(item4.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.ERROR); ConfigurationMetadataItem item5 = items.get(4); - assertProperty(item5, "spring.server-name2", "spring.server-name2", String.class, - null); + assertProperty(item5, "spring.server-name2", "spring.server-name2", String.class, null); assertThat(item5.isDeprecated()).isTrue(); assertThat(item5.getDeprecation().getReason()).isNull(); assertThat(item2.getDeprecation().getShortReason()).isNull(); - assertThat(item5.getDeprecation().getReplacement()) - .isEqualTo("spring.server.name"); - assertThat(item5.getDeprecation().getLevel()) - .isEqualTo(Deprecation.Level.WARNING); + assertThat(item5.getDeprecation().getReplacement()).isEqualTo("spring.server.name"); + assertThat(item5.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java index 7e12c478d91..f8cc2bf271f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,22 +33,21 @@ public class SentenceExtractorTests { @Test public void extractFirstSentence() { - String sentence = this.extractor - .getFirstSentence("My short " + "description. More stuff."); + String sentence = this.extractor.getFirstSentence("My short " + "description. More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test public void extractFirstSentenceNewLineBeforeDot() { - String sentence = this.extractor.getFirstSentence( - "My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); + String sentence = this.extractor + .getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test public void extractFirstSentenceNewLineBeforeDotWithSpaces() { - String sentence = this.extractor.getFirstSentence( - "My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); + String sentence = this.extractor + .getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } @@ -60,8 +59,7 @@ public class SentenceExtractorTests { @Test public void extractFirstSentenceNoDotMultipleLines() { - String sentence = this.extractor - .getFirstSentence("My short description " + NEW_LINE + " More stuff"); + String sentence = this.extractor.getFirstSentence("My short description " + NEW_LINE + " More stuff"); assertThat(sentence).isEqualTo("My short description"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java index f1d20de69d1..7bd068c1776 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java @@ -73,11 +73,9 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor static final String DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot." + "context.properties.DeprecatedConfigurationProperty"; - static final String DEFAULT_VALUE_ANNOTATION = "org.springframework.boot." - + "context.properties.bind.DefaultValue"; + static final String DEFAULT_VALUE_ANNOTATION = "org.springframework.boot." + "context.properties.bind.DefaultValue"; - static final String ENDPOINT_ANNOTATION = "org.springframework.boot.actuate." - + "endpoint.annotation.Endpoint"; + static final String ENDPOINT_ANNOTATION = "org.springframework.boot.actuate." + "endpoint.annotation.Endpoint"; static final String READ_OPERATION_ANNOTATION = "org.springframework.boot.actuate." + "endpoint.annotation.ReadOperation"; @@ -129,21 +127,16 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor public synchronized void init(ProcessingEnvironment env) { super.init(env); this.metadataStore = new MetadataStore(env); - this.metadataCollector = new MetadataCollector(env, - this.metadataStore.readMetadata()); - this.metadataEnv = new MetadataGenerationEnvironment(env, - configurationPropertiesAnnotation(), - nestedConfigurationPropertyAnnotation(), - deprecatedConfigurationPropertyAnnotation(), defaultValueAnnotation(), - endpointAnnotation(), readOperationAnnotation()); + this.metadataCollector = new MetadataCollector(env, this.metadataStore.readMetadata()); + this.metadataEnv = new MetadataGenerationEnvironment(env, configurationPropertiesAnnotation(), + nestedConfigurationPropertyAnnotation(), deprecatedConfigurationPropertyAnnotation(), + defaultValueAnnotation(), endpointAnnotation(), readOperationAnnotation()); } @Override - public boolean process(Set annotations, - RoundEnvironment roundEnv) { + public boolean process(Set annotations, RoundEnvironment roundEnv) { this.metadataCollector.processing(roundEnv); - TypeElement annotationType = this.metadataEnv - .getConfigurationPropertiesAnnotationElement(); + TypeElement annotationType = this.metadataEnv.getConfigurationPropertiesAnnotationElement(); if (annotationType != null) { // Is @ConfigurationProperties available for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) { processElement(element); @@ -151,8 +144,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } TypeElement endpointType = this.metadataEnv.getEndpointAnnotationElement(); if (endpointType != null) { // Is @Endpoint available - getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType) - .forEach(this::processEndpoint); + getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType).forEach(this::processEndpoint); } if (roundEnv.processingOver()) { try { @@ -165,8 +157,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return false; } - private Map> getElementsAnnotatedOrMetaAnnotatedWith( - RoundEnvironment roundEnv, TypeElement annotation) { + private Map> getElementsAnnotatedOrMetaAnnotatedWith(RoundEnvironment roundEnv, + TypeElement annotation) { DeclaredType annotationType = (DeclaredType) annotation.asType(); Map> result = new LinkedHashMap<>(); for (Element element : roundEnv.getRootElements()) { @@ -181,11 +173,10 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return result; } - private boolean collectElementsAnnotatedOrMetaAnnotatedWith( - DeclaredType annotationType, LinkedList stack) { + private boolean collectElementsAnnotatedOrMetaAnnotatedWith(DeclaredType annotationType, + LinkedList stack) { Element element = stack.peekLast(); - for (AnnotationMirror annotation : this.processingEnv.getElementUtils() - .getAllAnnotationMirrors(element)) { + for (AnnotationMirror annotation : this.processingEnv.getElementUtils().getAllAnnotationMirrors(element)) { Element annotationElement = annotation.getAnnotationType().asElement(); if (!stack.contains(annotationElement)) { stack.addLast(annotationElement); @@ -202,8 +193,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor private void processElement(Element element) { try { - AnnotationMirror annotation = this.metadataEnv - .getConfigurationPropertiesAnnotation(element); + AnnotationMirror annotation = this.metadataEnv.getConfigurationPropertiesAnnotation(element); if (annotation != null) { String prefix = getPrefix(annotation); if (element instanceof TypeElement) { @@ -215,8 +205,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } } catch (Exception ex) { - throw new IllegalStateException( - "Error processing configuration meta-data on " + element, ex); + throw new IllegalStateException("Error processing configuration meta-data on " + element, ex); } } @@ -227,22 +216,16 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } private void processExecutableElement(String prefix, ExecutableElement element) { - if (element.getModifiers().contains(Modifier.PUBLIC) - && (TypeKind.VOID != element.getReturnType().getKind())) { - Element returns = this.processingEnv.getTypeUtils() - .asElement(element.getReturnType()); + if (element.getModifiers().contains(Modifier.PUBLIC) && (TypeKind.VOID != element.getReturnType().getKind())) { + Element returns = this.processingEnv.getTypeUtils().asElement(element.getReturnType()); if (returns instanceof TypeElement) { - ItemMetadata group = ItemMetadata - .newGroup(prefix, - this.metadataEnv.getTypeUtils().getQualifiedName(returns), - this.metadataEnv.getTypeUtils() - .getQualifiedName(element.getEnclosingElement()), - element.toString()); + ItemMetadata group = ItemMetadata.newGroup(prefix, + this.metadataEnv.getTypeUtils().getQualifiedName(returns), + this.metadataEnv.getTypeUtils().getQualifiedName(element.getEnclosingElement()), + element.toString()); if (this.metadataCollector.hasSimilarGroup(group)) { this.processingEnv.getMessager().printMessage(Kind.ERROR, - "Duplicate `@ConfigurationProperties` definition for prefix '" - + prefix + "'", - element); + "Duplicate `@ConfigurationProperties` definition for prefix '" + prefix + "'", element); } else { this.metadataCollector.add(group); @@ -252,67 +235,54 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } } - private void processTypeElement(String prefix, TypeElement element, - ExecutableElement source) { - new PropertyDescriptorResolver(this.metadataEnv).resolve(element, source) - .forEach((descriptor) -> { - this.metadataCollector.add( - descriptor.resolveItemMetadata(prefix, this.metadataEnv)); - if (descriptor.isNested(this.metadataEnv)) { - TypeElement nestedTypeElement = (TypeElement) this.metadataEnv - .getTypeUtils().asElement(descriptor.getType()); - String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, - descriptor.getName()); - processTypeElement(nestedPrefix, nestedTypeElement, source); - } - }); + private void processTypeElement(String prefix, TypeElement element, ExecutableElement source) { + new PropertyDescriptorResolver(this.metadataEnv).resolve(element, source).forEach((descriptor) -> { + this.metadataCollector.add(descriptor.resolveItemMetadata(prefix, this.metadataEnv)); + if (descriptor.isNested(this.metadataEnv)) { + TypeElement nestedTypeElement = (TypeElement) this.metadataEnv.getTypeUtils() + .asElement(descriptor.getType()); + String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, descriptor.getName()); + processTypeElement(nestedPrefix, nestedTypeElement, source); + } + }); } private void processEndpoint(Element element, List annotations) { try { - String annotationName = this.metadataEnv.getTypeUtils() - .getQualifiedName(annotations.get(0)); - AnnotationMirror annotation = this.metadataEnv.getAnnotation(element, - annotationName); + String annotationName = this.metadataEnv.getTypeUtils().getQualifiedName(annotations.get(0)); + AnnotationMirror annotation = this.metadataEnv.getAnnotation(element, annotationName); if (element instanceof TypeElement) { processEndpoint(annotation, (TypeElement) element); } } catch (Exception ex) { - throw new IllegalStateException( - "Error processing configuration meta-data on " + element, ex); + throw new IllegalStateException("Error processing configuration meta-data on " + element, ex); } } private void processEndpoint(AnnotationMirror annotation, TypeElement element) { - Map elementValues = this.metadataEnv - .getAnnotationElementValues(annotation); + Map elementValues = this.metadataEnv.getAnnotationElementValues(annotation); String endpointId = (String) elementValues.get("id"); if (endpointId == null || "".equals(endpointId)) { return; // Can't process that endpoint } - String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.", - endpointId); + String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.", endpointId); Boolean enabledByDefault = (Boolean) elementValues.get("enableByDefault"); String type = this.metadataEnv.getTypeUtils().getQualifiedName(element); this.metadataCollector.add(ItemMetadata.newGroup(endpointKey, type, type, null)); - this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "enabled", - Boolean.class.getName(), type, null, + this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "enabled", Boolean.class.getName(), type, null, String.format("Whether to enable the %s endpoint.", endpointId), (enabledByDefault != null) ? enabledByDefault : true, null)); if (hasMainReadOperation(element)) { - this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, - "cache.time-to-live", Duration.class.getName(), type, null, - "Maximum time that a response can be cached.", "0ms", null)); + this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "cache.time-to-live", + Duration.class.getName(), type, null, "Maximum time that a response can be cached.", "0ms", null)); } } private boolean hasMainReadOperation(TypeElement element) { - for (ExecutableElement method : ElementFilter - .methodsIn(element.getEnclosedElements())) { + for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) { if (this.metadataEnv.getReadOperationAnnotation(method) != null - && (TypeKind.VOID != method.getReturnType().getKind()) - && hasNoOrOptionalParameters(method)) { + && (TypeKind.VOID != method.getReturnType().getKind()) && hasNoOrOptionalParameters(method)) { return true; } } @@ -329,8 +299,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } private String getPrefix(AnnotationMirror annotation) { - Map elementValues = this.metadataEnv - .getAnnotationElementValues(annotation); + Map elementValues = this.metadataEnv.getAnnotationElementValues(annotation); Object prefix = elementValues.get("prefix"); if (prefix != null && !"".equals(prefix)) { return (String) prefix; @@ -352,8 +321,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return null; } - private ConfigurationMetadata mergeAdditionalMetadata( - ConfigurationMetadata metadata) { + private ConfigurationMetadata mergeAdditionalMetadata(ConfigurationMetadata metadata) { try { ConfigurationMetadata merged = new ConfigurationMetadata(metadata); merged.merge(this.metadataStore.readAdditionalMetadata()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java index 0d90046ae36..d2fdc0787d1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java @@ -37,9 +37,8 @@ import javax.tools.Diagnostic.Kind; */ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor { - ConstructorParameterPropertyDescriptor(TypeElement ownerElement, - ExecutableElement factoryMethod, VariableElement source, String name, - TypeMirror type, VariableElement field, ExecutableElement getter, + ConstructorParameterPropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod, + VariableElement source, String name, TypeMirror type, VariableElement field, ExecutableElement getter, ExecutableElement setter) { super(ownerElement, factoryMethod, source, name, type, field, getter, setter); } @@ -60,8 +59,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor defaultValue = getDefaultValue(environment, annotation); if (defaultValue != null) { @@ -70,21 +68,18 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor coerceValue(specificType, value)) + return defaultValue.stream().map((value) -> coerceValue(specificType, value)) .collect(Collectors.toList()); } catch (IllegalArgumentException ex) { - environment.getMessager().printMessage(Kind.ERROR, ex.getMessage(), - element, annotation); + environment.getMessager().printMessage(Kind.ERROR, ex.getMessage(), element, annotation); } } return null; } @SuppressWarnings("unchecked") - private List getDefaultValue(MetadataGenerationEnvironment environment, - AnnotationMirror annotation) { + private List getDefaultValue(MetadataGenerationEnvironment environment, AnnotationMirror annotation) { if (annotation == null) { return null; } @@ -94,24 +89,20 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor { + private static class DefaultValueCoercionTypeVisitor extends TypeKindVisitor8 { private static final DefaultValueCoercionTypeVisitor INSTANCE = new DefaultValueCoercionTypeVisitor(); @@ -120,8 +111,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor 1) { - throw new IllegalArgumentException( - String.format("Invalid character representation '%s'", value)); + throw new IllegalArgumentException(String.format("Invalid character representation '%s'", value)); } return value; } @@ -181,8 +169,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor { + private static class DefaultPrimitiveTypeVisitor extends TypeKindVisitor8 { private static final DefaultPrimitiveTypeVisitor INSTANCE = new DefaultPrimitiveTypeVisitor(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptor.java index 80d21421f3a..4fcf11366b4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptor.java @@ -28,17 +28,15 @@ import javax.lang.model.type.TypeMirror; */ class JavaBeanPropertyDescriptor extends PropertyDescriptor { - JavaBeanPropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod, - ExecutableElement getter, String name, TypeMirror type, VariableElement field, - ExecutableElement setter) { + JavaBeanPropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod, ExecutableElement getter, + String name, TypeMirror type, VariableElement field, ExecutableElement setter) { super(ownerElement, factoryMethod, getter, name, type, field, getter, setter); } @Override protected boolean isProperty(MetadataGenerationEnvironment env) { boolean isCollection = env.getTypeUtils().isCollectionOrMap(getType()); - return !env.isExcluded(getType()) && getGetter() != null - && (getSetter() != null || isCollection); + return !env.isExcluded(getType()) && getGetter() != null && (getSetter() != null || isCollection); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptor.java index 55e9f12cbeb..3086400e776 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptor.java @@ -42,9 +42,8 @@ class LombokPropertyDescriptor extends PropertyDescriptor { private static final String LOMBOK_ACCESS_LEVEL_PUBLIC = "PUBLIC"; - LombokPropertyDescriptor(TypeElement typeElement, ExecutableElement factoryMethod, - VariableElement field, String name, TypeMirror type, ExecutableElement getter, - ExecutableElement setter) { + LombokPropertyDescriptor(TypeElement typeElement, ExecutableElement factoryMethod, VariableElement field, + String name, TypeMirror type, ExecutableElement getter, ExecutableElement setter) { super(typeElement, factoryMethod, field, name, type, field, getter, setter); } @@ -71,10 +70,8 @@ class LombokPropertyDescriptor extends PropertyDescriptor { } @Override - protected ItemDeprecation resolveItemDeprecation( - MetadataGenerationEnvironment environment) { - boolean deprecated = environment.isDeprecated(getField()) - || environment.isDeprecated(getGetter()) + protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) { + boolean deprecated = environment.isDeprecated(getField()) || environment.isDeprecated(getGetter()) || environment.isDeprecated(getFactoryMethod()); return deprecated ? environment.resolveItemDeprecation(getGetter()) : null; } @@ -93,25 +90,20 @@ class LombokPropertyDescriptor extends PropertyDescriptor { * write accessor * @return {@code true} if this field has a public accessor of the specified type */ - private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env, - boolean getter) { - String annotation = (getter ? LOMBOK_GETTER_ANNOTATION - : LOMBOK_SETTER_ANNOTATION); - AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(), - annotation); + private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env, boolean getter) { + String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION); + AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(), annotation); if (lombokMethodAnnotationOnField != null) { return isAccessLevelPublic(env, lombokMethodAnnotationOnField); } - AnnotationMirror lombokMethodAnnotationOnElement = env - .getAnnotation(getOwnerElement(), annotation); + AnnotationMirror lombokMethodAnnotationOnElement = env.getAnnotation(getOwnerElement(), annotation); if (lombokMethodAnnotationOnElement != null) { return isAccessLevelPublic(env, lombokMethodAnnotationOnElement); } return (env.getAnnotation(getOwnerElement(), LOMBOK_DATA_ANNOTATION) != null); } - private boolean isAccessLevelPublic(MetadataGenerationEnvironment env, - AnnotationMirror lombokAnnotation) { + private boolean isAccessLevelPublic(MetadataGenerationEnvironment env, AnnotationMirror lombokAnnotation) { Map values = env.getAnnotationElementValues(lombokAnnotation); Object value = values.get("value"); return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC)); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java index 6896b5c96d6..b9e4f0e3c6f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class MetadataCollector { * @param processingEnvironment the processing environment of the build * @param previousMetadata any previous metadata or {@code null} */ - public MetadataCollector(ProcessingEnvironment processingEnvironment, - ConfigurationMetadata previousMetadata) { + public MetadataCollector(ProcessingEnvironment processingEnvironment, ConfigurationMetadata previousMetadata) { this.processingEnvironment = processingEnvironment; this.previousMetadata = previousMetadata; this.typeUtils = new TypeUtils(processingEnvironment); @@ -82,8 +81,7 @@ public class MetadataCollector { throw new IllegalStateException("item " + metadata + " must be a group"); } for (ItemMetadata existing : this.metadataItems) { - if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) - && existing.getName().equals(metadata.getName()) + if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName()) && existing.getType().equals(metadata.getType())) { return true; } @@ -109,13 +107,11 @@ public class MetadataCollector { private boolean shouldBeMerged(ItemMetadata itemMetadata) { String sourceType = itemMetadata.getSourceType(); - return (sourceType != null && !deletedInCurrentBuild(sourceType) - && !processedInCurrentBuild(sourceType)); + return (sourceType != null && !deletedInCurrentBuild(sourceType) && !processedInCurrentBuild(sourceType)); } private boolean deletedInCurrentBuild(String sourceType) { - return this.processingEnvironment.getElementUtils() - .getTypeElement(sourceType) == null; + return this.processingEnvironment.getElementUtils().getTypeElement(sourceType) == null; } private boolean processedInCurrentBuild(String sourceType) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java index f108830ee08..c44f5c6a047 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java @@ -92,12 +92,9 @@ class MetadataGenerationEnvironment { private final String readOperationAnnotation; - MetadataGenerationEnvironment(ProcessingEnvironment environment, - String configurationPropertiesAnnotation, - String nestedConfigurationPropertyAnnotation, - String deprecatedConfigurationPropertyAnnotation, - String defaultValueAnnotation, String endpointAnnotation, - String readOperationAnnotation) { + MetadataGenerationEnvironment(ProcessingEnvironment environment, String configurationPropertiesAnnotation, + String nestedConfigurationPropertyAnnotation, String deprecatedConfigurationPropertyAnnotation, + String defaultValueAnnotation, String endpointAnnotation, String readOperationAnnotation) { this.typeUtils = new TypeUtils(environment); this.elements = environment.getElementUtils(); this.messager = environment.getMessager(); @@ -135,8 +132,7 @@ class MetadataGenerationEnvironment { * value has been detected */ public Object getFieldDefaultValue(TypeElement type, String name) { - return this.defaultValues.computeIfAbsent(type, this::resolveFieldValues) - .get(name); + return this.defaultValues.computeIfAbsent(type, this::resolveFieldValues).get(name); } public boolean isExcluded(TypeMirror type) { @@ -161,8 +157,7 @@ class MetadataGenerationEnvironment { } public ItemDeprecation resolveItemDeprecation(Element element) { - AnnotationMirror annotation = getAnnotation(element, - this.deprecatedConfigurationPropertyAnnotation); + AnnotationMirror annotation = getAnnotation(element, this.deprecatedConfigurationPropertyAnnotation); String reason = null; String replacement = null; if (annotation != null) { @@ -192,8 +187,8 @@ class MetadataGenerationEnvironment { public Map getAnnotationElementValues(AnnotationMirror annotation) { Map values = new LinkedHashMap<>(); - annotation.getElementValues().forEach((name, value) -> values - .put(name.getSimpleName().toString(), getAnnotationValue(value))); + annotation.getElementValues() + .forEach((name, value) -> values.put(name.getSimpleName().toString(), getAnnotationValue(value))); return values; } @@ -201,8 +196,7 @@ class MetadataGenerationEnvironment { Object value = annotationValue.getValue(); if (value instanceof List) { List values = new ArrayList<>(); - ((List) value) - .forEach((v) -> values.add(((AnnotationValue) v).getValue())); + ((List) value).forEach((v) -> values.add(((AnnotationValue) v).getValue())); return values; } return value; @@ -259,8 +253,7 @@ class MetadataGenerationEnvironment { // continue } Element superType = this.typeUtils.asElement(element.getSuperclass()); - if (superType instanceof TypeElement - && superType.asType().getKind() != TypeKind.NONE) { + if (superType instanceof TypeElement && superType.asType().getKind() != TypeKind.NONE) { resolveFieldValuesFor(values, (TypeElement) superType); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java index 818a133ed4f..b30927d63c6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +65,7 @@ public class MetadataStore { public void writeMetadata(ConfigurationMetadata metadata) throws IOException { if (!metadata.getItems().isEmpty()) { - try (OutputStream outputStream = createMetadataResource() - .openOutputStream()) { + try (OutputStream outputStream = createMetadataResource().openOutputStream()) { new JsonMarshaller().write(metadata, outputStream); } } @@ -85,8 +84,7 @@ public class MetadataStore { } catch (Exception ex) { throw new InvalidConfigurationMetadataException( - "Invalid additional meta-data in '" + METADATA_PATH + "': " - + ex.getMessage(), + "Invalid additional meta-data in '" + METADATA_PATH + "': " + ex.getMessage(), Diagnostic.Kind.ERROR); } finally { @@ -95,30 +93,27 @@ public class MetadataStore { } private FileObject getMetadataResource() throws IOException { - return this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", - METADATA_PATH); + return this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH); } private FileObject createMetadataResource() throws IOException { - return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, - "", METADATA_PATH); + return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH); } private InputStream getAdditionalMetadataStream() throws IOException { // Most build systems will have copied the file to the class output location - FileObject fileObject = this.environment.getFiler() - .getResource(StandardLocation.CLASS_OUTPUT, "", ADDITIONAL_METADATA_PATH); + FileObject fileObject = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", + ADDITIONAL_METADATA_PATH); File file = locateAdditionalMetadataFile(new File(fileObject.toUri())); - return (file.exists() ? new FileInputStream(file) - : fileObject.toUri().toURL().openStream()); + return (file.exists() ? new FileInputStream(file) : fileObject.toUri().toURL().openStream()); } File locateAdditionalMetadataFile(File standardLocation) throws IOException { if (standardLocation.exists()) { return standardLocation; } - String locations = this.environment.getOptions().get( - ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION); + String locations = this.environment.getOptions() + .get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION); if (locations != null) { for (String location : locations.split(",")) { File candidate = new File(location, ADDITIONAL_METADATA_PATH); @@ -127,22 +122,18 @@ public class MetadataStore { } } } - return new File(locateGradleResourcesFolder(standardLocation), - ADDITIONAL_METADATA_PATH); + return new File(locateGradleResourcesFolder(standardLocation), ADDITIONAL_METADATA_PATH); } - private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation) - throws FileNotFoundException { + private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation) throws FileNotFoundException { String path = standardAdditionalMetadataLocation.getPath(); int index = path.lastIndexOf(CLASSES_FOLDER); if (index < 0) { throw new FileNotFoundException(); } String buildFolderPath = path.substring(0, index); - File classOutputLocation = standardAdditionalMetadataLocation.getParentFile() - .getParentFile(); - return new File(buildFolderPath, - RESOURCES_FOLDER + '/' + classOutputLocation.getName()); + File classOutputLocation = standardAdditionalMetadataLocation.getParentFile().getParentFile(); + return new File(buildFolderPath, RESOURCES_FOLDER + '/' + classOutputLocation.getName()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptor.java index 9037278627f..dca485a15fc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptor.java @@ -51,9 +51,8 @@ abstract class PropertyDescriptor { private final ExecutableElement setter; - protected PropertyDescriptor(TypeElement ownerElement, - ExecutableElement factoryMethod, S source, String name, TypeMirror type, - VariableElement field, ExecutableElement getter, ExecutableElement setter) { + protected PropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod, S source, String name, + TypeMirror type, VariableElement field, ExecutableElement getter, ExecutableElement setter) { this.ownerElement = ownerElement; this.factoryMethod = factoryMethod; this.source = source; @@ -98,21 +97,17 @@ abstract class PropertyDescriptor { protected abstract boolean isProperty(MetadataGenerationEnvironment environment); - protected abstract Object resolveDefaultValue( - MetadataGenerationEnvironment environment); + protected abstract Object resolveDefaultValue(MetadataGenerationEnvironment environment); - protected ItemDeprecation resolveItemDeprecation( - MetadataGenerationEnvironment environment) { - boolean deprecated = environment.isDeprecated(getGetter()) - || environment.isDeprecated(getSetter()) + protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) { + boolean deprecated = environment.isDeprecated(getGetter()) || environment.isDeprecated(getSetter()) || environment.isDeprecated(getFactoryMethod()); return deprecated ? environment.resolveItemDeprecation(getGetter()) : null; } protected boolean isNested(MetadataGenerationEnvironment environment) { Element typeElement = environment.getTypeUtils().asElement(getType()); - if (!(typeElement instanceof TypeElement) - || typeElement.getKind() == ElementKind.ENUM) { + if (!(typeElement instanceof TypeElement) || typeElement.getKind() == ElementKind.ENUM) { return false; } if (environment.getConfigurationPropertiesAnnotation(getGetter()) != null) { @@ -127,8 +122,7 @@ abstract class PropertyDescriptor { return isParentTheSame(typeElement, getOwnerElement()); } - public ItemMetadata resolveItemMetadata(String prefix, - MetadataGenerationEnvironment environment) { + public ItemMetadata resolveItemMetadata(String prefix, MetadataGenerationEnvironment environment) { if (isNested(environment)) { return resolveItemMetadataGroup(prefix, environment); } @@ -138,19 +132,17 @@ abstract class PropertyDescriptor { return null; } - private ItemMetadata resolveItemMetadataProperty(String prefix, - MetadataGenerationEnvironment environment) { + private ItemMetadata resolveItemMetadataProperty(String prefix, MetadataGenerationEnvironment environment) { String dataType = resolveType(environment); String ownerType = environment.getTypeUtils().getQualifiedName(getOwnerElement()); String description = resolveDescription(environment); Object defaultValue = resolveDefaultValue(environment); ItemDeprecation deprecation = resolveItemDeprecation(environment); - return ItemMetadata.newProperty(prefix, getName(), dataType, ownerType, null, - description, defaultValue, deprecation); + return ItemMetadata.newProperty(prefix, getName(), dataType, ownerType, null, description, defaultValue, + deprecation); } - private ItemMetadata resolveItemMetadataGroup(String prefix, - MetadataGenerationEnvironment environment) { + private ItemMetadata resolveItemMetadataGroup(String prefix, MetadataGenerationEnvironment environment) { Element propertyElement = environment.getTypeUtils().asElement(getType()); String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, getName()); String dataType = environment.getTypeUtils().getQualifiedName(propertyElement); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java index 2f05356514a..eabaa01372b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java @@ -49,22 +49,19 @@ class PropertyDescriptorResolver { * or {@code null} * @return the candidate properties for metadata generation */ - public Stream> resolve(TypeElement type, - ExecutableElement factoryMethod) { + public Stream> resolve(TypeElement type, ExecutableElement factoryMethod) { TypeElementMembers members = new TypeElementMembers(this.environment, type); ExecutableElement constructor = resolveConstructor(type); if (constructor != null) { - return resolveConstructorProperties(type, factoryMethod, members, - constructor); + return resolveConstructorProperties(type, factoryMethod, members, constructor); } else { return resolveJavaBeanProperties(type, factoryMethod, members); } } - public Stream> resolveConstructorProperties(TypeElement type, - ExecutableElement factoryMethod, TypeElementMembers members, - ExecutableElement constructor) { + public Stream> resolveConstructorProperties(TypeElement type, ExecutableElement factoryMethod, + TypeElementMembers members, ExecutableElement constructor) { Map> candidates = new LinkedHashMap<>(); constructor.getParameters().forEach((parameter) -> { String name = parameter.getSimpleName().toString(); @@ -72,49 +69,44 @@ class PropertyDescriptorResolver { ExecutableElement getter = members.getPublicGetter(name, propertyType); ExecutableElement setter = members.getPublicSetter(name, propertyType); VariableElement field = members.getFields().get(name); - register(candidates, new ConstructorParameterPropertyDescriptor(type, - factoryMethod, parameter, name, propertyType, field, getter, setter)); + register(candidates, new ConstructorParameterPropertyDescriptor(type, factoryMethod, parameter, name, + propertyType, field, getter, setter)); }); return candidates.values().stream(); } - public Stream> resolveJavaBeanProperties(TypeElement type, - ExecutableElement factoryMethod, TypeElementMembers members) { + public Stream> resolveJavaBeanProperties(TypeElement type, ExecutableElement factoryMethod, + TypeElementMembers members) { // First check if we have regular java bean properties there Map> candidates = new LinkedHashMap<>(); members.getPublicGetters().forEach((name, getter) -> { TypeMirror propertyType = getter.getReturnType(); - register(candidates, - new JavaBeanPropertyDescriptor(type, factoryMethod, getter, name, - propertyType, members.getFields().get(name), - members.getPublicSetter(name, propertyType))); + register(candidates, new JavaBeanPropertyDescriptor(type, factoryMethod, getter, name, propertyType, + members.getFields().get(name), members.getPublicSetter(name, propertyType))); }); // Then check for Lombok ones members.getFields().forEach((name, field) -> { TypeMirror propertyType = field.asType(); ExecutableElement getter = members.getPublicGetter(name, propertyType); ExecutableElement setter = members.getPublicSetter(name, propertyType); - register(candidates, new LombokPropertyDescriptor(type, factoryMethod, field, - name, propertyType, getter, setter)); + register(candidates, + new LombokPropertyDescriptor(type, factoryMethod, field, name, propertyType, getter, setter)); }); return candidates.values().stream(); } - private void register(Map> candidates, - PropertyDescriptor descriptor) { + private void register(Map> candidates, PropertyDescriptor descriptor) { if (!candidates.containsKey(descriptor.getName()) && isCandidate(descriptor)) { candidates.put(descriptor.getName(), descriptor); } } private boolean isCandidate(PropertyDescriptor descriptor) { - return descriptor.isProperty(this.environment) - || descriptor.isNested(this.environment); + return descriptor.isProperty(this.environment) || descriptor.isNested(this.environment); } private ExecutableElement resolveConstructor(TypeElement type) { - List constructors = ElementFilter - .constructorsIn(type.getEnclosedElements()); + List constructors = ElementFilter.constructorsIn(type.getEnclosedElements()); if (constructors.size() == 1 && constructors.get(0).getParameters().size() > 0) { return constructors.get(0); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java index 352809e8bfb..537d632285c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java @@ -57,17 +57,14 @@ class TypeElementMembers { } private void process(TypeElement element) { - for (ExecutableElement method : ElementFilter - .methodsIn(element.getEnclosedElements())) { + for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) { processMethod(method); } - for (VariableElement field : ElementFilter - .fieldsIn(element.getEnclosedElements())) { + for (VariableElement field : ElementFilter.fieldsIn(element.getEnclosedElements())) { processField(field); } Element superType = this.env.getTypeUtils().asElement(element.getSuperclass()); - if (superType instanceof TypeElement - && !OBJECT_CLASS_NAME.equals(superType.toString())) { + if (superType instanceof TypeElement && !OBJECT_CLASS_NAME.equals(superType.toString())) { process((TypeElement) superType); } } @@ -80,8 +77,8 @@ class TypeElementMembers { } else if (isSetter(method)) { String propertyName = getAccessorName(name); - List matchingSetters = this.publicSetters - .computeIfAbsent(propertyName, (k) -> new ArrayList<>()); + List matchingSetters = this.publicSetters.computeIfAbsent(propertyName, + (k) -> new ArrayList<>()); TypeMirror paramType = method.getParameters().get(0).asType(); if (getMatchingSetter(matchingSetters, paramType) == null) { matchingSetters.add(method); @@ -92,13 +89,11 @@ class TypeElementMembers { private boolean isPublic(ExecutableElement method) { Set modifiers = method.getModifiers(); - return modifiers.contains(Modifier.PUBLIC) - && !modifiers.contains(Modifier.ABSTRACT) + return modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.ABSTRACT) && !modifiers.contains(Modifier.STATIC); } - private ExecutableElement getMatchingSetter(List candidates, - TypeMirror type) { + private ExecutableElement getMatchingSetter(List candidates, TypeMirror type) { for (ExecutableElement candidate : candidates) { TypeMirror paramType = candidate.getParameters().get(0).asType(); if (this.env.getTypeUtils().isSameType(paramType, type)) { @@ -110,27 +105,24 @@ class TypeElementMembers { private boolean isGetter(ExecutableElement method) { String name = method.getSimpleName().toString(); - return ((name.startsWith("get") && name.length() > 3) - || (name.startsWith("is") && name.length() > 2)) - && method.getParameters().isEmpty() - && (TypeKind.VOID != method.getReturnType().getKind()); + return ((name.startsWith("get") && name.length() > 3) || (name.startsWith("is") && name.length() > 2)) + && method.getParameters().isEmpty() && (TypeKind.VOID != method.getReturnType().getKind()); } private boolean isSetter(ExecutableElement method) { final String name = method.getSimpleName().toString(); - return (name.startsWith("set") && name.length() > 3 - && method.getParameters().size() == 1 && isSetterReturnType(method)); + return (name.startsWith("set") && name.length() > 3 && method.getParameters().size() == 1 + && isSetterReturnType(method)); } private boolean isSetterReturnType(ExecutableElement method) { TypeMirror returnType = method.getReturnType(); - return (TypeKind.VOID == returnType.getKind() || this.env.getTypeUtils() - .isSameType(method.getEnclosingElement().asType(), returnType)); + return (TypeKind.VOID == returnType.getKind() + || this.env.getTypeUtils().isSameType(method.getEnclosingElement().asType(), returnType)); } private String getAccessorName(String methodName) { - String name = methodName.startsWith("is") ? methodName.substring(2) - : methodName.substring(3); + String name = methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); return name; } @@ -157,10 +149,8 @@ class TypeElementMembers { if (this.env.getTypeUtils().isSameType(returnType, type)) { return candidate; } - TypeMirror alternative = this.env.getTypeUtils() - .getWrapperOrPrimitiveFor(type); - if (alternative != null - && this.env.getTypeUtils().isSameType(returnType, alternative)) { + TypeMirror alternative = this.env.getTypeUtils().getWrapperOrPrimitiveFor(type); + if (alternative != null && this.env.getTypeUtils().isSameType(returnType, alternative)) { return candidate; } } @@ -174,8 +164,7 @@ class TypeElementMembers { if (matching != null) { return matching; } - TypeMirror alternative = this.env.getTypeUtils() - .getWrapperOrPrimitiveFor(type); + TypeMirror alternative = this.env.getTypeUtils().getWrapperOrPrimitiveFor(type); if (alternative != null) { return getMatchingSetter(candidates, alternative); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java index 50fdd9b10cb..ead0d26fdaf 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java @@ -70,8 +70,7 @@ class TypeUtils { static { Map primitives = new HashMap<>(); - PRIMITIVE_WRAPPERS.forEach( - (kind, wrapperClass) -> primitives.put(wrapperClass.getName(), kind)); + PRIMITIVE_WRAPPERS.forEach((kind, wrapperClass) -> primitives.put(wrapperClass.getName(), kind)); WRAPPER_TO_PRIMITIVE = primitives; } @@ -95,12 +94,10 @@ class TypeUtils { this.mapType = getDeclaredType(this.types, Map.class, 2); } - private TypeMirror getDeclaredType(Types types, Class typeClass, - int numberOfTypeArgs) { + private TypeMirror getDeclaredType(Types types, Class typeClass, int numberOfTypeArgs) { TypeMirror[] typeArgs = new TypeMirror[numberOfTypeArgs]; Arrays.setAll(typeArgs, (i) -> types.getWildcardType(null, null)); - TypeElement typeElement = this.env.getElementUtils() - .getTypeElement(typeClass.getName()); + TypeElement typeElement = this.env.getElementUtils().getTypeElement(typeClass.getName()); try { return types.getDeclaredType(typeElement, typeArgs); } @@ -156,13 +153,11 @@ class TypeUtils { } private TypeMirror getCollectionElementType(TypeMirror type) { - if (((TypeElement) this.types.asElement(type)).getQualifiedName() - .contentEquals(Collection.class.getName())) { + if (((TypeElement) this.types.asElement(type)).getQualifiedName().contentEquals(Collection.class.getName())) { DeclaredType declaredType = (DeclaredType) type; // raw type, just "Collection" if (declaredType.getTypeArguments().size() == 0) { - return this.types.getDeclaredType(this.env.getElementUtils() - .getTypeElement(Object.class.getName())); + return this.types.getDeclaredType(this.env.getElementUtils().getTypeElement(Object.class.getName())); } // return type argument to Collection<...> return declaredType.getTypeArguments().get(0); @@ -183,8 +178,7 @@ class TypeUtils { } public String getJavaDoc(Element element) { - String javadoc = (element != null) - ? this.env.getElementUtils().getDocComment(element) : null; + String javadoc = (element != null) ? this.env.getElementUtils().getDocComment(element) : null; if (javadoc != null) { javadoc = NEW_LINE_PATTERN.matcher(javadoc).replaceAll("").trim(); } @@ -207,8 +201,7 @@ class TypeUtils { public TypeMirror getWrapperOrPrimitiveFor(TypeMirror typeMirror) { Class candidate = getWrapperFor(typeMirror); if (candidate != null) { - return this.env.getElementUtils().getTypeElement(candidate.getName()) - .asType(); + return this.env.getElementUtils().getTypeElement(candidate.getName()).asType(); } TypeKind primitiveKind = getPrimitiveFor(typeMirror); if (primitiveKind != null) { @@ -256,8 +249,7 @@ class TypeUtils { } } catch (Exception ex) { - this.env.getMessager().printMessage(Kind.WARNING, - "Failed to generated type descriptor for " + type, + this.env.getMessager().printMessage(Kind.WARNING, "Failed to generated type descriptor for " + type, this.types.asElement(type)); } } @@ -266,8 +258,7 @@ class TypeUtils { * A visitor that extracts the fully qualified name of a type, including generic * information. */ - private static class TypeExtractor - extends SimpleTypeVisitor8 { + private static class TypeExtractor extends SimpleTypeVisitor8 { private final Types types; @@ -284,17 +275,15 @@ class TypeUtils { } StringBuilder name = new StringBuilder(); name.append(qualifiedName); - name.append("<").append(type.getTypeArguments().stream() - .map((t) -> visit(t, descriptor)).collect(Collectors.joining(","))) + name.append("<").append( + type.getTypeArguments().stream().map((t) -> visit(t, descriptor)).collect(Collectors.joining(","))) .append(">"); return name.toString(); } - private String determineQualifiedName(DeclaredType type, - TypeElement enclosingElement) { + private String determineQualifiedName(DeclaredType type, TypeElement enclosingElement) { if (enclosingElement != null) { - return getQualifiedName(enclosingElement) + "$" - + type.asElement().getSimpleName(); + return getQualifiedName(enclosingElement) + "$" + type.asElement().getSimpleName(); } return getQualifiedName(type.asElement()); } @@ -355,8 +344,7 @@ class TypeUtils { if (element instanceof TypeElement) { return ((TypeElement) element).getQualifiedName().toString(); } - throw new IllegalStateException( - "Could not extract qualified name from " + element); + throw new IllegalStateException("Could not extract qualified name from " + element); } private TypeElement getEnclosingTypeElement(TypeMirror type) { @@ -388,8 +376,7 @@ class TypeUtils { } public TypeMirror resolveGeneric(String parameterName) { - return this.generics.entrySet().stream() - .filter((e) -> getParameterName(e.getKey()).equals(parameterName)) + return this.generics.entrySet().stream().filter((e) -> getParameterName(e.getKey()).equals(parameterName)) .findFirst().map(Entry::getValue).orElse(null); } @@ -397,8 +384,7 @@ class TypeUtils { if (variable instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) variable; if (this.generics.keySet().stream() - .noneMatch((candidate) -> getParameterName(candidate) - .equals(getParameterName(typeVariable)))) { + .noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(typeVariable)))) { this.generics.put(typeVariable, resolution); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java index a222f3f9556..ec7074aeba9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,20 +31,15 @@ class ExpressionTree extends ReflectionWrapper { private final Class literalTreeType = findClass("com.sun.source.tree.LiteralTree"); - private final Method literalValueMethod = findMethod(this.literalTreeType, - "getValue"); + private final Method literalValueMethod = findMethod(this.literalTreeType, "getValue"); - private final Class methodInvocationTreeType = findClass( - "com.sun.source.tree.MethodInvocationTree"); + private final Class methodInvocationTreeType = findClass("com.sun.source.tree.MethodInvocationTree"); - private final Method methodInvocationArgumentsMethod = findMethod( - this.methodInvocationTreeType, "getArguments"); + private final Method methodInvocationArgumentsMethod = findMethod(this.methodInvocationTreeType, "getArguments"); - private final Class newArrayTreeType = findClass( - "com.sun.source.tree.NewArrayTree"); + private final Class newArrayTreeType = findClass("com.sun.source.tree.NewArrayTree"); - private final Method arrayValueMethod = findMethod(this.newArrayTreeType, - "getInitializers"); + private final Method arrayValueMethod = findMethod(this.newArrayTreeType, "getInitializers"); ExpressionTree(Object instance) { super("com.sun.source.tree.ExpressionTree", instance); @@ -63,8 +58,7 @@ class ExpressionTree extends ReflectionWrapper { public Object getFactoryValue() throws Exception { if (this.methodInvocationTreeType.isAssignableFrom(getInstance().getClass())) { - List arguments = (List) this.methodInvocationArgumentsMethod - .invoke(getInstance()); + List arguments = (List) this.methodInvocationArgumentsMethod.invoke(getInstance()); if (arguments.size() == 1) { return new ExpressionTree(arguments.get(0)).getLiteralValue(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java index 051f31974b3..aedd453b190 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,8 +155,7 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { return defaultValue; } - private Object getValue(ExpressionTree expression, Object defaultValue) - throws Exception { + private Object getValue(ExpressionTree expression, Object defaultValue) throws Exception { Object literalValue = expression.getLiteralValue(); if (literalValue != null) { return literalValue; @@ -187,21 +186,19 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { } private Object getFactoryValue(ExpressionTree expression, Object factoryValue) { - Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF, - DURATION_SUFFIX); + Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF, DURATION_SUFFIX); if (durationValue != null) { return durationValue; } - Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF, - DATA_SIZE_SUFFIX); + Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF, DATA_SIZE_SUFFIX); if (dataSizeValue != null) { return dataSizeValue; } return factoryValue; } - private Object getFactoryValue(ExpressionTree expression, Object factoryValue, - String prefix, Map suffixMapping) { + private Object getFactoryValue(ExpressionTree expression, Object factoryValue, String prefix, + Map suffixMapping) { Object instance = expression.getInstance(); if (instance != null && instance.toString().startsWith(prefix)) { String type = instance.toString(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java index 8d5485d8acb..f5e54fd42a5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ class ReflectionWrapper { } } - protected static Method findMethod(Class type, String name, - Class... parameterTypes) { + protected static Method findMethod(Class type, String name, Class... parameterTypes) { try { return type.getMethod(name, parameterTypes); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java index 1b1d310bb09..631f9aae03d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,22 +30,17 @@ class Tree extends ReflectionWrapper { private final Class treeVisitorType = findClass("com.sun.source.tree.TreeVisitor"); - private final Method acceptMethod = findMethod("accept", this.treeVisitorType, - Object.class); + private final Method acceptMethod = findMethod("accept", this.treeVisitorType, Object.class); - private final Method getClassTreeMembers = findMethod( - findClass("com.sun.source.tree.ClassTree"), "getMembers"); + private final Method getClassTreeMembers = findMethod(findClass("com.sun.source.tree.ClassTree"), "getMembers"); Tree(Object instance) { super("com.sun.source.tree.Tree", instance); } public void accept(TreeVisitor visitor) throws Exception { - this.acceptMethod.invoke(getInstance(), - Proxy.newProxyInstance(getInstance().getClass().getClassLoader(), - new Class[] { this.treeVisitorType }, - new TreeVisitorInvocationHandler(visitor)), - 0); + this.acceptMethod.invoke(getInstance(), Proxy.newProxyInstance(getInstance().getClass().getClassLoader(), + new Class[] { this.treeVisitorType }, new TreeVisitorInvocationHandler(visitor)), 0); } /** @@ -61,15 +56,12 @@ class Tree extends ReflectionWrapper { @Override @SuppressWarnings("rawtypes") - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("visitClass") && (Integer) args[1] == 0) { - Iterable members = (Iterable) Tree.this.getClassTreeMembers - .invoke(args[0]); + Iterable members = (Iterable) Tree.this.getClassTreeMembers.invoke(args[0]); for (Object member : members) { if (member != null) { - Tree.this.acceptMethod.invoke(member, proxy, - ((Integer) args[1]) + 1); + Tree.this.acceptMethod.invoke(member, proxy, ((Integer) args[1]) + 1); } } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java index 92e0c18e908..2d41427016b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ class VariableTree extends ReflectionWrapper { if (modifiers == null) { return Collections.emptySet(); } - return (Set) findMethod(findClass("com.sun.source.tree.ModifiersTree"), - "getFlags").invoke(modifiers); + return (Set) findMethod(findClass("com.sun.source.tree.ModifiersTree"), "getFlags").invoke(modifiers); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java index 8af7a7dcd24..4473816db07 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -148,8 +148,7 @@ public class ConfigurationMetadata { candidates = new ArrayList<>(candidates); candidates.removeIf((itemMetadata) -> !itemMetadata.hasSameType(metadata)); if (candidates.size() > 1 && metadata.getType() != null) { - candidates.removeIf( - (itemMetadata) -> !metadata.getType().equals(itemMetadata.getType())); + candidates.removeIf((itemMetadata) -> !metadata.getType().equals(itemMetadata.getType())); } if (candidates.size() == 1) { return candidates.get(0); @@ -183,8 +182,7 @@ public class ConfigurationMetadata { if (SEPARATORS.contains(current)) { dashed.append("-"); } - else if (Character.isUpperCase(current) && previous != null - && !SEPARATORS.contains(previous)) { + else if (Character.isUpperCase(current) && previous != null && !SEPARATORS.contains(previous)) { dashed.append("-").append(current); } else { @@ -209,8 +207,7 @@ public class ConfigurationMetadata { public String toString() { StringBuilder result = new StringBuilder(); result.append(String.format("items: %n")); - this.items.values().forEach((itemMetadata) -> result.append("\t") - .append(String.format("%s%n", itemMetadata))); + this.items.values().forEach((itemMetadata) -> result.append("\t").append(String.format("%s%n", itemMetadata))); return result.toString(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java index 28cf2ec232f..40032022f9e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,7 @@ public class ItemDeprecation { return false; } ItemDeprecation other = (ItemDeprecation) o; - return nullSafeEquals(this.reason, other.reason) - && nullSafeEquals(this.replacement, other.replacement) + return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement) && nullSafeEquals(this.level, other.level); } @@ -92,9 +91,8 @@ public class ItemDeprecation { @Override public String toString() { - return "ItemDeprecation{" + "reason='" + this.reason + '\'' + ", " - + "replacement='" + this.replacement + '\'' + ", " + "level='" - + this.level + '\'' + '}'; + return "ItemDeprecation{" + "reason='" + this.reason + '\'' + ", " + "replacement='" + this.replacement + '\'' + + ", " + "level='" + this.level + '\'' + '}'; } private boolean nullSafeEquals(Object o1, Object o2) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java index e2e61063add..f7dbf662ff9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,7 @@ public class ItemHint implements Comparable { public ItemHint(String name, List values, List providers) { this.name = toCanonicalName(name); this.values = (values != null) ? new ArrayList<>(values) : new ArrayList<>(); - this.providers = (providers != null) ? new ArrayList<>(providers) - : new ArrayList<>(); + this.providers = (providers != null) ? new ArrayList<>(providers) : new ArrayList<>(); } private String toCanonicalName(String name) { @@ -82,8 +81,7 @@ public class ItemHint implements Comparable { @Override public String toString() { - return "ItemHint{" + "name='" + this.name + "', values=" + this.values - + ", providers=" + this.providers + '}'; + return "ItemHint{" + "name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}'; } /** @@ -110,8 +108,7 @@ public class ItemHint implements Comparable { @Override public String toString() { - return "ValueHint{" + "value=" + this.value + ", description='" - + this.description + '\'' + '}'; + return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}'; } } @@ -140,8 +137,7 @@ public class ItemHint implements Comparable { @Override public String toString() { - return "ValueProvider{" + "name='" + this.name + "', parameters=" - + this.parameters + '}'; + return "ValueProvider{" + "name='" + this.name + "', parameters=" + this.parameters + '}'; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java index 5afe2b3d637..781653bd078 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,9 +44,8 @@ public final class ItemMetadata implements Comparable { private ItemDeprecation deprecation; - ItemMetadata(ItemType itemType, String prefix, String name, String type, - String sourceType, String sourceMethod, String description, - Object defaultValue, ItemDeprecation deprecation) { + ItemMetadata(ItemType itemType, String prefix, String name, String type, String sourceType, String sourceMethod, + String description, Object defaultValue, ItemDeprecation deprecation) { this.itemType = itemType; this.name = buildName(prefix, name); this.type = type; @@ -197,8 +196,7 @@ public final class ItemMetadata implements Comparable { return string.toString(); } - protected void buildToStringProperty(StringBuilder string, String property, - Object value) { + protected void buildToStringProperty(StringBuilder string, String property, Object value) { if (value != null) { string.append(" ").append(property).append(":").append(value); } @@ -209,22 +207,18 @@ public final class ItemMetadata implements Comparable { return getName().compareTo(o.getName()); } - public static ItemMetadata newGroup(String name, String type, String sourceType, - String sourceMethod) { - return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, - sourceMethod, null, null, null); + public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) { + return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null); } - public static ItemMetadata newProperty(String prefix, String name, String type, - String sourceType, String sourceMethod, String description, - Object defaultValue, ItemDeprecation deprecation) { - return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, - sourceMethod, description, defaultValue, deprecation); + public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType, + String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { + return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description, + defaultValue, deprecation); } public static String newItemMetadataPrefix(String prefix, String suffix) { - return prefix.toLowerCase(Locale.ENGLISH) - + ConfigurationMetadata.toDashedCase(suffix); + return prefix.toLowerCase(Locale.ENGLISH) + ConfigurationMetadata.toDashedCase(suffix); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java index 47fa6e8bd6a..3a50b657ac8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java @@ -37,12 +37,10 @@ class JsonConverter { private static final ItemMetadataComparator ITEM_COMPARATOR = new ItemMetadataComparator(); - public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) - throws Exception { + public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception { JSONArray jsonArray = new JSONArray(); - List items = metadata.getItems().stream() - .filter((item) -> item.isOfItemType(itemType)).sorted(ITEM_COMPARATOR) - .collect(Collectors.toList()); + List items = metadata.getItems().stream().filter((item) -> item.isOfItemType(itemType)) + .sorted(ITEM_COMPARATOR).collect(Collectors.toList()); for (ItemMetadata item : items) { if (item.isOfItemType(itemType)) { jsonArray.put(toJsonObject(item)); @@ -123,8 +121,7 @@ class JsonConverter { return providers; } - private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) - throws Exception { + private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception { JSONObject result = new JSONObject(); result.put("name", provider.getName()); if (provider.getParameters() != null && !provider.getParameters().isEmpty()) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java index 1a1377f53fd..7a6bcfb74e4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class JsonMarshaller { private static final int BUFFER_SIZE = 4098; - public void write(ConfigurationMetadata metadata, OutputStream outputStream) - throws IOException { + public void write(ConfigurationMetadata metadata, OutputStream outputStream) throws IOException { try { JSONObject object = new JSONObject(); JsonConverter converter = new JsonConverter(); @@ -75,8 +74,7 @@ public class JsonMarshaller { JSONArray properties = object.optJSONArray("properties"); if (properties != null) { for (int i = 0; i < properties.length(); i++) { - metadata.add(toItemMetadata((JSONObject) properties.get(i), - ItemType.PROPERTY)); + metadata.add(toItemMetadata((JSONObject) properties.get(i), ItemType.PROPERTY)); } } JSONArray hints = object.optJSONArray("hints"); @@ -88,8 +86,7 @@ public class JsonMarshaller { return metadata; } - private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType) - throws Exception { + private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType) throws Exception { String name = object.getString("name"); String type = object.optString("type", null); String description = object.optString("description", null); @@ -97,8 +94,8 @@ public class JsonMarshaller { String sourceMethod = object.optString("sourceMethod", null); Object defaultValue = readItemValue(object.opt("defaultValue")); ItemDeprecation deprecation = toItemDeprecation(object); - return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod, - description, defaultValue, deprecation); + return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod, description, defaultValue, + deprecation); } private ItemDeprecation toItemDeprecation(JSONObject object) throws Exception { @@ -107,8 +104,7 @@ public class JsonMarshaller { ItemDeprecation deprecation = new ItemDeprecation(); deprecation.setLevel(deprecationJsonObject.optString("level", null)); deprecation.setReason(deprecationJsonObject.optString("reason", null)); - deprecation - .setReplacement(deprecationJsonObject.optString("replacement", null)); + deprecation.setReplacement(deprecationJsonObject.optString("replacement", null)); return deprecation; } return object.optBoolean("deprecated") ? new ItemDeprecation() : null; @@ -167,8 +163,7 @@ public class JsonMarshaller { private String toString(InputStream inputStream) throws IOException { StringBuilder out = new StringBuilder(); - InputStreamReader reader = new InputStreamReader(inputStream, - StandardCharsets.UTF_8); + InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); char[] buffer = new char[BUFFER_SIZE]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index c596ab4d093..da20b1a979e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -62,8 +62,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Kris De Volder * @author Jonas Keßler */ -public class ConfigurationMetadataAnnotationProcessorTests - extends AbstractMetadataGenerationTests { +public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGenerationTests { @Test public void notAnnotated() { @@ -74,15 +73,12 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void simpleProperties() { ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) - .withDefaultValue(false).fromSource(SimpleProperties.class) - .withDescription("A simple flag.").withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).withDefaultValue(false) + .fromSource(SimpleProperties.class).withDescription("A simple flag.").withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size")); @@ -91,85 +87,60 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void simplePrefixValueProperties() { ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); - assertThat(metadata).has(Metadata.withGroup("simple") - .fromSource(SimplePrefixValueProperties.class)); - assertThat(metadata).has(Metadata.withProperty("simple.name", String.class) - .fromSource(SimplePrefixValueProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class)); } @Test public void simpleTypeProperties() { ConfigurationMetadata metadata = compile(SimpleTypeProperties.class); - assertThat(metadata).has( - Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-byte", Byte.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-string", String.class)); + .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class).withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-char", Character.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-char", Character.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-byte", Byte.class)); + .has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class).withDefaultValue(false)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-short", Short.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class) - .withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-short", Short.class).withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-integer", Integer.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-char", Character.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-char", Character.class)); + .has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class).withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-long", Long.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class) - .withDefaultValue(false)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-short", Short.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-short", Short.class) - .withDefaultValue(0)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-integer", Integer.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-integer", Integer.class) - .withDefaultValue(0)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-long", Long.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class) - .withDefaultValue(0)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-double", Double.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-double", Double.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-float", Float.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-float", Float.class)); + .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class).withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-double", Double.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-double", Double.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-float", Float.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-float", Float.class)); assertThat(metadata.getItems().size()).isEqualTo(18); } @Test public void hierarchicalProperties() { - ConfigurationMetadata metadata = compile(HierarchicalProperties.class, - HierarchicalPropertiesParent.class, + ConfigurationMetadata metadata = compile(HierarchicalProperties.class, HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class); - assertThat(metadata).has(Metadata.withGroup("hierarchical") + assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class).withDefaultValue("one") .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class) - .withDefaultValue("one").fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata - .withProperty("hierarchical.second", String.class).withDefaultValue("two") + assertThat(metadata).has(Metadata.withProperty("hierarchical.second", String.class).withDefaultValue("two") + .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class).withDefaultValue("three") .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class) - .withDefaultValue("three").fromSource(HierarchicalProperties.class)); } @Test public void descriptionProperties() { ConfigurationMetadata metadata = compile(DescriptionProperties.class); - assertThat(metadata).has(Metadata.withGroup("description") - .fromSource(DescriptionProperties.class)); + assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class)); assertThat(metadata).has(Metadata.withProperty("description.simple", String.class) - .fromSource(DescriptionProperties.class) - .withDescription("A simple description.")); - assertThat(metadata).has(Metadata - .withProperty("description.multi-line", String.class) + .fromSource(DescriptionProperties.class).withDescription("A simple description.")); + assertThat(metadata).has(Metadata.withProperty("description.multi-line", String.class) .fromSource(DescriptionProperties.class).withDescription( "This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically.")); } @@ -180,11 +151,10 @@ public class ConfigurationMetadataAnnotationProcessorTests Class type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("deprecated.name", String.class) - .fromSource(type).withDeprecation(null, null)); - assertThat(metadata) - .has(Metadata.withProperty("deprecated.description", String.class) - .fromSource(type).withDeprecation(null, null)); + assertThat(metadata).has( + Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class).fromSource(type) + .withDeprecation(null, null)); } @Test @@ -192,11 +162,8 @@ public class ConfigurationMetadataAnnotationProcessorTests Class type = DeprecatedSingleProperty.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type)); - assertThat(metadata) - .has(Metadata.withProperty("singledeprecated.new-name", String.class) - .fromSource(type)); - assertThat(metadata).has(Metadata - .withProperty("singledeprecated.name", String.class).fromSource(type) + assertThat(metadata).has(Metadata.withProperty("singledeprecated.new-name", String.class).fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class).fromSource(type) .withDeprecation("renamed", "singledeprecated.new-name")); } @@ -205,12 +172,10 @@ public class ConfigurationMetadataAnnotationProcessorTests Class type = DeprecatedUnrelatedMethodPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); - assertThat(metadata) - .has(Metadata.withProperty("not.deprecated.counter", Integer.class) - .withNoDeprecation().fromSource(type)); - assertThat(metadata) - .has(Metadata.withProperty("not.deprecated.flag", Boolean.class) - .withDefaultValue(false).withNoDeprecation().fromSource(type)); + assertThat(metadata).has( + Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withDefaultValue(false) + .withNoDeprecation().fromSource(type)); } @Test @@ -218,10 +183,9 @@ public class ConfigurationMetadataAnnotationProcessorTests Class type = BoxingPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("boxing.flag", Boolean.class) - .withDefaultValue(false).fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); + assertThat(metadata) + .has(Metadata.withProperty("boxing.flag", Boolean.class).withDefaultValue(false).fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); } @Test @@ -230,17 +194,13 @@ public class ConfigurationMetadataAnnotationProcessorTests // getter and setter assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names", "java.util.Map")); - assertThat(metadata).has(Metadata.withProperty("collection.longs", - "java.util.Collection")); - assertThat(metadata).has(Metadata.withProperty("collection.floats", - "java.util.List")); + assertThat(metadata).has(Metadata.withProperty("collection.longs", "java.util.Collection")); + assertThat(metadata).has(Metadata.withProperty("collection.floats", "java.util.List")); // getter only assertThat(metadata).has(Metadata.withProperty("collection.names-to-integers", "java.util.Map")); - assertThat(metadata).has(Metadata.withProperty("collection.bytes", - "java.util.Collection")); - assertThat(metadata).has(Metadata.withProperty("collection.doubles", - "java.util.List")); + assertThat(metadata).has(Metadata.withProperty("collection.bytes", "java.util.Collection")); + assertThat(metadata).has(Metadata.withProperty("collection.doubles", "java.util.List")); assertThat(metadata).has(Metadata.withProperty("collection.names-to-holders", "java.util.Map>")); } @@ -248,38 +208,32 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void parseArrayConfig() throws Exception { ConfigurationMetadata metadata = compile(SimpleArrayProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class)); - assertThat(metadata) - .has(Metadata.withProperty("array.primitive", "java.lang.Integer[]")); - assertThat(metadata) - .has(Metadata.withProperty("array.simple", "java.lang.String[]")); + assertThat(metadata).has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class)); + assertThat(metadata).has(Metadata.withProperty("array.primitive", "java.lang.Integer[]")); + assertThat(metadata).has(Metadata.withProperty("array.simple", "java.lang.String[]")); assertThat(metadata).has(Metadata.withProperty("array.inner", "org.springframework.boot.configurationsample.simple.SimpleArrayProperties$Holder[]")); - assertThat(metadata).has(Metadata.withProperty("array.name-to-integer", - "java.util.Map[]")); + assertThat(metadata).has( + Metadata.withProperty("array.name-to-integer", "java.util.Map[]")); assertThat(metadata.getItems()).hasSize(5); } @Test public void annotatedGetter() { ConfigurationMetadata metadata = compile(AnnotatedGetter.class); + assertThat(metadata).has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class)); assertThat(metadata) - .has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class)); - assertThat(metadata).has(Metadata.withProperty("specific.name", String.class) - .fromSource(AnnotatedGetter.class)); + .has(Metadata.withProperty("specific.name", String.class).fromSource(AnnotatedGetter.class)); } @Test public void staticAccessor() { ConfigurationMetadata metadata = compile(StaticAccessor.class); - assertThat(metadata) - .has(Metadata.withGroup("specific").fromSource(StaticAccessor.class)); + assertThat(metadata).has(Metadata.withGroup("specific").fromSource(StaticAccessor.class)); assertThat(metadata).has(Metadata.withProperty("specific.counter", Integer.class) .fromSource(StaticAccessor.class).withDefaultValue(42)); assertThat(metadata) - .doesNotHave(Metadata.withProperty("specific.name", String.class) - .fromSource(StaticAccessor.class)); + .doesNotHave(Metadata.withProperty("specific.name", String.class).fromSource(StaticAccessor.class)); assertThat(metadata.getItems()).hasSize(2); } @@ -292,20 +246,17 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void innerClassProperties() { ConfigurationMetadata metadata = compile(InnerClassProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); - assertThat(metadata).has( - Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); - assertThat(metadata).has( - Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.the-second.name")); assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name")); - assertThat(metadata).has(Metadata.withGroup("config.third") - .ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); + assertThat(metadata).has( + Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.third.value")); assertThat(metadata).has(Metadata.withProperty("config.fourth")); assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth")); @@ -314,12 +265,11 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void innerClassPropertiesHierarchical() { ConfigurationMetadata metadata = compile(InnerClassHierarchicalProperties.class); - assertThat(metadata).has(Metadata.withGroup("config.foo") - .ofType(InnerClassHierarchicalProperties.Foo.class)); - assertThat(metadata).has(Metadata.withGroup("config.foo.bar") - .ofType(InnerClassHierarchicalProperties.Bar.class)); - assertThat(metadata).has(Metadata.withGroup("config.foo.bar.baz") - .ofType(InnerClassHierarchicalProperties.Foo.Baz.class)); + assertThat(metadata).has(Metadata.withGroup("config.foo").ofType(InnerClassHierarchicalProperties.Foo.class)); + assertThat(metadata) + .has(Metadata.withGroup("config.foo.bar").ofType(InnerClassHierarchicalProperties.Bar.class)); + assertThat(metadata) + .has(Metadata.withGroup("config.foo.bar.baz").ofType(InnerClassHierarchicalProperties.Foo.Baz.class)); assertThat(metadata).has(Metadata.withProperty("config.foo.bar.baz.blah")); assertThat(metadata).has(Metadata.withProperty("config.foo.bar.bling")); } @@ -335,16 +285,12 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void nestedClassChildProperties() { ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class); - assertThat(metadata).has(Metadata.withGroup("nestedChildProps") - .fromSource(ClassWithNestedProperties.NestedChildClass.class)); - assertThat(metadata).has(Metadata - .withProperty("nestedChildProps.child-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class) - .withDefaultValue(20)); - assertThat(metadata).has(Metadata - .withProperty("nestedChildProps.parent-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class) - .withDefaultValue(10)); + assertThat(metadata).has( + Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); + assertThat(metadata).has(Metadata.withProperty("nestedChildProps.child-class-property", Integer.class) + .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(20)); + assertThat(metadata).has(Metadata.withProperty("nestedChildProps.parent-class-property", Integer.class) + .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(10)); } @Test @@ -383,30 +329,25 @@ public class ConfigurationMetadataAnnotationProcessorTests @Test public void invalidDoubleRegistration() { - assertThatIllegalStateException() - .isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) + assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) .withMessageContaining("Compilation failed"); } @Test public void constructorParameterPropertyWithInvalidDefaultValueOnNumber() { - assertThatIllegalStateException() - .isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class)) + assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class)) .withMessageContaining("Compilation failed"); } @Test public void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() { - assertThatIllegalStateException() - .isThrownBy( - () -> compile(InvalidDefaultValueFloatingPointProperties.class)) + assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class)) .withMessageContaining("Compilation failed"); } @Test public void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() { - assertThatIllegalStateException() - .isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class)) + assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class)) .withMessageContaining("Compilation failed"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java index 2242c0ae0f2..94b9bc889b0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java @@ -47,10 +47,8 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip @Test public void constructorParameterSimpleProperty() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableSimpleProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "theName"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertThat(property.getName()).isEqualTo("theName"); assertThat(property.getSource()).hasToString("theName"); assertThat(property.getGetter().getSimpleName()).hasToString("getTheName"); @@ -62,10 +60,8 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip @Test public void constructorParameterNestedPropertySameClass() throws IOException { process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableInnerClassProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "first"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertThat(property.getName()).isEqualTo("first"); assertThat(property.getSource()).hasToString("first"); assertThat(property.getGetter().getSimpleName()).hasToString("getFirst"); @@ -77,10 +73,8 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip @Test public void constructorParameterNestedPropertyWithAnnotation() throws IOException { process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableInnerClassProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "third"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third"); assertThat(property.getName()).isEqualTo("third"); assertThat(property.getSource()).hasToString("third"); assertThat(property.getGetter().getSimpleName()).hasToString("getThird"); @@ -90,13 +84,10 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() - throws IOException { + public void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableSimpleProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "counter"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter"); assertThat(property.getName()).isEqualTo("counter"); assertThat(property.getSource()).hasToString("counter"); assertThat(property.getGetter()).isNull(); @@ -108,55 +99,43 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip @Test public void constructorParameterMetadataSimpleProperty() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableSimpleProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "counter"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.counter") - .hasType(Long.class).hasSourceType(ImmutableSimpleProperties.class) - .hasNoDescription().isNotDeprecated(); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter"); + assertItemMetadata(metadataEnv, property).isProperty().hasName("test.counter").hasType(Long.class) + .hasSourceType(ImmutableSimpleProperties.class).hasNoDescription().isNotDeprecated(); }); } @Test public void constructorParameterMetadataNestedGroup() throws IOException { process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableInnerClassProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "first"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType( - "org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo") - .hasSourceType(ImmutableInnerClassProperties.class) - .hasSourceMethod("getFirst()").hasNoDescription().isNotDeprecated(); + .hasType("org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo") + .hasSourceType(ImmutableInnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription() + .isNotDeprecated(); }); } @Test public void constructorParameterDeprecatedPropertyOnGetter() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableSimpleProperties.class); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ExecutableElement getter = getMethod(ownerElement, "isFlag"); VariableElement field = getField(ownerElement, "flag"); - VariableElement constructorParameter = getConstructorParameter(ownerElement, - "flag"); - ConstructorParameterPropertyDescriptor property = new ConstructorParameterPropertyDescriptor( - ownerElement, null, constructorParameter, "flag", field.asType(), - field, getter, null); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithNoInformation(); + VariableElement constructorParameter = getConstructorParameter(ownerElement, "flag"); + ConstructorParameterPropertyDescriptor property = new ConstructorParameterPropertyDescriptor(ownerElement, + null, constructorParameter, "flag", field.asType(), field, getter, null); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); } @Test public void constructorParameterPropertyWithDescription() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableSimpleProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "theName"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertItemMetadata(metadataEnv, property).isProperty() .hasDescription("The name of this simple properties."); }); @@ -165,154 +144,86 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip @Test public void constructorParameterPropertyWithDefaultValue() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableSimpleProperties.class); - ConstructorParameterPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "theName"); - assertItemMetadata(metadataEnv, property).isProperty() - .hasDefaultValue("boot"); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); + ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); + assertItemMetadata(metadataEnv, property).isProperty().hasDefaultValue("boot"); }); } @Test public void constructorParameterPropertyWithPrimitiveTypes() throws IOException { process(ImmutablePrimitiveProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutablePrimitiveProperties.class); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "flag")) - .hasDefaultValue(false); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(0); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "letter")) - .hasDefaultValue(null); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(0); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(0); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(0L); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "percentage")) - .hasDefaultValue(0); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(0D); + TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveProperties.class); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(false); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(0); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue(null); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(0); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(0); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(0L); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(0D); }); } @Test - public void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() - throws IOException { - process(ImmutablePrimitiveWithDefaultsProperties.class, - (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv.getRootElement( - ImmutablePrimitiveWithDefaultsProperties.class); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "flag")) - .hasDefaultValue(true); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "octet")) - .hasDefaultValue(120); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "letter")) - .hasDefaultValue("a"); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue(1000); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "counter")) - .hasDefaultValue(42); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "value")) - .hasDefaultValue(2000); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "percentage")) - .hasDefaultValue(0.5); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "ratio")) - .hasDefaultValue(42.42); - }); + public void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() throws IOException { + process(ImmutablePrimitiveWithDefaultsProperties.class, (roundEnv, metadataEnv) -> { + TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWithDefaultsProperties.class); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(120); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a"); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(1000); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(42.42); + }); } @Test - public void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() - throws IOException { - process(ImmutablePrimitiveWrapperWithDefaultsProperties.class, - (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv.getRootElement( - ImmutablePrimitiveWrapperWithDefaultsProperties.class); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "flag")) - .hasDefaultValue(true); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "octet")) - .hasDefaultValue(120); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "letter")) - .hasDefaultValue("a"); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue(1000); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "counter")) - .hasDefaultValue(42); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "value")) - .hasDefaultValue(2000); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "percentage")) - .hasDefaultValue(0.5); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "ratio")) - .hasDefaultValue(42.42); - }); + public void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() throws IOException { + process(ImmutablePrimitiveWrapperWithDefaultsProperties.class, (roundEnv, metadataEnv) -> { + TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWrapperWithDefaultsProperties.class); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(120); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a"); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(1000); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(42.42); + }); } @Test - public void constructorParameterPropertyWithCollectionTypesAndDefaultValues() - throws IOException { + public void constructorParameterPropertyWithCollectionTypesAndDefaultValues() throws IOException { process(ImmutableCollectionProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(ImmutableCollectionProperties.class); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "names")) - .hasDefaultValue(null); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "flags")) - .hasDefaultValue(Arrays.asList(true, false)); - assertItemMetadata(metadataEnv, - createPropertyDescriptor(ownerElement, "durations")) - .hasDefaultValue(Arrays.asList("10s", "1m", "1h")); + TypeElement ownerElement = roundEnv.getRootElement(ImmutableCollectionProperties.class); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "names")).hasDefaultValue(null); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flags")) + .hasDefaultValue(Arrays.asList(true, false)); + assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "durations")) + .hasDefaultValue(Arrays.asList("10s", "1m", "1h")); }); } - protected ConstructorParameterPropertyDescriptor createPropertyDescriptor( - TypeElement ownerElement, String name) { - VariableElement constructorParameter = getConstructorParameter(ownerElement, - name); + protected ConstructorParameterPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name) { + VariableElement constructorParameter = getConstructorParameter(ownerElement, name); VariableElement field = getField(ownerElement, name); - ExecutableElement getter = getMethod(ownerElement, - createAccessorMethodName("get", name)); - ExecutableElement setter = getMethod(ownerElement, - createAccessorMethodName("set", name)); - return new ConstructorParameterPropertyDescriptor(ownerElement, null, - constructorParameter, name, field.asType(), field, getter, setter); + ExecutableElement getter = getMethod(ownerElement, createAccessorMethodName("get", name)); + ExecutableElement setter = getMethod(ownerElement, createAccessorMethodName("set", name)); + return new ConstructorParameterPropertyDescriptor(ownerElement, null, constructorParameter, name, + field.asType(), field, getter, setter); } - private VariableElement getConstructorParameter(TypeElement ownerElement, - String name) { - List constructors = ElementFilter - .constructorsIn(ownerElement.getEnclosedElements()).stream() - .filter((constructor) -> !constructor.getParameters().isEmpty()) - .collect(Collectors.toList()); + private VariableElement getConstructorParameter(TypeElement ownerElement, String name) { + List constructors = ElementFilter.constructorsIn(ownerElement.getEnclosedElements()).stream() + .filter((constructor) -> !constructor.getParameters().isEmpty()).collect(Collectors.toList()); if (constructors.size() != 1) { - throw new IllegalStateException( - "No candidate constructor for " + ownerElement); + throw new IllegalStateException("No candidate constructor for " + ownerElement); } return constructors.get(0).getParameters().stream() - .filter((parameter) -> parameter.getSimpleName().toString().equals(name)) - .findFirst().orElse(null); + .filter((parameter) -> parameter.getSimpleName().toString().equals(name)).findFirst().orElse(null); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java index 785c43d380f..37b6489e89a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java @@ -42,8 +42,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void simpleEndpoint() { ConfigurationMetadata metadata = compile(SimpleEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple") - .fromSource(SimpleEndpoint.class)); + assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple").fromSource(SimpleEndpoint.class)); assertThat(metadata).has(enabledFlag("simple", true)); assertThat(metadata).has(cacheTtl("simple")); assertThat(metadata.getItems()).hasSize(3); @@ -52,8 +51,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void disableEndpoint() { ConfigurationMetadata metadata = compile(DisabledEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled") - .fromSource(DisabledEndpoint.class)); + assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled").fromSource(DisabledEndpoint.class)); assertThat(metadata).has(enabledFlag("disabled", false)); assertThat(metadata.getItems()).hasSize(2); } @@ -61,8 +59,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void enabledEndpoint() { ConfigurationMetadata metadata = compile(EnabledEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled") - .fromSource(EnabledEndpoint.class)); + assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled").fromSource(EnabledEndpoint.class)); assertThat(metadata).has(enabledFlag("enabled", true)); assertThat(metadata.getItems()).hasSize(2); } @@ -70,11 +67,10 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void customPropertiesEndpoint() { ConfigurationMetadata metadata = compile(CustomPropertiesEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.customprops") - .fromSource(CustomPropertiesEndpoint.class)); assertThat(metadata) - .has(Metadata.withProperty("management.endpoint.customprops.name") - .ofType(String.class).withDefaultValue("test")); + .has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class)); + assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name").ofType(String.class) + .withDefaultValue("test")); assertThat(metadata).has(enabledFlag("customprops", true)); assertThat(metadata).has(cacheTtl("customprops")); assertThat(metadata.getItems()).hasSize(4); @@ -83,8 +79,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void specificEndpoint() { ConfigurationMetadata metadata = compile(SpecificEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific") - .fromSource(SpecificEndpoint.class)); + assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); assertThat(metadata).has(enabledFlag("specific", true)); assertThat(metadata).has(cacheTtl("specific")); assertThat(metadata.getItems()).hasSize(3); @@ -93,27 +88,26 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void camelCaseEndpoint() { ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.pascal-case") - .fromSource(CamelCaseEndpoint.class)); + assertThat(metadata) + .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); assertThat(metadata).has(enabledFlag("PascalCase", "pascal-case", true)); assertThat(metadata.getItems()).hasSize(2); } @Test public void incrementalEndpointBuildChangeGeneralEnabledFlag() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, - IncrementalEndpoint.class); + TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental") - .fromSource(IncrementalEndpoint.class)); + assertThat(metadata) + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); project.replaceText(IncrementalEndpoint.class, "id = \"incremental\"", "id = \"incremental\", enableByDefault = false"); metadata = project.incrementalBuild(IncrementalEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental") - .fromSource(IncrementalEndpoint.class)); + assertThat(metadata) + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", false)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); @@ -121,61 +115,50 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void incrementalEndpointBuildChangeCacheFlag() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, - IncrementalEndpoint.class); + TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental") - .fromSource(IncrementalEndpoint.class)); + assertThat(metadata) + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); - project.replaceText(IncrementalEndpoint.class, "@Nullable String param", - "String param"); + project.replaceText(IncrementalEndpoint.class, "@Nullable String param", "String param"); metadata = project.incrementalBuild(IncrementalEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental") - .fromSource(IncrementalEndpoint.class)); + assertThat(metadata) + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata.getItems()).hasSize(2); } @Test public void incrementalEndpointBuildEnableSpecificEndpoint() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, - SpecificEndpoint.class); + TestProject project = new TestProject(this.temporaryFolder, SpecificEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific") - .fromSource(SpecificEndpoint.class)); + assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); assertThat(metadata).has(enabledFlag("specific", true)); assertThat(metadata).has(cacheTtl("specific")); assertThat(metadata.getItems()).hasSize(3); - project.replaceText(SpecificEndpoint.class, "enableByDefault = true", - "enableByDefault = false"); + project.replaceText(SpecificEndpoint.class, "enableByDefault = true", "enableByDefault = false"); metadata = project.incrementalBuild(SpecificEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific") - .fromSource(SpecificEndpoint.class)); + assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); assertThat(metadata).has(enabledFlag("specific", false)); assertThat(metadata).has(cacheTtl("specific")); assertThat(metadata.getItems()).hasSize(3); } - private Metadata.MetadataItemCondition enabledFlag(String endpointId, - String endpointSuffix, Boolean defaultValue) { - return Metadata - .withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled") - .withDefaultValue(defaultValue).withDescription( - String.format("Whether to enable the %s endpoint.", endpointId)); + private Metadata.MetadataItemCondition enabledFlag(String endpointId, String endpointSuffix, Boolean defaultValue) { + return Metadata.withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled") + .withDefaultValue(defaultValue) + .withDescription(String.format("Whether to enable the %s endpoint.", endpointId)); } - private Metadata.MetadataItemCondition enabledFlag(String endpointId, - Boolean defaultValue) { + private Metadata.MetadataItemCondition enabledFlag(String endpointId, Boolean defaultValue) { return enabledFlag(endpointId, endpointId, defaultValue); } private Metadata.MetadataItemCondition cacheTtl(String endpointId) { - return Metadata - .withProperty("management.endpoint." + endpointId + ".cache.time-to-live") - .ofType(Duration.class).withDefaultValue("0ms") - .withDescription("Maximum time that a response can be cached."); + return Metadata.withProperty("management.endpoint." + endpointId + ".cache.time-to-live").ofType(Duration.class) + .withDefaultValue("0ms").withDescription("Maximum time that a response can be cached."); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java index 0ad23dcfdbb..cdf294092de 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java @@ -39,90 +39,74 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT @Test public void simpleGenericProperties() { - ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, - SimpleGenericProperties.class); - assertThat(metadata).has( - Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class)); + ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class); + assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) - .fromSource(SimpleGenericProperties.class) - .withDescription("Generic name.").withDefaultValue(null)); + .fromSource(SimpleGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); assertThat(metadata).has(Metadata - .withProperty("generic.mappings", - "java.util.Map") - .fromSource(SimpleGenericProperties.class) - .withDescription("Generic mappings.").withDefaultValue(null)); + .withProperty("generic.mappings", "java.util.Map") + .fromSource(SimpleGenericProperties.class).withDescription("Generic mappings.").withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @Test public void complexGenericProperties() { ConfigurationMetadata metadata = compile(ComplexGenericProperties.class); - assertThat(metadata).has( - Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class)); - assertThat(metadata).has( - Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class) - .fromSource(ComplexGenericProperties.class)); - assertThat(metadata).has(Metadata - .withProperty("generic.test.mappings", - "java.util.Map,java.lang.String>") - .fromSource(UpperBoundGenericPojo.class)); + assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class)); + assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class) + .fromSource(ComplexGenericProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("generic.test.mappings", "java.util.Map,java.lang.String>") + .fromSource(UpperBoundGenericPojo.class)); assertThat(metadata.getItems()).hasSize(3); } @Test public void unresolvedGenericProperties() { - ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, - UnresolvedGenericProperties.class); - assertThat(metadata).has(Metadata.withGroup("generic") - .fromSource(UnresolvedGenericProperties.class)); + ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class); + assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) - .fromSource(UnresolvedGenericProperties.class) - .withDescription("Generic name.").withDefaultValue(null)); - assertThat(metadata).has(Metadata - .withProperty("generic.mappings", - "java.util.Map") - .fromSource(UnresolvedGenericProperties.class) - .withDescription("Generic mappings.").withDefaultValue(null)); + .fromSource(UnresolvedGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); + assertThat(metadata) + .has(Metadata.withProperty("generic.mappings", "java.util.Map") + .fromSource(UnresolvedGenericProperties.class).withDescription("Generic mappings.") + .withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @Test public void genericTypes() { ConfigurationMetadata metadata = compile(GenericConfig.class); - assertThat(metadata).has(Metadata.withGroup("generic").ofType( - "org.springframework.boot.configurationsample.generic.GenericConfig")); - assertThat(metadata).has(Metadata.withGroup("generic.foo").ofType( - "org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); - assertThat(metadata).has(Metadata.withGroup("generic.foo.bar").ofType( - "org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); - assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz").ofType( - "org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); - assertThat(metadata).has(Metadata.withProperty("generic.foo.name") - .ofType(String.class).fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar") - .ofType("java.util.Map>") + assertThat(metadata).has(Metadata.withGroup("generic") + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); + assertThat(metadata).has(Metadata.withGroup("generic.foo") + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); + assertThat(metadata).has(Metadata.withGroup("generic.foo.bar") + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); + assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz") + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); + assertThat(metadata).has( + Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar").ofType( + "java.util.Map>") .fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-integer") - .ofType("java.util.Map") - .fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name") - .ofType("java.lang.String").fromSource(GenericConfig.Bar.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name") - .ofType("java.lang.String").fromSource(GenericConfig.Bar.Biz.class)); + .ofType("java.util.Map").fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name").ofType("java.lang.String") + .fromSource(GenericConfig.Bar.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name").ofType("java.lang.String") + .fromSource(GenericConfig.Bar.Biz.class)); assertThat(metadata.getItems()).hasSize(9); } @Test public void wildcardTypes() { ConfigurationMetadata metadata = compile(WildcardConfig.class); - assertThat(metadata) - .has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); + assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number") - .ofType("java.util.Map") - .fromSource(WildcardConfig.class)); + .ofType("java.util.Map").fromSource(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.integers") - .ofType("java.util.List") - .fromSource(WildcardConfig.class)); + .ofType("java.util.List").fromSource(WildcardConfig.class)); assertThat(metadata.getItems()).hasSize(3); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java index 0b7fb04b729..785bed5df1d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java @@ -29,21 +29,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ImmutablePropertiesMetadataGenerationTests - extends AbstractMetadataGenerationTests { +public class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test public void immutableSimpleProperties() { ConfigurationMetadata metadata = compile(ImmutableSimpleProperties.class); - assertThat(metadata).has(Metadata.withGroup("immutable") - .fromSource(ImmutableSimpleProperties.class)); - assertThat(metadata).has(Metadata.withProperty("immutable.the-name", String.class) - .fromSource(ImmutableSimpleProperties.class) - .withDescription("The name of this simple properties.") - .withDefaultValue("boot")); - assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class) - .withDefaultValue(false).fromSource(ImmutableSimpleProperties.class) - .withDescription("A simple flag.").withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withGroup("immutable").fromSource(ImmutableSimpleProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("immutable.the-name", String.class).fromSource(ImmutableSimpleProperties.class) + .withDescription("The name of this simple properties.").withDefaultValue("boot")); + assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class).withDefaultValue(false) + .fromSource(ImmutableSimpleProperties.class).withDescription("A simple flag.") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("immutable.comparator")); assertThat(metadata).has(Metadata.withProperty("immutable.counter")); assertThat(metadata.getItems()).hasSize(5); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java index 747d76b9055..7c4cf0aa36b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java @@ -31,79 +31,65 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class IncrementalBuildMetadataGenerationTests - extends AbstractMetadataGenerationTests { +public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test public void incrementalBuild() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, - BarProperties.class); + TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse(); ConfigurationMetadata metadata = project.fullBuild(); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue(); - assertThat(metadata).has(Metadata.withProperty("foo.counter") - .fromSource(FooProperties.class).withDefaultValue(0)); - assertThat(metadata).has(Metadata.withProperty("bar.counter") - .fromSource(BarProperties.class).withDefaultValue(0)); + assertThat(metadata) + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + assertThat(metadata) + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata).has(Metadata.withProperty("foo.counter") - .fromSource(FooProperties.class).withDefaultValue(0)); - assertThat(metadata).has(Metadata.withProperty("bar.counter") - .fromSource(BarProperties.class).withDefaultValue(0)); - project.addSourceCode(BarProperties.class, - BarProperties.class.getResourceAsStream("BarProperties.snippet")); + assertThat(metadata) + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + assertThat(metadata) + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + project.addSourceCode(BarProperties.class, BarProperties.class.getResourceAsStream("BarProperties.snippet")); metadata = project.incrementalBuild(BarProperties.class); assertThat(metadata).has(Metadata.withProperty("bar.extra")); - assertThat(metadata) - .has(Metadata.withProperty("foo.counter").withDefaultValue(0)); - assertThat(metadata) - .has(Metadata.withProperty("bar.counter").withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0)); project.revert(BarProperties.class); metadata = project.incrementalBuild(BarProperties.class); assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.extra")); - assertThat(metadata) - .has(Metadata.withProperty("foo.counter").withDefaultValue(0)); - assertThat(metadata) - .has(Metadata.withProperty("bar.counter").withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0)); } @Test public void incrementalBuildAnnotationRemoved() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, - BarProperties.class); + TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata) - .has(Metadata.withProperty("foo.counter").withDefaultValue(0)); - assertThat(metadata) - .has(Metadata.withProperty("bar.counter").withDefaultValue(0)); - project.replaceText(BarProperties.class, "@ConfigurationProperties", - "//@ConfigurationProperties"); + assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0)); + project.replaceText(BarProperties.class, "@ConfigurationProperties", "//@ConfigurationProperties"); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata) - .has(Metadata.withProperty("foo.counter").withDefaultValue(0)); + assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0)); assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.counter")); } @Test public void incrementalBuildTypeRenamed() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, - BarProperties.class); + TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata).has(Metadata.withProperty("foo.counter") - .fromSource(FooProperties.class).withDefaultValue(0)); - assertThat(metadata).has(Metadata.withProperty("bar.counter") - .fromSource(BarProperties.class).withDefaultValue(0)); - assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter") - .fromSource(RenamedBarProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + assertThat(metadata) + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class)); project.delete(BarProperties.class); project.add(RenamedBarProperties.class); metadata = project.incrementalBuild(RenamedBarProperties.class); - assertThat(metadata).has(Metadata.withProperty("foo.counter") - .fromSource(FooProperties.class).withDefaultValue(0)); - assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter") - .fromSource(BarProperties.class).withDefaultValue(0)); - assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0) - .fromSource(RenamedBarProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + assertThat(metadata) + .doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + assertThat(metadata) + .has(Metadata.withProperty("bar.counter").withDefaultValue(0).fromSource(RenamedBarProperties.class)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java index 3b0fbe3aa1b..9c2254dc055 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java @@ -42,10 +42,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void javaBeanSimpleProperty() throws IOException { process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(SimpleTypeProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "myString"); + TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString"); assertThat(property.getName()).isEqualTo("myString"); assertThat(property.getSource()).isSameAs(property.getGetter()); assertThat(property.getGetter().getSimpleName()).hasToString("getMyString"); @@ -58,10 +56,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void javaBeanCollectionProperty() throws IOException { process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(SimpleCollectionProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "doubles"); + TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles"); assertThat(property.getName()).isEqualTo("doubles"); assertThat(property.getGetter().getSimpleName()).hasToString("getDoubles"); assertThat(property.getSetter()).isNull(); @@ -73,10 +69,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void javaBeanNestedPropertySameClass() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(InnerClassProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "first"); + TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertThat(property.getName()).isEqualTo("first"); assertThat(property.getGetter().getSimpleName()).hasToString("getFirst"); assertThat(property.getSetter()).isNull(); @@ -88,10 +82,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void javaBeanNestedPropertyWithAnnotation() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(InnerClassProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "third"); + TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third"); assertThat(property.getName()).isEqualTo("third"); assertThat(property.getGetter().getSimpleName()).hasToString("getThird"); assertThat(property.getSetter()).isNull(); @@ -101,14 +93,13 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() - throws IOException { + public void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); ExecutableElement getter = getMethod(ownerElement, "getSize"); VariableElement field = getField(ownerElement, "size"); - JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor( - ownerElement, getter, getter, "size", field.asType(), field, null); + JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(ownerElement, getter, getter, "size", + field.asType(), field, null); assertThat(property.getName()).isEqualTo("size"); assertThat(property.getSource()).isSameAs(property.getGetter()); assertThat(property.getGetter().getSimpleName()).hasToString("getSize"); @@ -119,14 +110,12 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() - throws IOException { + public void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); VariableElement field = getField(ownerElement, "counter"); - JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor( - ownerElement, null, null, "counter", field.asType(), field, - getMethod(ownerElement, "setCounter")); + JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(ownerElement, null, null, "counter", + field.asType(), field, getMethod(ownerElement, "setCounter")); assertThat(property.getName()).isEqualTo("counter"); assertThat(property.getSource()).isSameAs(property.getGetter()); assertThat(property.getGetter()).isNull(); @@ -139,55 +128,43 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void javaBeanMetadataSimpleProperty() throws IOException { process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(SimpleTypeProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "myString"); - assertItemMetadata(metadataEnv, property).isProperty() - .hasName("test.my-string").hasType(String.class) - .hasSourceType(SimpleTypeProperties.class).hasNoDescription() - .isNotDeprecated(); + TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString"); + assertItemMetadata(metadataEnv, property).isProperty().hasName("test.my-string").hasType(String.class) + .hasSourceType(SimpleTypeProperties.class).hasNoDescription().isNotDeprecated(); }); } @Test public void javaBeanMetadataCollectionProperty() throws IOException { process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(SimpleCollectionProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "doubles"); + TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles"); assertItemMetadata(metadataEnv, property).isProperty().hasName("test.doubles") - .hasType("java.util.List") - .hasSourceType(SimpleCollectionProperties.class).hasNoDescription() - .isNotDeprecated(); + .hasType("java.util.List").hasSourceType(SimpleCollectionProperties.class) + .hasNoDescription().isNotDeprecated(); }); } @Test public void javaBeanMetadataNestedGroup() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(InnerClassProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "first"); + TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType( - "org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo") - .hasSourceType(InnerClassProperties.class) - .hasSourceMethod("getFirst()").hasNoDescription().isNotDeprecated(); + .hasType("org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo") + .hasSourceType(InnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription() + .isNotDeprecated(); }); } @Test - public void javaBeanMetadataNotACandidatePropertyShouldReturnNull() - throws IOException { + public void javaBeanMetadataNotACandidatePropertyShouldReturnNull() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); VariableElement field = getField(ownerElement, "counter"); - JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor( - ownerElement, null, null, "counter", field.asType(), field, - getMethod(ownerElement, "setCounter")); + JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(ownerElement, null, null, "counter", + field.asType(), field, getMethod(ownerElement, "setCounter")); assertThat(property.resolveItemMetadata("test", metadataEnv)).isNull(); }); } @@ -199,22 +176,17 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement( org.springframework.boot.configurationsample.simple.DeprecatedProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "name"); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithNoInformation(); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); } @Test public void javaBeanMetadataDeprecatedPropertyWithAnnotation() throws IOException { process(DeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(DeprecatedSingleProperty.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "name"); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithReason("renamed") + TypeElement ownerElement = roundEnv.getRootElement(DeprecatedSingleProperty.class); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithReason("renamed") .isDeprecatedWithReplacement("singledeprecated.new-name"); }); } @@ -223,10 +195,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { public void javaBeanDeprecatedPropertyOnGetter() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "flag", "isFlag", "setFlag"); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithNoInformation(); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "flag", "isFlag", "setFlag"); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); } @@ -234,10 +204,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { public void javaBeanDeprecatedPropertyOnSetter() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "theName"); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithNoInformation(); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); } @@ -245,8 +213,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { public void javaBeanPropertyWithDescription() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "theName"); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertItemMetadata(metadataEnv, property).isProperty() .hasDescription("The name of this simple properties."); }); @@ -256,27 +223,22 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { public void javaBeanPropertyWithDefaultValue() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); - JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "theName"); - assertItemMetadata(metadataEnv, property).isProperty() - .hasDefaultValue("boot"); + JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); + assertItemMetadata(metadataEnv, property).isProperty().hasDefaultValue("boot"); }); } - protected JavaBeanPropertyDescriptor createPropertyDescriptor( - TypeElement ownerElement, String name) { - return createPropertyDescriptor(ownerElement, name, - createAccessorMethodName("get", name), + protected JavaBeanPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name) { + return createPropertyDescriptor(ownerElement, name, createAccessorMethodName("get", name), createAccessorMethodName("set", name)); } - protected JavaBeanPropertyDescriptor createPropertyDescriptor( - TypeElement ownerElement, String name, String getterName, String setterName) { + protected JavaBeanPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name, + String getterName, String setterName) { ExecutableElement getter = getMethod(ownerElement, getterName); ExecutableElement setter = getMethod(ownerElement, setterName); VariableElement field = getField(ownerElement, name); - return new JavaBeanPropertyDescriptor(ownerElement, null, getter, name, - getter.getReturnType(), field, setter); + return new JavaBeanPropertyDescriptor(ownerElement, null, getter, name, getter.getReturnType(), field, setter); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java index dbac08dedaa..73acdf3566b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java @@ -55,63 +55,51 @@ public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTes @Test public void lombokExplicitProperties() { ConfigurationMetadata metadata = compile(LombokExplicitProperties.class); - assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, - "explicit"); + assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, "explicit"); assertThat(metadata.getItems()).hasSize(6); } @Test public void lombokAccessLevelProperties() { ConfigurationMetadata metadata = compile(LombokAccessLevelProperties.class); - assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, - "accesslevel", 2); + assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, "accesslevel", 2); } @Test public void lombokAccessLevelOverwriteDataProperties() { - ConfigurationMetadata metadata = compile( - LombokAccessLevelOverwriteDataProperties.class); - assertAccessLevelOverwriteLombokProperties(metadata, - LombokAccessLevelOverwriteDataProperties.class, + ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDataProperties.class); + assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDataProperties.class, "accesslevel.overwrite.data"); } @Test public void lombokAccessLevelOverwriteExplicitProperties() { - ConfigurationMetadata metadata = compile( - LombokAccessLevelOverwriteExplicitProperties.class); - assertAccessLevelOverwriteLombokProperties(metadata, - LombokAccessLevelOverwriteExplicitProperties.class, + ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteExplicitProperties.class); + assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteExplicitProperties.class, "accesslevel.overwrite.explicit"); } @Test public void lombokAccessLevelOverwriteDefaultProperties() { - ConfigurationMetadata metadata = compile( - LombokAccessLevelOverwriteDefaultProperties.class); - assertAccessLevelOverwriteLombokProperties(metadata, - LombokAccessLevelOverwriteDefaultProperties.class, + ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDefaultProperties.class); + assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDefaultProperties.class, "accesslevel.overwrite.default"); } @Test public void lombokInnerClassProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); - assertThat(metadata).has(Metadata.withGroup("config") - .fromSource(LombokInnerClassProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first") - .ofType(LombokInnerClassProperties.Foo.class) + assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); - assertThat(metadata).has( - Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) + .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.second.name")); assertThat(metadata).has(Metadata.withProperty("config.second.bar.name")); - assertThat(metadata) - .has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) + .fromSource(LombokInnerClassProperties.class)); // For some reason the annotation processor resolves a type for SimpleLombokPojo // that is resolved (compiled) and the source annotations are gone. Because we // don't see the @Data annotation anymore, no field is harvested. What is crazy is @@ -124,43 +112,38 @@ public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTes @Test public void lombokInnerClassWithGetterProperties() { - ConfigurationMetadata metadata = compile( - LombokInnerClassWithGetterProperties.class); - assertThat(metadata).has(Metadata.withGroup("config") - .fromSource(LombokInnerClassWithGetterProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first") - .ofType(LombokInnerClassWithGetterProperties.Foo.class) - .fromSourceMethod("getFirst()") - .fromSource(LombokInnerClassWithGetterProperties.class)); + ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class); + assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class)); + assertThat(metadata) + .has(Metadata.withGroup("config.first").ofType(LombokInnerClassWithGetterProperties.Foo.class) + .fromSourceMethod("getFirst()").fromSource(LombokInnerClassWithGetterProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata.getItems()).hasSize(3); } - private void assertSimpleLombokProperties(ConfigurationMetadata metadata, - Class source, String prefix) { + private void assertSimpleLombokProperties(ConfigurationMetadata metadata, Class source, String prefix) { assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class) - .fromSource(source).withDescription("Name description.")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class).fromSource(source) + .withDescription("Name description.")); assertThat(metadata).has(Metadata.withProperty(prefix + ".description")); assertThat(metadata).has(Metadata.withProperty(prefix + ".counter")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".number") - .fromSource(source).withDefaultValue(0).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".number").fromSource(source).withDefaultValue(0) + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty(prefix + ".items")); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored")); } - private void assertAccessLevelOverwriteLombokProperties( - ConfigurationMetadata metadata, Class source, String prefix) { + private void assertAccessLevelOverwriteLombokProperties(ConfigurationMetadata metadata, Class source, + String prefix) { assertAccessLevelLombokProperties(metadata, source, prefix, 7); } - private void assertAccessLevelLombokProperties(ConfigurationMetadata metadata, - Class source, String prefix, int countNameFields) { + private void assertAccessLevelLombokProperties(ConfigurationMetadata metadata, Class source, String prefix, + int countNameFields) { assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); for (int i = 0; i < countNameFields; i++) { - assertThat(metadata) - .has(Metadata.withProperty(prefix + ".name" + i, String.class)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name" + i, String.class)); } assertThat(metadata.getItems()).hasSize(1 + countNameFields); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java index 2f8ea533af0..fd775fac688 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java @@ -45,10 +45,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void lombokSimpleProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "name"); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); assertThat(property.getName()).isEqualTo("name"); assertThat(property.getSource()).isSameAs(property.getField()); assertThat(property.getField().getSimpleName()).hasToString("name"); @@ -60,10 +58,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void lombokCollectionProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "items"); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items"); assertThat(property.getName()).isEqualTo("items"); assertThat(property.getSource()).isSameAs(property.getField()); assertThat(property.getField().getSimpleName()).hasToString("items"); @@ -75,10 +71,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void lombokNestedPropertySameClass() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokInnerClassProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "first"); + TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertThat(property.getName()).isEqualTo("first"); assertThat(property.getSource()).isSameAs(property.getField()); assertThat(property.getField().getSimpleName()).hasToString("first"); @@ -90,10 +84,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void lombokNestedPropertyWithAnnotation() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokInnerClassProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "third"); + TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third"); assertThat(property.getName()).isEqualTo("third"); assertThat(property.getSource()).isSameAs(property.getField()); assertThat(property.getField().getSimpleName()).hasToString("third"); @@ -103,52 +95,40 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() - throws IOException { + public void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "ignored"); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored"); assertThat(property.isProperty(metadataEnv)).isFalse(); assertThat(property.isNested(metadataEnv)).isFalse(); }); } @Test - public void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() - throws IOException { + public void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() throws IOException { process(LombokSimpleDataProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleDataProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "ignored"); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleDataProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored"); assertThat(property.isProperty(metadataEnv)).isFalse(); assertThat(property.isNested(metadataEnv)).isFalse(); }); } @Test - public void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() - throws IOException { + public void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() throws IOException { process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokExplicitProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "ignoredOnlyGetter"); + TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlyGetter"); assertThat(property.isProperty(metadataEnv)).isFalse(); assertThat(property.isNested(metadataEnv)).isFalse(); }); } @Test - public void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() - throws IOException { + public void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() throws IOException { process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokExplicitProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "ignoredOnlySetter"); + TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlySetter"); assertThat(property.isProperty(metadataEnv)).isFalse(); assertThat(property.isNested(metadataEnv)).isFalse(); }); @@ -157,70 +137,56 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void lombokMetadataSimpleProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "description"); - assertItemMetadata(metadataEnv, property).isProperty() - .hasName("test.description").hasType(String.class) - .hasSourceType(LombokSimpleProperties.class).hasNoDescription() - .isNotDeprecated(); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description"); + assertItemMetadata(metadataEnv, property).isProperty().hasName("test.description").hasType(String.class) + .hasSourceType(LombokSimpleProperties.class).hasNoDescription().isNotDeprecated(); }); } @Test public void lombokMetadataCollectionProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "items"); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items"); assertItemMetadata(metadataEnv, property).isProperty().hasName("test.items") - .hasType("java.util.List") - .hasSourceType(LombokSimpleProperties.class).hasNoDescription() - .isNotDeprecated(); + .hasType("java.util.List").hasSourceType(LombokSimpleProperties.class) + .hasNoDescription().isNotDeprecated(); }); } @Test public void lombokMetadataNestedGroup() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokInnerClassProperties.class); + TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); VariableElement field = getField(ownerElement, "third"); ExecutableElement getter = getMethod(ownerElement, "getThird"); - LombokPropertyDescriptor property = new LombokPropertyDescriptor(ownerElement, - null, field, "third", field.asType(), getter, null); + LombokPropertyDescriptor property = new LombokPropertyDescriptor(ownerElement, null, field, "third", + field.asType(), getter, null); assertItemMetadata(metadataEnv, property).isGroup().hasName("test.third") - .hasType( - "org.springframework.boot.configurationsample.lombok.SimpleLombokPojo") - .hasSourceType(LombokInnerClassProperties.class) - .hasSourceMethod("getThird()").hasNoDescription().isNotDeprecated(); + .hasType("org.springframework.boot.configurationsample.lombok.SimpleLombokPojo") + .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod("getThird()").hasNoDescription() + .isNotDeprecated(); }); } @Test public void lombokMetadataNestedGroupNoGetter() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokInnerClassProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "first"); + TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType( - "org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo") - .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod(null) - .hasNoDescription().isNotDeprecated(); + .hasType("org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo") + .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod(null).hasNoDescription() + .isNotDeprecated(); }); } @Test public void lombokMetadataNotACandidatePropertyShouldReturnNull() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "ignored"); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored"); assertThat(property.resolveItemMetadata("test", metadataEnv)).isNull(); }); } @@ -232,46 +198,35 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement( org.springframework.boot.configurationsample.lombok.LombokDeprecatedProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor( - ownerElement, "name"); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithNoInformation(); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); } @Test public void lombokDeprecatedPropertyOnField() throws IOException { process(LombokDeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokDeprecatedSingleProperty.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "name"); - assertItemMetadata(metadataEnv, property).isProperty() - .isDeprecatedWithNoInformation(); + TypeElement ownerElement = roundEnv.getRootElement(LombokDeprecatedSingleProperty.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); + assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); } @Test public void lombokPropertyWithDescription() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokSimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "name"); - assertItemMetadata(metadataEnv, property).isProperty() - .hasDescription("Name description."); + TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); + assertItemMetadata(metadataEnv, property).isProperty().hasDescription("Name description."); }); } @Test public void lombokPropertyWithDefaultValue() throws IOException { process(LombokDefaultValueProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(LombokDefaultValueProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "description"); - assertItemMetadata(metadataEnv, property).isProperty() - .hasDefaultValue("my description"); + TypeElement ownerElement = roundEnv.getRootElement(LombokDefaultValueProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description"); + assertItemMetadata(metadataEnv, property).isProperty().hasDefaultValue("my description"); }); } @@ -279,8 +234,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { public void lombokPropertyNotCandidate() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "theName"); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertThat(property.isProperty(metadataEnv)).isFalse(); assertThat(property.isNested(metadataEnv)).isFalse(); }); @@ -289,24 +243,18 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test public void lombokNestedPropertyNotCandidate() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv - .getRootElement(InnerClassProperties.class); - LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, - "first"); + TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); + LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); assertThat(property.isProperty(metadataEnv)).isFalse(); assertThat(property.isNested(metadataEnv)).isFalse(); }); } - protected LombokPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, - String name) { + protected LombokPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name) { VariableElement field = getField(ownerElement, name); - ExecutableElement getter = getMethod(ownerElement, - createAccessorMethodName("get", name)); - ExecutableElement setter = getMethod(ownerElement, - createAccessorMethodName("set", name)); - return new LombokPropertyDescriptor(ownerElement, null, field, name, - field.asType(), getter, setter); + ExecutableElement getter = getMethod(ownerElement, createAccessorMethodName("get", name)); + ExecutableElement setter = getMethod(ownerElement, createAccessorMethodName("set", name)); + return new LombokPropertyDescriptor(ownerElement, null, field, name, field.asType(), getter, setter); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java index 3111b181c84..77313795f9f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java @@ -56,114 +56,96 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); - assertThat(metadata).has(Metadata.withProperty("foo", String.class) - .fromSource(AdditionalMetadata.class)); + assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class)); } @Test public void mergingOfAdditionalPropertyMatchingGroup() throws Exception { - ItemMetadata property = ItemMetadata.newProperty(null, "simple", - "java.lang.String", null, null, null, null, null); + ItemMetadata property = ItemMetadata.newProperty(null, "simple", "java.lang.String", null, null, null, null, + null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple", String.class)); } @Test public void mergeExistingPropertyDefaultValue() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, - null, null, true, null); + ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) - .fromSource(SimpleProperties.class).withDescription("A simple flag.") - .withDeprecation(null, null).withDefaultValue(true)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class) + .withDescription("A simple flag.").withDeprecation(null, null).withDefaultValue(true)); assertThat(metadata.getItems()).hasSize(4); } @Test public void mergeExistingPropertyWithSeveralCandidates() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "flag", - Boolean.class.getName(), null, null, null, true, null); + ItemMetadata property = ItemMetadata.newProperty("simple", "flag", Boolean.class.getName(), null, null, null, + true, null); writeAdditionalMetadata(property); - ConfigurationMetadata metadata = compile(SimpleProperties.class, - SimpleConflictingProperties.class); + ConfigurationMetadata metadata = compile(SimpleProperties.class, SimpleConflictingProperties.class); assertThat(metadata.getItems()).hasSize(6); - List items = metadata.getItems().stream() - .filter((item) -> item.getName().equals("simple.flag")) + List items = metadata.getItems().stream().filter((item) -> item.getName().equals("simple.flag")) .collect(Collectors.toList()); assertThat(items).hasSize(2); - ItemMetadata matchingProperty = items.stream() - .filter((item) -> item.getType().equals(Boolean.class.getName())) + ItemMetadata matchingProperty = items.stream().filter((item) -> item.getType().equals(Boolean.class.getName())) .findFirst().orElse(null); assertThat(matchingProperty).isNotNull(); assertThat(matchingProperty.getDefaultValue()).isEqualTo(true); - assertThat(matchingProperty.getSourceType()) - .isEqualTo(SimpleProperties.class.getName()); + assertThat(matchingProperty.getSourceType()).isEqualTo(SimpleProperties.class.getName()); assertThat(matchingProperty.getDescription()).isEqualTo("A simple flag."); ItemMetadata nonMatchingProperty = items.stream() - .filter((item) -> item.getType().equals(String.class.getName())) - .findFirst().orElse(null); + .filter((item) -> item.getType().equals(String.class.getName())).findFirst().orElse(null); assertThat(nonMatchingProperty).isNotNull(); assertThat(nonMatchingProperty.getDefaultValue()).isEqualTo("hello"); - assertThat(nonMatchingProperty.getSourceType()) - .isEqualTo(SimpleConflictingProperties.class.getName()); + assertThat(nonMatchingProperty.getSourceType()).isEqualTo(SimpleConflictingProperties.class.getName()); assertThat(nonMatchingProperty.getDescription()).isNull(); } @Test public void mergeExistingPropertyDescription() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, - null, null, "A nice comparator.", null, null); + ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, "A nice comparator.", + null, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withProperty("simple.comparator", "java.util.Comparator") - .fromSource(SimpleProperties.class) - .withDescription("A nice comparator.")); + assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator") + .fromSource(SimpleProperties.class).withDescription("A nice comparator.")); assertThat(metadata.getItems()).hasSize(4); } @Test public void mergeExistingPropertyDeprecation() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, - null, null, null, null, new ItemDeprecation("Don't use this.", - "simple.complex-comparator", "error")); + ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, null, null, + new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withProperty("simple.comparator", "java.util.Comparator") - .fromSource(SimpleProperties.class).withDeprecation( - "Don't use this.", "simple.complex-comparator", "error")); + assertThat(metadata).has( + Metadata.withProperty("simple.comparator", "java.util.Comparator").fromSource(SimpleProperties.class) + .withDeprecation("Don't use this.", "simple.complex-comparator", "error")); assertThat(metadata.getItems()).hasSize(4); } @Test public void mergeExistingPropertyDeprecationOverride() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, - null, null, null, null, + ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null, new ItemDeprecation("Don't use this.", "single.name")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); - assertThat(metadata).has( - Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class) - .withDeprecation("Don't use this.", "single.name")); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) + .fromSource(DeprecatedSingleProperty.class).withDeprecation("Don't use this.", "single.name")); assertThat(metadata.getItems()).hasSize(3); } @Test public void mergeExistingPropertyDeprecationOverrideLevel() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, - null, null, null, null, new ItemDeprecation(null, null, "error")); + ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null, + new ItemDeprecation(null, null, "error")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); - assertThat(metadata).has( - Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class).withDeprecation( - "renamed", "singledeprecated.new-name", "error")); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) + .fromSource(DeprecatedSingleProperty.class) + .withDeprecation("renamed", "singledeprecated.new-name", "error")); assertThat(metadata.getItems()).hasSize(3); } @@ -171,70 +153,59 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest public void mergeOfInvalidAdditionalMetadata() throws IOException { File additionalMetadataFile = createAdditionalMetadataFile(); FileCopyUtils.copy("Hello World", new FileWriter(additionalMetadataFile)); - assertThatIllegalStateException() - .isThrownBy(() -> compile(SimpleProperties.class)) + assertThatIllegalStateException().isThrownBy(() -> compile(SimpleProperties.class)) .withMessage("Compilation failed"); } @Test public void mergingOfSimpleHint() throws Exception { - writeAdditionalHints(ItemHint.newHint("simple.the-name", - new ItemHint.ValueHint("boot", "Bla bla"), + writeAdditionalHints(ItemHint.newHint("simple.the-name", new ItemHint.ValueHint("boot", "Bla bla"), new ItemHint.ValueHint("spring", null))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withHint("simple.the-name") - .withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); + assertThat(metadata) + .has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); } @Test public void mergingOfHintWithNonCanonicalName() throws Exception { - writeAdditionalHints(ItemHint.newHint("simple.theName", - new ItemHint.ValueHint("boot", "Bla bla"))); + writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has( - Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); + assertThat(metadata).has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); } @Test public void mergingOfHintWithProvider() throws Exception { writeAdditionalHints(new ItemHint("simple.theName", Collections.emptyList(), - Arrays.asList( - new ItemHint.ValueProvider("first", - Collections.singletonMap("target", "org.foo")), + Arrays.asList(new ItemHint.ValueProvider("first", Collections.singletonMap("target", "org.foo")), new ItemHint.ValueProvider("second", null)))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withHint("simple.the-name") - .withProvider("first", "target", "org.foo").withProvider("second")); + assertThat(metadata).has( + Metadata.withHint("simple.the-name").withProvider("first", "target", "org.foo").withProvider("second")); } @Test public void mergingOfAdditionalDeprecation() throws Exception { - writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", - "java.lang.String", null, null, null, null, - new ItemDeprecation("Lame name.", "simple.the-name"))); + writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null, + null, new ItemDeprecation("Lame name.", "simple.the-name"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class) - .withDeprecation("Lame name.", "simple.the-name")); + assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class).withDeprecation("Lame name.", + "simple.the-name")); } @Test public void mergingOfAdditionalMetadata() throws Exception { File metaInfFolder = new File(getCompiler().getOutputLocation(), "META-INF"); metaInfFolder.mkdirs(); - File additionalMetadataFile = new File(metaInfFolder, - "additional-spring-configuration-metadata.json"); + File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json"); additionalMetadataFile.createNewFile(); JSONObject property = new JSONObject(); property.put("name", "foo"); @@ -250,8 +221,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest writer.close(); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); - assertThat(metadata).has(Metadata.withProperty("foo", String.class) - .fromSource(AdditionalMetadata.class)); + assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class)); } private void writeAdditionalMetadata(ItemMetadata... metadata) throws Exception { @@ -305,8 +275,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest private File createAdditionalMetadataFile() throws IOException { File metaInfFolder = new File(getCompiler().getOutputLocation(), "META-INF"); metaInfFolder.mkdirs(); - File additionalMetadataFile = new File(metaInfFolder, - "additional-spring-configuration-metadata.json"); + File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json"); additionalMetadataFile.createNewFile(); return additionalMetadataFile; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironmentFactory.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironmentFactory.java index d86f2b63114..e42347fc080 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironmentFactory.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironmentFactory.java @@ -27,8 +27,7 @@ import org.springframework.boot.configurationprocessor.test.TestConfigurationMet * * @author Stephane Nicoll */ -class MetadataGenerationEnvironmentFactory - implements Function { +class MetadataGenerationEnvironmentFactory implements Function { @Override public MetadataGenerationEnvironment apply(ProcessingEnvironment environment) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java index 4945cfcd22c..b18a324c7f6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,13 +50,11 @@ public class MetadataStoreTests { File classesLocation = new File(app, "target/classes"); File metaInf = new File(classesLocation, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - assertThat( - this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation, - "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + assertThat(this.metadataStore.locateAdditionalMetadataFile( + new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) + .isEqualTo(additionalMetadata); } @Test @@ -66,13 +64,11 @@ public class MetadataStoreTests { File resourcesLocation = new File(app, "build/resources/main"); File metaInf = new File(resourcesLocation, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - assertThat( - this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation, - "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + assertThat(this.metadataStore.locateAdditionalMetadataFile( + new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) + .isEqualTo(additionalMetadata); } @Test @@ -82,13 +78,11 @@ public class MetadataStoreTests { File resourcesLocation = new File(app, "build/resources/main"); File metaInf = new File(resourcesLocation, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - assertThat( - this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation, - "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + assertThat(this.metadataStore.locateAdditionalMetadataFile( + new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) + .isEqualTo(additionalMetadata); } @Test @@ -97,14 +91,12 @@ public class MetadataStoreTests { File location = new File(app, "src/main/resources"); File metaInf = new File(location, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - given(this.environment.getOptions()).willReturn(Collections.singletonMap( - ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION, - location.getAbsolutePath())); - assertThat(this.metadataStore.locateAdditionalMetadataFile(new File(app, "foo"))) - .isEqualTo(additionalMetadata); + given(this.environment.getOptions()).willReturn( + Collections.singletonMap(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION, + location.getAbsolutePath())); + assertThat(this.metadataStore.locateAdditionalMetadataFile(new File(app, "foo"))).isEqualTo(additionalMetadata); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java index 9429043826e..c8dd32216c2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java @@ -38,31 +38,30 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati @Test public void simpleMethodConfig() { ConfigurationMetadata metadata = compile(SimpleMethodConfig.class); + assertThat(metadata).has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class)); assertThat(metadata) - .has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class)); - assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) + .has(Metadata.withProperty("foo.name", String.class).fromSource(SimpleMethodConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) .fromSource(SimpleMethodConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) - .withDefaultValue(false).fromSource(SimpleMethodConfig.Foo.class)); } @Test public void invalidMethodConfig() { ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); - assertThat(metadata).has(Metadata.withProperty("something.name", String.class) - .fromSource(InvalidMethodConfig.class)); + assertThat(metadata) + .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name")); } @Test public void methodAndClassConfig() { ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); - assertThat(metadata).has(Metadata.withProperty("conflict.name", String.class) + assertThat(metadata) + .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class).withDefaultValue(false) .fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class) - .withDefaultValue(false).fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("conflict.value", String.class) - .fromSource(MethodAndClassConfig.class)); + assertThat(metadata) + .has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class)); } @Test @@ -77,11 +76,9 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(DeprecatedMethodConfig.Foo.class) - .withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) - .withDefaultValue(false).fromSource(DeprecatedMethodConfig.Foo.class) - .withDeprecation(null, null)); + .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) + .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); } @Test @@ -91,13 +88,10 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource( - org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) .withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) - .withDefaultValue(false) - .fromSource( - org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) .withDeprecation(null, null)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java index 22e83e81c2c..16d319c4559 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java @@ -59,90 +59,76 @@ public class PropertyDescriptorResolverTests { @Test public void propertiesWithJavaBeanProperties() throws IOException { - process(SimpleProperties.class, propertyNames((stream) -> assertThat(stream) - .containsExactly("theName", "flag", "comparator"))); + process(SimpleProperties.class, + propertyNames((stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator"))); } @Test public void propertiesWithJavaBeanHierarchicalProperties() throws IOException { process(HierarchicalProperties.class, - Arrays.asList(HierarchicalPropertiesParent.class, - HierarchicalPropertiesGrandparent.class), + Arrays.asList(HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class), (type, metadataEnv) -> { - PropertyDescriptorResolver resolver = new PropertyDescriptorResolver( - metadataEnv); - assertThat( - resolver.resolve(type, null).map(PropertyDescriptor::getName)) - .containsExactly("third", "second", "first"); + PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(metadataEnv); + assertThat(resolver.resolve(type, null).map(PropertyDescriptor::getName)).containsExactly("third", + "second", "first"); assertThat(resolver.resolve(type, null) - .map((descriptor) -> descriptor.resolveItemMetadata("test", - metadataEnv)) - .map(ItemMetadata::getDefaultValue)).containsExactly("three", - "two", "one"); + .map((descriptor) -> descriptor.resolveItemMetadata("test", metadataEnv)) + .map(ItemMetadata::getDefaultValue)).containsExactly("three", "two", "one"); }); } @Test public void propertiesWithLombokGetterSetterAtClassLevel() throws IOException { - process(LombokSimpleProperties.class, propertyNames((stream) -> assertThat(stream) - .containsExactly("name", "description", "counter", "number", "items"))); + process(LombokSimpleProperties.class, propertyNames( + (stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items"))); } @Test public void propertiesWithLombokGetterSetterAtFieldLevel() throws IOException { - process(LombokExplicitProperties.class, - propertyNames((stream) -> assertThat(stream).containsExactly("name", - "description", "counter", "number", "items"))); + process(LombokExplicitProperties.class, propertyNames( + (stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items"))); } @Test public void propertiesWithLombokDataClass() throws IOException { - process(LombokSimpleDataProperties.class, - propertyNames((stream) -> assertThat(stream).containsExactly("name", - "description", "counter", "number", "items"))); + process(LombokSimpleDataProperties.class, propertyNames( + (stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items"))); } @Test public void propertiesWithConstructorParameters() throws IOException { - process(ImmutableSimpleProperties.class, - propertyNames((stream) -> assertThat(stream).containsExactly("theName", - "flag", "comparator", "counter"))); + process(ImmutableSimpleProperties.class, propertyNames( + (stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator", "counter"))); } @Test public void propertiesWithSeveralConstructors() throws IOException { + process(TwoConstructorsExample.class, propertyNames((stream) -> assertThat(stream).containsExactly("name"))); process(TwoConstructorsExample.class, - propertyNames((stream) -> assertThat(stream).containsExactly("name"))); - process(TwoConstructorsExample.class, properties((stream) -> assertThat(stream) - .element(0).isInstanceOf(JavaBeanPropertyDescriptor.class))); + properties((stream) -> assertThat(stream).element(0).isInstanceOf(JavaBeanPropertyDescriptor.class))); } private BiConsumer properties( Consumer>> stream) { return (element, metadataEnv) -> { - PropertyDescriptorResolver resolver = new PropertyDescriptorResolver( - metadataEnv); + PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(metadataEnv); stream.accept(resolver.resolve(element, null)); }; } - private BiConsumer propertyNames( - Consumer> stream) { - return properties( - (result) -> stream.accept(result.map(PropertyDescriptor::getName))); + private BiConsumer propertyNames(Consumer> stream) { + return properties((result) -> stream.accept(result.map(PropertyDescriptor::getName))); } - private void process(Class target, - BiConsumer consumer) + private void process(Class target, BiConsumer consumer) throws IOException { process(target, Collections.emptyList(), consumer); } private void process(Class target, Collection> additionalClasses, - BiConsumer consumer) - throws IOException { - BiConsumer internalConsumer = ( - roundEnv, metadataEnv) -> { + BiConsumer consumer) throws IOException { + BiConsumer internalConsumer = (roundEnv, + metadataEnv) -> { TypeElement element = roundEnv.getRootElement(target); consumer.accept(element, metadataEnv); }; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java index 35b4bc4bf16..b715f2122bd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java @@ -50,24 +50,23 @@ public abstract class PropertyDescriptorTests { } protected ExecutableElement getMethod(TypeElement element, String name) { - return ElementFilter.methodsIn(element.getEnclosedElements()).stream().filter( - (method) -> ((Element) method).getSimpleName().toString().equals(name)) - .findFirst().orElse(null); + return ElementFilter.methodsIn(element.getEnclosedElements()).stream() + .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst() + .orElse(null); } protected VariableElement getField(TypeElement element, String name) { - return ElementFilter.fieldsIn(element.getEnclosedElements()).stream().filter( - (method) -> ((Element) method).getSimpleName().toString().equals(name)) - .findFirst().orElse(null); + return ElementFilter.fieldsIn(element.getEnclosedElements()).stream() + .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst() + .orElse(null); } - protected ItemMetadataAssert assertItemMetadata( - MetadataGenerationEnvironment metadataEnv, PropertyDescriptor property) { + protected ItemMetadataAssert assertItemMetadata(MetadataGenerationEnvironment metadataEnv, + PropertyDescriptor property) { return new ItemMetadataAssert(property.resolveItemMetadata("test", metadataEnv)); } - protected void process(Class target, - BiConsumer consumer) + protected void process(Class target, BiConsumer consumer) throws IOException { TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>( consumer, new MetadataGenerationEnvironmentFactory()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java index 67c4e9d4fbd..6b733b5d836 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java @@ -64,8 +64,7 @@ public class TestProject { private Set sourceFiles = new LinkedHashSet<>(); - public TestProject(TemporaryFolder tempFolder, Class... classes) - throws IOException { + public TestProject(TemporaryFolder tempFolder, Class... classes) throws IOException { this.sourceFolder = tempFolder.newFolder(); this.compiler = new TestCompiler(tempFolder) { @Override @@ -134,15 +133,12 @@ public class TestProject { * @param snippetStream the snippet stream * @throws Exception if the source cannot be added */ - public void addSourceCode(Class target, InputStream snippetStream) - throws Exception { + public void addSourceCode(Class target, InputStream snippetStream) throws Exception { File targetFile = getSourceFile(target); String contents = getContents(targetFile); int insertAt = contents.lastIndexOf('}'); - String additionalSource = FileCopyUtils - .copyToString(new InputStreamReader(snippetStream)); - contents = contents.substring(0, insertAt) + additionalSource - + contents.substring(insertAt); + String additionalSource = FileCopyUtils.copyToString(new InputStreamReader(snippetStream)); + contents = contents.substring(0, insertAt) + additionalSource + contents.substring(insertAt); putContents(targetFile, contents); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java index 53e32d3da9b..f5c701ac003 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java @@ -47,17 +47,13 @@ public class TypeUtilsTests { @Test public void resolveTypeDescriptorOnConcreteClass() throws IOException { process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> { - TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor( - roundEnv.getRootElement(SimpleGenericProperties.class)); - assertThat( - typeDescriptor.getGenerics().keySet().stream().map(Object::toString)) - .containsOnly("A", "B", "C"); - assertThat(typeDescriptor.resolveGeneric("A")) - .hasToString(String.class.getName()); - assertThat(typeDescriptor.resolveGeneric("B")) - .hasToString(Integer.class.getName()); - assertThat(typeDescriptor.resolveGeneric("C")) - .hasToString(Duration.class.getName()); + TypeDescriptor typeDescriptor = typeUtils + .resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class)); + assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", + "C"); + assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName()); + assertThat(typeDescriptor.resolveGeneric("B")).hasToString(Integer.class.getName()); + assertThat(typeDescriptor.resolveGeneric("C")).hasToString(Duration.class.getName()); }); } @@ -65,15 +61,12 @@ public class TypeUtilsTests { @Test public void resolveTypeDescriptorOnIntermediateClass() throws IOException { process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> { - TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor( - roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); - assertThat( - typeDescriptor.getGenerics().keySet().stream().map(Object::toString)) - .containsOnly("A", "B", "C"); - assertThat(typeDescriptor.resolveGeneric("A")) - .hasToString(String.class.getName()); - assertThat(typeDescriptor.resolveGeneric("B")) - .hasToString(Integer.class.getName()); + TypeDescriptor typeDescriptor = typeUtils + .resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); + assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", + "C"); + assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName()); + assertThat(typeDescriptor.resolveGeneric("B")).hasToString(Integer.class.getName()); assertThat(typeDescriptor.resolveGeneric("C")).hasToString("C"); }); } @@ -81,19 +74,16 @@ public class TypeUtilsTests { @Test public void resolveTypeDescriptorWithOnlyGenerics() throws IOException { process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> { - TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor( - roundEnv.getRootElement(AbstractGenericProperties.class)); - assertThat( - typeDescriptor.getGenerics().keySet().stream().map(Object::toString)) - .containsOnly("A", "B", "C"); + TypeDescriptor typeDescriptor = typeUtils + .resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class)); + assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", + "C"); }); } - private void process(Class target, - BiConsumer consumer) throws IOException { - TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>( - consumer, TypeUtils::new); + private void process(Class target, BiConsumer consumer) throws IOException { + TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>(consumer, TypeUtils::new); TestCompiler compiler = new TestCompiler(this.temporaryFolder); compiler.getTask(target).call(processor); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index 040ba8765cc..0e7c733562c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,8 +84,7 @@ public abstract class AbstractFieldValuesProcessorTests { assertThat(values.get("stringArrayNone")).isNull(); assertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]); assertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" }); - assertThat(values.get("stringArrayConstElements")) - .isEqualTo(new Object[] { "c" }); + assertThat(values.get("stringArrayConstElements")).isEqualTo(new Object[] { "c" }); assertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 }); assertThat(values.get("unknownArray")).isNull(); assertThat(values.get("durationNone")).isNull(); @@ -103,8 +102,7 @@ public abstract class AbstractFieldValuesProcessorTests { assertThat(values.get("dataSizeTerabytes")).isEqualTo("40TB"); } - @SupportedAnnotationTypes({ - "org.springframework.boot.configurationsample.ConfigurationProperties" }) + @SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" }) @SupportedSourceVersion(SourceVersion.RELEASE_6) private class TestProcessor extends AbstractProcessor { @@ -118,14 +116,12 @@ public abstract class AbstractFieldValuesProcessorTests { } @Override - public boolean process(Set annotations, - RoundEnvironment roundEnv) { + public boolean process(Set annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { if (element instanceof TypeElement) { try { - this.values.putAll( - this.processor.getFieldValues((TypeElement) element)); + this.values.putAll(this.processor.getFieldValues((TypeElement) element)); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java index 4ceed8e9d46..5573ab9aef1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import static org.junit.Assume.assumeNoException; * * @author Phillip Webb */ -public class JavaCompilerFieldValuesProcessorTests - extends AbstractFieldValuesProcessorTests { +public class JavaCompilerFieldValuesProcessorTests extends AbstractFieldValuesProcessorTests { @Override protected FieldValuesParser createProcessor(ProcessingEnvironment env) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java index eb13427767c..1bdfa8ab66a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,14 +44,12 @@ public class ConfigurationMetadataTests { @Test public void toDashedCaseWordsUnderscore() { - assertThat(toDashedCase("Word_With_underscore")) - .isEqualTo("word-with-underscore"); + assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore"); } @Test public void toDashedCaseWordsSeveralUnderscores() { - assertThat(toDashedCase("Word___With__underscore")) - .isEqualTo("word---with--underscore"); + assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java index b7af5f22775..02a1467c7f5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,14 +34,12 @@ public class ItemMetadataTests { @Test public void newItemMetadataPrefixWithCamelCaseSuffix() { - assertThat(newItemMetadataPrefix("prefix.", "myValue")) - .isEqualTo("prefix.my-value"); + assertThat(newItemMetadataPrefix("prefix.", "myValue")).isEqualTo("prefix.my-value"); } @Test public void newItemMetadataPrefixWithUpperCamelCaseSuffix() { - assertThat(newItemMetadataPrefix("prefix.", "MyValue")) - .isEqualTo("prefix.my-value"); + assertThat(newItemMetadataPrefix("prefix.", "MyValue")).isEqualTo("prefix.my-value"); } private String newItemMetadataPrefix(String prefix, String suffix) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java index 8655cce6d1e..3572079362e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,49 +38,34 @@ public class JsonMarshallerTests { @Test public void marshallAndUnmarshal() throws Exception { ConfigurationMetadata metadata = new ConfigurationMetadata(); - metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), - InputStream.class.getName(), "sourceMethod", "desc", "x", - new ItemDeprecation("Deprecation comment", "b.c.d"))); - metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null, - null)); - metadata.add( - ItemMetadata.newProperty("c", null, null, null, null, null, 123, null)); - metadata.add( - ItemMetadata.newProperty("d", null, null, null, null, null, true, null)); - metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null, - new String[] { "y", "n" }, null)); - metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null, - new Boolean[] { true, false }, null)); + metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), InputStream.class.getName(), + "sourceMethod", "desc", "x", new ItemDeprecation("Deprecation comment", "b.c.d"))); + metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("c", null, null, null, null, null, 123, null)); + metadata.add(ItemMetadata.newProperty("d", null, null, null, null, null, true, null)); + metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null, new String[] { "y", "n" }, null)); + metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null, new Boolean[] { true, false }, null)); metadata.add(ItemMetadata.newGroup("d", null, null, null)); metadata.add(ItemHint.newHint("a.b")); - metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"), - new ItemHint.ValueHint(456, null))); + metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"), new ItemHint.ValueHint(456, null))); metadata.add(new ItemHint("d", null, - Arrays.asList( - new ItemHint.ValueProvider("first", - Collections.singletonMap("target", "foo")), + Arrays.asList(new ItemHint.ValueProvider("first", Collections.singletonMap("target", "foo")), new ItemHint.ValueProvider("second", null)))); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); - ConfigurationMetadata read = marshaller - .read(new ByteArrayInputStream(outputStream.toByteArray())); - assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class) - .fromSource(InputStream.class).withDescription("desc") - .withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); + ConfigurationMetadata read = marshaller.read(new ByteArrayInputStream(outputStream.toByteArray())); + assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class).fromSource(InputStream.class) + .withDescription("desc").withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); assertThat(read).has(Metadata.withProperty("b.c.d")); assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123)); assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true)); - assertThat(read).has( - Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" })); - assertThat(read).has(Metadata.withProperty("f") - .withDefaultValue(new Object[] { true, false })); + assertThat(read).has(Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" })); + assertThat(read).has(Metadata.withProperty("f").withDefaultValue(new Object[] { true, false })); assertThat(read).has(Metadata.withGroup("d")); assertThat(read).has(Metadata.withHint("a.b")); - assertThat(read).has( - Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); - assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo") - .withProvider("second")); + assertThat(read).has(Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); + assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo").withProvider("second")); } @Test @@ -88,45 +73,35 @@ public class JsonMarshallerTests { ConfigurationMetadata metadata = new ConfigurationMetadata(); metadata.add(ItemHint.newHint("fff")); metadata.add(ItemHint.newHint("eee")); - metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, - null, null, null, null)); - metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, - null, null, null, null)); - metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, - null, null, null, null)); - metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, - null, null, null, null)); - metadata.add(ItemMetadata.newGroup("com.acme.bravo", - "com.example.AnotherTestProperties", null, null)); - metadata.add(ItemMetadata.newGroup("com.acme.alpha", "com.example.TestProperties", - null, null)); + metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, null, null, null, null)); + metadata.add(ItemMetadata.newGroup("com.acme.bravo", "com.example.AnotherTestProperties", null, null)); + metadata.add(ItemMetadata.newGroup("com.acme.alpha", "com.example.TestProperties", null, null)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); String json = new String(outputStream.toByteArray()); - assertThat(json).containsSubsequence("\"groups\"", "\"com.acme.alpha\"", - "\"com.acme.bravo\"", "\"properties\"", "\"com.example.alpha.ccc\"", - "\"com.example.alpha.ddd\"", "\"com.example.bravo.aaa\"", + assertThat(json).containsSubsequence("\"groups\"", "\"com.acme.alpha\"", "\"com.acme.bravo\"", "\"properties\"", + "\"com.example.alpha.ccc\"", "\"com.example.alpha.ddd\"", "\"com.example.bravo.aaa\"", "\"com.example.bravo.bbb\"", "\"hints\"", "\"eee\"", "\"fff\""); } @Test public void marshallPutDeprecatedItemsAtTheEnd() throws IOException { ConfigurationMetadata metadata = new ConfigurationMetadata(); - metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, - null, null, null, null)); - metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, - null, null, null, new ItemDeprecation(null, null, "warning"))); - metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, - null, null, null, null)); - metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, - null, null, null, new ItemDeprecation(null, null, "warning"))); + metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null, + new ItemDeprecation(null, null, "warning"))); + metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, null, null, null, + new ItemDeprecation(null, null, "warning"))); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); String json = new String(outputStream.toByteArray()); - assertThat(json).containsSubsequence("\"properties\"", - "\"com.example.alpha.ddd\"", "\"com.example.bravo.bbb\"", + assertThat(json).containsSubsequence("\"properties\"", "\"com.example.alpha.ddd\"", "\"com.example.bravo.bbb\"", "\"com.example.alpha.ccc\"", "\"com.example.bravo.aaa\""); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java index e16d085cc87..84366a989c7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java @@ -92,9 +92,8 @@ public final class Metadata { this(itemType, name, null, null, null, null, null, null); } - public MetadataItemCondition(ItemType itemType, String name, String type, - Class sourceType, String sourceMethod, String description, - Object defaultValue, ItemDeprecation deprecation) { + public MetadataItemCondition(ItemType itemType, String name, String type, Class sourceType, + String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { this.itemType = itemType; this.name = name; this.type = type; @@ -139,90 +138,76 @@ public final class Metadata { if (this.type != null && !this.type.equals(itemMetadata.getType())) { return false; } - if (this.sourceType != null - && !this.sourceType.getName().equals(itemMetadata.getSourceType())) { + if (this.sourceType != null && !this.sourceType.getName().equals(itemMetadata.getSourceType())) { return false; } - if (this.sourceMethod != null - && !this.sourceMethod.equals(itemMetadata.getSourceMethod())) { + if (this.sourceMethod != null && !this.sourceMethod.equals(itemMetadata.getSourceMethod())) { return false; } - if (this.defaultValue != null && !ObjectUtils - .nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) { + if (this.defaultValue != null + && !ObjectUtils.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) { return false; } if (this.defaultValue == null && itemMetadata.getDefaultValue() != null) { return false; } - if (this.description != null - && !this.description.equals(itemMetadata.getDescription())) { + if (this.description != null && !this.description.equals(itemMetadata.getDescription())) { return false; } if (this.deprecation == null && itemMetadata.getDeprecation() != null) { return false; } - if (this.deprecation != null - && !this.deprecation.equals(itemMetadata.getDeprecation())) { + if (this.deprecation != null && !this.deprecation.equals(itemMetadata.getDeprecation())) { return false; } return true; } public MetadataItemCondition ofType(Class dataType) { - return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), this.sourceType, + this.sourceMethod, this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition ofType(String dataType) { - return new MetadataItemCondition(this.itemType, this.name, dataType, - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, dataType, this.sourceType, this.sourceMethod, + this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition fromSource(Class sourceType) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - sourceType, this.sourceMethod, this.description, this.defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, sourceType, this.sourceMethod, + this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition fromSourceMethod(String sourceMethod) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, sourceMethod, this.description, this.defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, sourceMethod, + this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition withDescription(String description) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, description, this.defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + description, this.defaultValue, this.deprecation); } public MetadataItemCondition withDefaultValue(Object defaultValue) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, this.description, defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + this.description, defaultValue, this.deprecation); } public MetadataItemCondition withDeprecation(String reason, String replacement) { return withDeprecation(reason, replacement, null); } - public MetadataItemCondition withDeprecation(String reason, String replacement, - String level) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, new ItemDeprecation(reason, replacement, level)); + public MetadataItemCondition withDeprecation(String reason, String replacement, String level) { + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + this.description, this.defaultValue, new ItemDeprecation(reason, replacement, level)); } public MetadataItemCondition withNoDeprecation() { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, null); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + this.description, this.defaultValue, null); } - private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, - String name) { + private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, String name) { for (ItemMetadata item : metadata.getItems()) { if (item.isOfItemType(this.itemType) && name.equals(item.getName())) { return item; @@ -247,8 +232,7 @@ public final class Metadata { this.providerConditions = Collections.emptyList(); } - public MetadataHintCondition(String name, - List valueConditions, + public MetadataHintCondition(String name, List valueConditions, List providerConditions) { this.name = name; this.valueConditions = valueConditions; @@ -274,12 +258,10 @@ public final class Metadata { if (itemHint == null) { return false; } - return matches(itemHint, this.valueConditions) - && matches(itemHint, this.providerConditions); + return matches(itemHint, this.valueConditions) && matches(itemHint, this.providerConditions); } - private boolean matches(ItemHint itemHint, - List> conditions) { + private boolean matches(ItemHint itemHint, List> conditions) { for (Condition condition : conditions) { if (!condition.matches(itemHint)) { return false; @@ -288,8 +270,7 @@ public final class Metadata { return true; } - private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, - String name) { + private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, String name) { for (ItemHint hint : metadata.getHints()) { if (name.equals(hint.getName())) { return hint; @@ -298,11 +279,9 @@ public final class Metadata { return null; } - public MetadataHintCondition withValue(int index, Object value, - String description) { + public MetadataHintCondition withValue(int index, Object value, String description) { return new MetadataHintCondition(this.name, - add(this.valueConditions, - new ItemHintValueCondition(index, value, description)), + add(this.valueConditions, new ItemHintValueCondition(index, value, description)), this.providerConditions); } @@ -310,17 +289,13 @@ public final class Metadata { return withProvider(this.providerConditions.size(), provider, null); } - public MetadataHintCondition withProvider(String provider, String key, - Object value) { - return withProvider(this.providerConditions.size(), provider, - Collections.singletonMap(key, value)); + public MetadataHintCondition withProvider(String provider, String key, Object value) { + return withProvider(this.providerConditions.size(), provider, Collections.singletonMap(key, value)); } - public MetadataHintCondition withProvider(int index, String provider, - Map parameters) { + public MetadataHintCondition withProvider(int index, String provider, Map parameters) { return new MetadataHintCondition(this.name, this.valueConditions, - add(this.providerConditions, - new ItemHintProviderCondition(index, provider, parameters))); + add(this.providerConditions, new ItemHintProviderCondition(index, provider, parameters))); } private List add(List items, T item) { @@ -367,8 +342,7 @@ public final class Metadata { if (this.value != null && !this.value.equals(valueHint.getValue())) { return false; } - if (this.description != null - && !this.description.equals(valueHint.getDescription())) { + if (this.description != null && !this.description.equals(valueHint.getDescription())) { return false; } return true; @@ -384,8 +358,7 @@ public final class Metadata { private final Map parameters; - ItemHintProviderCondition(int index, String name, - Map parameters) { + ItemHintProviderCondition(int index, String name, Map parameters) { this.index = index; this.name = name; this.parameters = parameters; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java index 3c84cd66d96..c33496fb509 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java @@ -39,10 +39,8 @@ public class RoundEnvironmentTester { */ public TypeElement getRootElement(Class type) { return (TypeElement) this.roundEnvironment.getRootElements().stream() - .filter((element) -> element.toString().equals(type.getName())) - .findFirst() - .orElseThrow(() -> new IllegalStateException("No element found for " - + type + .filter((element) -> element.toString().equals(type.getName())).findFirst() + .orElseThrow(() -> new IllegalStateException("No element found for " + type + " make sure it is included in the list of classes to compile")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestConfigurationMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestConfigurationMetadataAnnotationProcessor.java index f311617f99b..ab3f3be62d2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestConfigurationMetadataAnnotationProcessor.java @@ -38,8 +38,7 @@ import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller; */ @SupportedAnnotationTypes({ "*" }) @SupportedSourceVersion(SourceVersion.RELEASE_6) -public class TestConfigurationMetadataAnnotationProcessor - extends ConfigurationMetadataAnnotationProcessor { +public class TestConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor { public static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties"; @@ -95,11 +94,9 @@ public class TestConfigurationMetadataAnnotationProcessor protected ConfigurationMetadata writeMetaData() throws Exception { super.writeMetaData(); try { - File metadataFile = new File(this.outputLocation, - "META-INF/spring-configuration-metadata.json"); + File metadataFile = new File(this.outputLocation, "META-INF/spring-configuration-metadata.json"); if (metadataFile.isFile()) { - this.metadata = new JsonMarshaller() - .read(new FileInputStream(metadataFile)); + this.metadata = new JsonMarshaller().read(new FileInputStream(metadataFile)); } else { this.metadata = new ConfigurationMetadata(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestableAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestableAnnotationProcessor.java index b681aea2cd4..f937978277c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestableAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/TestableAnnotationProcessor.java @@ -57,8 +57,7 @@ public class TestableAnnotationProcessor extends AbstractProcessor { } @Override - public boolean process(Set annotations, - RoundEnvironment roundEnv) { + public boolean process(Set annotations, RoundEnvironment roundEnv) { RoundEnvironmentTester tester = new RoundEnvironmentTester(roundEnv); if (!roundEnv.getRootElements().isEmpty()) { this.consumer.accept(tester, this.target); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/AbstractIntermediateGenericProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/AbstractIntermediateGenericProperties.java index bbb9a339d81..70ca477a333 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/AbstractIntermediateGenericProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/AbstractIntermediateGenericProperties.java @@ -22,7 +22,6 @@ package org.springframework.boot.configurationsample.generic; * @param mapping value type * @author Stephane Nicoll */ -public abstract class AbstractIntermediateGenericProperties - extends AbstractGenericProperties { +public abstract class AbstractIntermediateGenericProperties extends AbstractGenericProperties { } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/SimpleGenericProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/SimpleGenericProperties.java index 853f812ff13..e695379e749 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/SimpleGenericProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/SimpleGenericProperties.java @@ -26,7 +26,6 @@ import org.springframework.boot.configurationsample.ConfigurationProperties; * @author Stephane Nicoll */ @ConfigurationProperties("generic") -public class SimpleGenericProperties - extends AbstractIntermediateGenericProperties { +public class SimpleGenericProperties extends AbstractIntermediateGenericProperties { } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/UnresolvedGenericProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/UnresolvedGenericProperties.java index 85a228c4e81..240fe8680c9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/UnresolvedGenericProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/UnresolvedGenericProperties.java @@ -26,7 +26,6 @@ import org.springframework.boot.configurationsample.ConfigurationProperties; * @author Stephane Nicoll */ @ConfigurationProperties("generic") -public class UnresolvedGenericProperties - extends AbstractGenericProperties { +public class UnresolvedGenericProperties extends AbstractGenericProperties { } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableCollectionProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableCollectionProperties.java index 0c453d52dff..c148409be7c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableCollectionProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableCollectionProperties.java @@ -35,8 +35,7 @@ public class ImmutableCollectionProperties { private final List durations; - public ImmutableCollectionProperties(List names, - @DefaultValue({ "true", "false" }) List flags, + public ImmutableCollectionProperties(List names, @DefaultValue({ "true", "false" }) List flags, @DefaultValue({ "10s", "1m", "1h" }) List durations) { this.names = names; this.flags = flags; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableInnerClassProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableInnerClassProperties.java index d25b11b6d31..b62a0cdbaca 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableInnerClassProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableInnerClassProperties.java @@ -35,8 +35,7 @@ public class ImmutableInnerClassProperties { private final Fourth fourth; - public ImmutableInnerClassProperties(Foo first, Foo second, SimplePojo third, - Fourth fourth) { + public ImmutableInnerClassProperties(Foo first, Foo second, SimplePojo third, Fourth fourth) { this.first = first; this.second = second; this.third = third; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveProperties.java index 24a6961374f..5156bb903d5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveProperties.java @@ -40,8 +40,8 @@ public class ImmutablePrimitiveProperties { private final double ratio; - public ImmutablePrimitiveProperties(boolean flag, byte octet, char letter, - short number, int counter, long value, float percentage, double ratio) { + public ImmutablePrimitiveProperties(boolean flag, byte octet, char letter, short number, int counter, long value, + float percentage, double ratio) { this.flag = flag; this.octet = octet; this.letter = letter; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWithDefaultsProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWithDefaultsProperties.java index c496f0942d4..b6203796cba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWithDefaultsProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWithDefaultsProperties.java @@ -42,9 +42,8 @@ public class ImmutablePrimitiveWithDefaultsProperties { private final double ratio; - public ImmutablePrimitiveWithDefaultsProperties(@DefaultValue("true") boolean flag, - @DefaultValue("120") byte octet, @DefaultValue("a") char letter, - @DefaultValue("1000") short number, @DefaultValue("42") int counter, + public ImmutablePrimitiveWithDefaultsProperties(@DefaultValue("true") boolean flag, @DefaultValue("120") byte octet, + @DefaultValue("a") char letter, @DefaultValue("1000") short number, @DefaultValue("42") int counter, @DefaultValue("2000") long value, @DefaultValue("0.5") float percentage, @DefaultValue("42.42") double ratio) { this.flag = flag; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWrapperWithDefaultsProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWrapperWithDefaultsProperties.java index c2148f93e3b..010a5b66527 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWrapperWithDefaultsProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWrapperWithDefaultsProperties.java @@ -42,9 +42,8 @@ public class ImmutablePrimitiveWrapperWithDefaultsProperties { private final Double ratio; - public ImmutablePrimitiveWrapperWithDefaultsProperties( - @DefaultValue("true") Boolean flag, @DefaultValue("120") Byte octet, - @DefaultValue("a") Character letter, @DefaultValue("1000") Short number, + public ImmutablePrimitiveWrapperWithDefaultsProperties(@DefaultValue("true") Boolean flag, + @DefaultValue("120") Byte octet, @DefaultValue("a") Character letter, @DefaultValue("1000") Short number, @DefaultValue("42") Integer counter, @DefaultValue("2000") Long value, @DefaultValue("0.5") Float percentage, @DefaultValue("42.42") Double ratio) { this.flag = flag; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableSimpleProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableSimpleProperties.java index b55b0c3ade0..3e64f6fa32c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableSimpleProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutableSimpleProperties.java @@ -47,8 +47,8 @@ public class ImmutableSimpleProperties { @SuppressWarnings("unused") private final Long counter; - public ImmutableSimpleProperties(@DefaultValue("boot") String theName, boolean flag, - Comparator comparator, Long counter) { + public ImmutableSimpleProperties(@DefaultValue("boot") String theName, boolean flag, Comparator comparator, + Long counter) { this.theName = theName; this.flag = flag; this.comparator = comparator; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java index 273f8143814..f8df3f7c4ae 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java @@ -30,8 +30,7 @@ public class DeprecatedSingleProperty { private String newName; @Deprecated - @DeprecatedConfigurationProperty(reason = "renamed", - replacement = "singledeprecated.new-name") + @DeprecatedConfigurationProperty(reason = "renamed", replacement = "singledeprecated.new-name") public String getName() { return getNewName(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java index 765ded2b0c4..364ba561195 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java @@ -21,8 +21,7 @@ package org.springframework.boot.configurationsample.simple; * * @author Stephane Nicoll */ -public abstract class HierarchicalPropertiesParent - extends HierarchicalPropertiesGrandparent { +public abstract class HierarchicalPropertiesParent extends HierarchicalPropertiesGrandparent { private String second = "two"; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InvalidDefaultValueFloatingPointProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InvalidDefaultValueFloatingPointProperties.java index 33862006e62..b638e421690 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InvalidDefaultValueFloatingPointProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InvalidDefaultValueFloatingPointProperties.java @@ -30,8 +30,7 @@ public class InvalidDefaultValueFloatingPointProperties { private final Double ratio; - public InvalidDefaultValueFloatingPointProperties( - @DefaultValue("55.55.33") Double ratio) { + public InvalidDefaultValueFloatingPointProperties(@DefaultValue("55.55.33") Double ratio) { this.ratio = ratio; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/build.gradle b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/build.gradle index 2f72a0981e0..8497b16ea56 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/build.gradle +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/build.gradle @@ -4,7 +4,7 @@ buildscript { mavenCentral() } dependencies { - classpath("io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.9") + classpath("io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.11") } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java index 59413a40677..2fac0c020ef 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,13 +89,11 @@ public class SpringBootExtension { * @param configurer the task configurer */ public void buildInfo(Action configurer) { - BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo", - BuildInfo.class); + BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo", BuildInfo.class); bootBuildInfo.setGroup(BasePlugin.BUILD_GROUP); bootBuildInfo.setDescription("Generates a META-INF/build-info.properties file."); this.project.getPlugins().withType(JavaPlugin.class, (plugin) -> { - this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME) - .dependsOn(bootBuildInfo); + this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME).dependsOn(bootBuildInfo); this.project.afterEvaluate((evaluated) -> { BuildInfoProperties properties = bootBuildInfo.getProperties(); if (properties.getArtifact() == null) { @@ -103,8 +101,7 @@ public class SpringBootExtension { } }); bootBuildInfo.getConventionMapping().map("destinationDir", - () -> new File(determineMainSourceSetResourcesOutputDir(), - "META-INF")); + () -> new File(determineMainSourceSetResourcesOutputDir(), "META-INF")); }); if (configurer != null) { configurer.execute(bootBuildInfo); @@ -112,9 +109,8 @@ public class SpringBootExtension { } private File determineMainSourceSetResourcesOutputDir() { - return this.project.getConvention().getPlugin(JavaPluginConvention.class) - .getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput() - .getResourcesDir(); + return this.project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput().getResourcesDir(); } private String determineArtifactBaseName() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java index 668acf0d60b..c7b8ba00844 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,37 +47,31 @@ final class ApplicationPluginAction implements PluginApplicationAction { public void execute(Project project) { ApplicationPluginConvention applicationConvention = project.getConvention() .getPlugin(ApplicationPluginConvention.class); - DistributionContainer distributions = project.getExtensions() - .getByType(DistributionContainer.class); + DistributionContainer distributions = project.getExtensions().getByType(DistributionContainer.class); Distribution distribution = distributions.create("boot"); if (distribution instanceof IConventionAware) { ((IConventionAware) distribution).getConventionMapping().map("baseName", () -> applicationConvention.getApplicationName() + "-boot"); } - CreateBootStartScripts bootStartScripts = project.getTasks() - .create("bootStartScripts", CreateBootStartScripts.class); - bootStartScripts.setDescription("Generates OS-specific start scripts to run the" - + " project as a Spring Boot application."); + CreateBootStartScripts bootStartScripts = project.getTasks().create("bootStartScripts", + CreateBootStartScripts.class); + bootStartScripts.setDescription( + "Generates OS-specific start scripts to run the" + " project as a Spring Boot application."); ((TemplateBasedScriptGenerator) bootStartScripts.getUnixStartScriptGenerator()) - .setTemplate(project.getResources().getText() - .fromString(loadResource("/unixStartScript.txt"))); + .setTemplate(project.getResources().getText().fromString(loadResource("/unixStartScript.txt"))); ((TemplateBasedScriptGenerator) bootStartScripts.getWindowsStartScriptGenerator()) - .setTemplate(project.getResources().getText() - .fromString(loadResource("/windowsStartScript.txt"))); + .setTemplate(project.getResources().getText().fromString(loadResource("/windowsStartScript.txt"))); project.getConfigurations().all((configuration) -> { if ("bootArchives".equals(configuration.getName())) { CopySpec libCopySpec = project.copySpec().into("lib") - .from((Callable) () -> configuration - .getArtifacts().getFiles()); + .from((Callable) () -> configuration.getArtifacts().getFiles()); libCopySpec.setFileMode(0644); distribution.getContents().with(libCopySpec); bootStartScripts.setClasspath(configuration.getArtifacts().getFiles()); } }); - bootStartScripts.getConventionMapping().map("outputDir", - () -> new File(project.getBuildDir(), "bootScripts")); - bootStartScripts.getConventionMapping().map("applicationName", - applicationConvention::getApplicationName); + bootStartScripts.getConventionMapping().map("outputDir", () -> new File(project.getBuildDir(), "bootScripts")); + bootStartScripts.getConventionMapping().map("applicationName", applicationConvention::getApplicationName); bootStartScripts.getConventionMapping().map("defaultJvmOpts", applicationConvention::getApplicationDefaultJvmArgs); CopySpec binCopySpec = project.copySpec().into("bin").from(bootStartScripts); @@ -91,8 +85,7 @@ final class ApplicationPluginAction implements PluginApplicationAction { } private String loadResource(String name) { - try (InputStreamReader reader = new InputStreamReader( - getClass().getResourceAsStream(name))) { + try (InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(name))) { char[] buffer = new char[4096]; int read = 0; StringWriter writer = new StringWriter(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java index 94cc4fb59c3..c8b6759f126 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ final class DependencyManagementPluginAction implements PluginApplicationAction @Override public void execute(Project project) { project.getExtensions().findByType(DependencyManagementExtension.class) - .imports((importsHandler) -> importsHandler - .mavenBom(SpringBootPlugin.BOM_COORDINATES)); + .imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES)); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java index 6d12a4eb58d..91800b1b16e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,25 +77,20 @@ final class JavaPluginAction implements PluginApplicationAction { } private void configureBuildTask(Project project) { - project.getTasks().getByName(BasePlugin.ASSEMBLE_TASK_NAME) - .dependsOn(this.singlePublishedArtifact); + project.getTasks().getByName(BasePlugin.ASSEMBLE_TASK_NAME).dependsOn(this.singlePublishedArtifact); } private BootJar configureBootJarTask(Project project) { - BootJar bootJar = project.getTasks().create(SpringBootPlugin.BOOT_JAR_TASK_NAME, - BootJar.class); - bootJar.setDescription("Assembles an executable jar archive containing the main" - + " classes and their dependencies."); + BootJar bootJar = project.getTasks().create(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class); + bootJar.setDescription( + "Assembles an executable jar archive containing the main" + " classes and their dependencies."); bootJar.setGroup(BasePlugin.BUILD_GROUP); bootJar.classpath((Callable) () -> { - JavaPluginConvention convention = project.getConvention() - .getPlugin(JavaPluginConvention.class); - SourceSet mainSourceSet = convention.getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + JavaPluginConvention convention = project.getConvention().getPlugin(JavaPluginConvention.class); + SourceSet mainSourceSet = convention.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); return mainSourceSet.getRuntimeClasspath(); }); - bootJar.conventionMapping("mainClassName", - new MainClassConvention(project, bootJar::getClasspath)); + bootJar.conventionMapping("mainClassName", new MainClassConvention(project, bootJar::getClasspath)); return bootJar; } @@ -105,30 +100,26 @@ final class JavaPluginAction implements PluginApplicationAction { } private void configureBootRunTask(Project project) { - JavaPluginConvention javaConvention = project.getConvention() - .getPlugin(JavaPluginConvention.class); + JavaPluginConvention javaConvention = project.getConvention().getPlugin(JavaPluginConvention.class); BootRun run = project.getTasks().create("bootRun", BootRun.class); run.setDescription("Runs this project as a Spring Boot application."); run.setGroup(ApplicationPlugin.APPLICATION_GROUP); - run.classpath(javaConvention.getSourceSets() - .findByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath()); + run.classpath(javaConvention.getSourceSets().findByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath()); run.getConventionMapping().map("jvmArgs", () -> { if (project.hasProperty("applicationDefaultJvmArgs")) { return project.property("applicationDefaultJvmArgs"); } return Collections.emptyList(); }); - run.conventionMapping("main", - new MainClassConvention(project, run::getClasspath)); + run.conventionMapping("main", new MainClassConvention(project, run::getClasspath)); } private void configureUtf8Encoding(Project project) { - project.afterEvaluate((evaluated) -> evaluated.getTasks() - .withType(JavaCompile.class, (compile) -> { - if (compile.getOptions().getEncoding() == null) { - compile.getOptions().setEncoding("UTF-8"); - } - })); + project.afterEvaluate((evaluated) -> evaluated.getTasks().withType(JavaCompile.class, (compile) -> { + if (compile.getOptions().getEncoding() == null) { + compile.getOptions().setEncoding("UTF-8"); + } + })); } private void configureParametersCompilerArg(Project project) { @@ -141,8 +132,8 @@ final class JavaPluginAction implements PluginApplicationAction { } private void configureAdditionalMetadataLocations(Project project) { - project.afterEvaluate((evaluated) -> evaluated.getTasks() - .withType(JavaCompile.class, this::configureAdditionalMetadataLocations)); + project.afterEvaluate((evaluated) -> evaluated.getTasks().withType(JavaCompile.class, + this::configureAdditionalMetadataLocations)); } private void configureAdditionalMetadataLocations(JavaCompile compile) { @@ -163,35 +154,27 @@ final class JavaPluginAction implements PluginApplicationAction { } JavaCompile compile = (JavaCompile) task; if (hasConfigurationProcessorOnClasspath(compile)) { - findMatchingSourceSet(compile).ifPresent( - (sourceSet) -> configureAdditionalMetadataLocations(compile, - sourceSet)); + findMatchingSourceSet(compile) + .ifPresent((sourceSet) -> configureAdditionalMetadataLocations(compile, sourceSet)); } } private boolean hasConfigurationProcessorOnClasspath(JavaCompile compile) { Set files = (compile.getOptions().getAnnotationProcessorPath() != null) - ? compile.getOptions().getAnnotationProcessorPath().getFiles() - : compile.getClasspath().getFiles(); - return files.stream().map(File::getName).anyMatch( - (name) -> name.startsWith("spring-boot-configuration-processor")); + ? compile.getOptions().getAnnotationProcessorPath().getFiles() : compile.getClasspath().getFiles(); + return files.stream().map(File::getName) + .anyMatch((name) -> name.startsWith("spring-boot-configuration-processor")); } private Optional findMatchingSourceSet(JavaCompile compile) { - return compile - .getProject().getConvention().getPlugin(JavaPluginConvention.class) - .getSourceSets().stream().filter((sourceSet) -> sourceSet - .getCompileJavaTaskName().equals(compile.getName())) - .findFirst(); + return compile.getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().stream() + .filter((sourceSet) -> sourceSet.getCompileJavaTaskName().equals(compile.getName())).findFirst(); } - private void configureAdditionalMetadataLocations(JavaCompile compile, - SourceSet sourceSet) { - String locations = StringUtils.collectionToCommaDelimitedString( - sourceSet.getResources().getSrcDirs()); - compile.getOptions().getCompilerArgs().add( - "-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" - + locations); + private void configureAdditionalMetadataLocations(JavaCompile compile, SourceSet sourceSet) { + String locations = StringUtils.collectionToCommaDelimitedString(sourceSet.getResources().getSrcDirs()); + compile.getOptions().getCompilerArgs() + .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + locations); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java index 117126fd043..ccf0d0cb4d6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,10 +33,8 @@ class KotlinPluginAction implements PluginApplicationAction { @Override public void execute(Project project) { - String kotlinVersion = project.getPlugins().getPlugin(KotlinPluginWrapper.class) - .getKotlinPluginVersion(); - ExtraPropertiesExtension extraProperties = project.getExtensions() - .getExtraProperties(); + String kotlinVersion = project.getPlugins().getPlugin(KotlinPluginWrapper.class).getKotlinPluginVersion(); + ExtraPropertiesExtension extraProperties = project.getExtensions().getExtraProperties(); if (!extraProperties.has("kotlin.version")) { extraProperties.set("kotlin.version", kotlinVersion); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/MainClassConvention.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/MainClassConvention.java index 0e812b17b4c..b929b0f0fe0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/MainClassConvention.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/MainClassConvention.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,10 +49,8 @@ final class MainClassConvention implements Callable { @Override public Object call() throws Exception { - SpringBootExtension springBootExtension = this.project.getExtensions() - .findByType(SpringBootExtension.class); - if (springBootExtension != null - && springBootExtension.getMainClassName() != null) { + SpringBootExtension springBootExtension = this.project.getExtensions().findByType(SpringBootExtension.class); + if (springBootExtension != null && springBootExtension.getMainClassName() != null) { return springBootExtension.getMainClassName(); } if (this.project.hasProperty("mainClassName")) { @@ -65,16 +63,14 @@ final class MainClassConvention implements Callable { } private String resolveMainClass() { - return this.classpathSupplier.get().filter(File::isDirectory).getFiles().stream() - .map(this::findMainClass).filter(Objects::nonNull).findFirst() - .orElseThrow(() -> new InvalidUserDataException( + return this.classpathSupplier.get().filter(File::isDirectory).getFiles().stream().map(this::findMainClass) + .filter(Objects::nonNull).findFirst().orElseThrow(() -> new InvalidUserDataException( "Main class name has not been configured and it could not be resolved")); } private String findMainClass(File file) { try { - return MainClassFinder.findSingleMainClass(file, - SPRING_BOOT_APPLICATION_CLASS_NAME); + return MainClassFinder.findSingleMainClass(file, SPRING_BOOT_APPLICATION_CLASS_NAME); } catch (IOException ex) { return null; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java index b348acb51f1..4084e7a1fd1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java @@ -85,8 +85,8 @@ public class SpringBootPlugin implements Plugin { private void verifyGradleVersion() { if (GradleVersion.current().compareTo(GradleVersion.version("4.10")) < 0) { - throw new GradleException("Spring Boot plugin requires Gradle 4.10 or later." - + " The current version is " + GradleVersion.current()); + throw new GradleException("Spring Boot plugin requires Gradle 4.10 or later." + " The current version is " + + GradleVersion.current()); } } @@ -95,27 +95,20 @@ public class SpringBootPlugin implements Plugin { } private Configuration createBootArchivesConfiguration(Project project) { - Configuration bootArchives = project.getConfigurations() - .create(BOOT_ARCHIVES_CONFIGURATION_NAME); + Configuration bootArchives = project.getConfigurations().create(BOOT_ARCHIVES_CONFIGURATION_NAME); bootArchives.setDescription("Configuration for Spring Boot archive artifacts."); return bootArchives; } private void registerPluginActions(Project project, Configuration bootArchives) { - SinglePublishedArtifact singlePublishedArtifact = new SinglePublishedArtifact( - bootArchives.getArtifacts()); - List actions = Arrays.asList( - new JavaPluginAction(singlePublishedArtifact), - new WarPluginAction(singlePublishedArtifact), - new MavenPluginAction(bootArchives.getUploadTaskName()), - new DependencyManagementPluginAction(), new ApplicationPluginAction(), - new KotlinPluginAction()); + SinglePublishedArtifact singlePublishedArtifact = new SinglePublishedArtifact(bootArchives.getArtifacts()); + List actions = Arrays.asList(new JavaPluginAction(singlePublishedArtifact), + new WarPluginAction(singlePublishedArtifact), new MavenPluginAction(bootArchives.getUploadTaskName()), + new DependencyManagementPluginAction(), new ApplicationPluginAction(), new KotlinPluginAction()); for (PluginApplicationAction action : actions) { - Class> pluginClass = action - .getPluginClass(); + Class> pluginClass = action.getPluginClass(); if (pluginClass != null) { - project.getPlugins().withType(pluginClass, - (plugin) -> action.execute(project)); + project.getPlugins().withType(pluginClass, (plugin) -> action.execute(project)); } } } @@ -126,29 +119,25 @@ public class SpringBootPlugin implements Plugin { ResolvableDependencies incoming = configuration.getIncoming(); incoming.afterResolve((resolvableDependencies) -> { if (incoming.equals(resolvableDependencies)) { - unresolvedDependenciesAnalyzer.analyze(configuration - .getResolvedConfiguration().getLenientConfiguration() - .getUnresolvedModuleDependencies()); + unresolvedDependenciesAnalyzer.analyze(configuration.getResolvedConfiguration() + .getLenientConfiguration().getUnresolvedModuleDependencies()); } }); }); - project.getGradle().buildFinished( - (buildResult) -> unresolvedDependenciesAnalyzer.buildFinished(project)); + project.getGradle().buildFinished((buildResult) -> unresolvedDependenciesAnalyzer.buildFinished(project)); } private static String determineSpringBootVersion() { - String implementationVersion = DependencyManagementPluginAction.class.getPackage() - .getImplementationVersion(); + String implementationVersion = DependencyManagementPluginAction.class.getPackage().getImplementationVersion(); if (implementationVersion != null) { return implementationVersion; } - URL codeSourceLocation = DependencyManagementPluginAction.class - .getProtectionDomain().getCodeSource().getLocation(); + URL codeSourceLocation = DependencyManagementPluginAction.class.getProtectionDomain().getCodeSource() + .getLocation(); try { URLConnection connection = codeSourceLocation.openConnection(); if (connection instanceof JarURLConnection) { - return getImplementationVersion( - ((JarURLConnection) connection).getJarFile()); + return getImplementationVersion(((JarURLConnection) connection).getJarFile()); } try (JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) { return getImplementationVersion(jarFile); @@ -160,8 +149,7 @@ public class SpringBootPlugin implements Plugin { } private static String getImplementationVersion(JarFile jarFile) throws IOException { - return jarFile.getManifest().getMainAttributes() - .getValue(Attributes.Name.IMPLEMENTATION_VERSION); + return jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/UnresolvedDependenciesAnalyzer.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/UnresolvedDependenciesAnalyzer.java index 28847665f58..712e2a24140 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/UnresolvedDependenciesAnalyzer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/UnresolvedDependenciesAnalyzer.java @@ -42,8 +42,8 @@ class UnresolvedDependenciesAnalyzer { void analyze(Set unresolvedDependencies) { this.dependenciesWithNoVersion = unresolvedDependencies.stream() - .map((unresolvedDependency) -> unresolvedDependency.getSelector()) - .filter(this::hasNoVersion).collect(Collectors.toSet()); + .map((unresolvedDependency) -> unresolvedDependency.getSelector()).filter(this::hasNoVersion) + .collect(Collectors.toSet()); } void buildFinished(Project project) { @@ -52,10 +52,9 @@ class UnresolvedDependenciesAnalyzer { StringBuilder message = new StringBuilder(); message.append("\nDuring the build, one or more dependencies that were " + "declared without a version failed to resolve:\n"); - this.dependenciesWithNoVersion.forEach((dependency) -> message.append(" ") - .append(dependency).append("\n")); - message.append("\nDid you forget to apply the " - + "io.spring.dependency-management plugin to the "); + this.dependenciesWithNoVersion + .forEach((dependency) -> message.append(" ").append(dependency).append("\n")); + message.append("\nDid you forget to apply the " + "io.spring.dependency-management plugin to the "); message.append(project.getName()).append(" project?\n"); logger.warn(message.toString()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java index f3ad74da615..b406948c8f5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,21 +47,18 @@ class WarPluginAction implements PluginApplicationAction { @Override public void execute(Project project) { project.getTasks().getByName(WarPlugin.WAR_TASK_NAME).setEnabled(false); - BootWar bootWar = project.getTasks().create(SpringBootPlugin.BOOT_WAR_TASK_NAME, - BootWar.class); + BootWar bootWar = project.getTasks().create(SpringBootPlugin.BOOT_WAR_TASK_NAME, BootWar.class); bootWar.setGroup(BasePlugin.BUILD_GROUP); bootWar.setDescription("Assembles an executable war archive containing webapp" + " content, and the main classes and their dependencies."); bootWar.providedClasspath(providedRuntimeConfiguration(project)); ArchivePublishArtifact artifact = new ArchivePublishArtifact(bootWar); this.singlePublishedArtifact.addCandidate(artifact); - bootWar.conventionMapping("mainClassName", - new MainClassConvention(project, bootWar::getClasspath)); + bootWar.conventionMapping("mainClassName", new MainClassConvention(project, bootWar::getClasspath)); } private Configuration providedRuntimeConfiguration(Project project) { - return project.getConfigurations() - .getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME); + return project.getConfigurations().getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java index d21e0946d75..b81f7463c89 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,14 +53,13 @@ public class BuildInfo extends ConventionTask { @TaskAction public void generateBuildProperties() { try { - new BuildPropertiesWriter(new File(getDestinationDir(), - "build-info.properties")).writeBuildProperties(new ProjectDetails( - this.properties.getGroup(), - (this.properties.getArtifact() != null) - ? this.properties.getArtifact() : "unspecified", - this.properties.getVersion(), this.properties.getName(), - this.properties.getTime(), - coerceToStringValues(this.properties.getAdditional()))); + new BuildPropertiesWriter(new File(getDestinationDir(), "build-info.properties")) + .writeBuildProperties( + new ProjectDetails(this.properties.getGroup(), + (this.properties.getArtifact() != null) ? this.properties.getArtifact() + : "unspecified", + this.properties.getVersion(), this.properties.getName(), this.properties.getTime(), + coerceToStringValues(this.properties.getAdditional()))); } catch (IOException ex) { throw new TaskExecutionException(this, ex); @@ -74,8 +73,7 @@ public class BuildInfo extends ConventionTask { */ @OutputDirectory public File getDestinationDir() { - return (this.destinationDir != null) ? this.destinationDir - : getProject().getBuildDir(); + return (this.destinationDir != null) ? this.destinationDir : getProject().getBuildDir(); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java index f14c839edea..5d2041a547e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -172,8 +172,7 @@ public class BuildInfoProperties implements Serializable { } BuildInfoProperties other = (BuildInfoProperties) obj; boolean result = true; - result = result - && nullSafeEquals(this.additionalProperties, other.additionalProperties); + result = result && nullSafeEquals(this.additionalProperties, other.additionalProperties); result = result && nullSafeEquals(this.artifact, other.artifact); result = result && nullSafeEquals(this.group, other.group); result = result && nullSafeEquals(this.name, other.name); @@ -196,10 +195,8 @@ public class BuildInfoProperties implements Serializable { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((this.additionalProperties == null) ? 0 - : this.additionalProperties.hashCode()); - result = prime * result - + ((this.artifact == null) ? 0 : this.artifact.hashCode()); + result = prime * result + ((this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode()); + result = prime * result + ((this.artifact == null) ? 0 : this.artifact.hashCode()); result = prime * result + ((this.group == null) ? 0 : this.group.hashCode()); result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + ((this.version == null) ? 0 : this.version.hashCode()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java index 4e6316c104d..48b42b10a63 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java @@ -71,21 +71,18 @@ class BootArchiveSupport { private boolean excludeDevtools = true; - BootArchiveSupport(String loaderMainClass, - Function compressionResolver) { + BootArchiveSupport(String loaderMainClass, Function compressionResolver) { this.loaderMainClass = loaderMainClass; this.compressionResolver = compressionResolver; this.requiresUnpack.include(Specs.satisfyNone()); configureExclusions(); } - void configureManifest(Jar jar, String mainClassName, String springBootClasses, - String springBootLib) { + void configureManifest(Jar jar, String mainClassName, String springBootClasses, String springBootLib) { Attributes attributes = jar.getManifest().getAttributes(); attributes.putIfAbsent("Main-Class", this.loaderMainClass); attributes.putIfAbsent("Start-Class", mainClassName); - attributes.computeIfAbsent("Spring-Boot-Version", - (key) -> determineSpringBootVersion()); + attributes.computeIfAbsent("Spring-Boot-Version", (key) -> determineSpringBootVersion()); attributes.putIfAbsent("Spring-Boot-Classes", springBootClasses); attributes.putIfAbsent("Spring-Boot-Lib", springBootLib); } @@ -96,9 +93,8 @@ class BootArchiveSupport { } CopyAction createCopyAction(Jar jar) { - CopyAction copyAction = new BootZipCopyAction(jar.getArchivePath(), - jar.isPreserveFileTimestamps(), isUsingDefaultLoader(jar), - this.requiresUnpack.getAsSpec(), this.exclusions.getAsExcludeSpec(), + CopyAction copyAction = new BootZipCopyAction(jar.getArchivePath(), jar.isPreserveFileTimestamps(), + isUsingDefaultLoader(jar), this.requiresUnpack.getAsSpec(), this.exclusions.getAsExcludeSpec(), this.launchScript, this.compressionResolver, jar.getMetadataCharset()); if (!jar.isReproducibleFileOrder()) { return copyAction; @@ -107,8 +103,7 @@ class BootArchiveSupport { } private boolean isUsingDefaultLoader(Jar jar) { - return DEFAULT_LAUNCHER_CLASSES - .contains(jar.getManifest().getAttributes().get("Main-Class")); + return DEFAULT_LAUNCHER_CLASSES.contains(jar.getManifest().getAttributes().get("Main-Class")); } LaunchScriptConfiguration getLaunchScript() { @@ -176,8 +171,7 @@ class BootArchiveSupport { public WorkResult execute(CopyActionProcessingStream stream) { return this.delegate.execute((action) -> { Map detailsByPath = new TreeMap<>(); - stream.process((details) -> detailsByPath.put(details.getRelativePath(), - details)); + stream.process((details) -> detailsByPath.put(details.getRelativePath(), details)); detailsByPath.values().forEach(action::processFile); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootJar.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootJar.java index a6145d8e23c..e1507399a00 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootJar.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootJar.java @@ -38,8 +38,8 @@ import org.gradle.api.tasks.bundling.Jar; */ public class BootJar extends Jar implements BootArchive { - private final BootArchiveSupport support = new BootArchiveSupport( - "org.springframework.boot.loader.JarLauncher", this::resolveZipCompression); + private final BootArchiveSupport support = new BootArchiveSupport("org.springframework.boot.loader.JarLauncher", + this::resolveZipCompression); private final CopySpec bootInf; @@ -59,23 +59,20 @@ public class BootJar extends Jar implements BootArchive { (details) -> details.setRelativePath(details.getRelativeSourcePath())); getRootSpec().eachFile((details) -> { String pathString = details.getRelativePath().getPathString(); - if (pathString.startsWith("BOOT-INF/lib/") - && !this.support.isZip(details.getFile())) { + if (pathString.startsWith("BOOT-INF/lib/") && !this.support.isZip(details.getFile())) { details.exclude(); } }); } private Action classpathFiles(Spec filter) { - return (copySpec) -> copySpec - .from((Callable>) () -> (this.classpath != null) - ? this.classpath.filter(filter) : Collections.emptyList()); + return (copySpec) -> copySpec.from((Callable>) () -> (this.classpath != null) + ? this.classpath.filter(filter) : Collections.emptyList()); } @Override public void copy() { - this.support.configureManifest(this, getMainClassName(), "BOOT-INF/classes/", - "BOOT-INF/lib/"); + this.support.configureManifest(this, getMainClassName(), "BOOT-INF/classes/", "BOOT-INF/lib/"); super.copy(); } @@ -87,8 +84,7 @@ public class BootJar extends Jar implements BootArchive { @Override public String getMainClassName() { if (this.mainClassName == null) { - String manifestStartClass = (String) getManifest().getAttributes() - .get("Start-Class"); + String manifestStartClass = (String) getManifest().getAttributes().get("Start-Class"); if (manifestStartClass != null) { setMainClassName(manifestStartClass); } @@ -134,8 +130,7 @@ public class BootJar extends Jar implements BootArchive { @Override public void classpath(Object... classpath) { FileCollection existingClasspath = this.classpath; - this.classpath = getProject().files( - (existingClasspath != null) ? existingClasspath : Collections.emptyList(), + this.classpath = getProject().files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java index 7a87ab77c63..de30351b27a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java @@ -39,8 +39,8 @@ import org.gradle.api.tasks.bundling.War; */ public class BootWar extends War implements BootArchive { - private final BootArchiveSupport support = new BootArchiveSupport( - "org.springframework.boot.loader.WarLauncher", this::resolveZipCompression); + private final BootArchiveSupport support = new BootArchiveSupport("org.springframework.boot.loader.WarLauncher", + this::resolveZipCompression); private String mainClassName; @@ -51,15 +51,13 @@ public class BootWar extends War implements BootArchive { */ public BootWar() { getWebInf().into("lib-provided", - (copySpec) -> copySpec.from( - (Callable>) () -> (this.providedClasspath != null) - ? this.providedClasspath : Collections.emptyList())); + (copySpec) -> copySpec.from((Callable>) () -> (this.providedClasspath != null) + ? this.providedClasspath : Collections.emptyList())); getRootSpec().filesMatching("module-info.class", (details) -> details.setRelativePath(details.getRelativeSourcePath())); getRootSpec().eachFile((details) -> { String pathString = details.getRelativePath().getPathString(); - if ((pathString.startsWith("WEB-INF/lib/") - || pathString.startsWith("WEB-INF/lib-provided/")) + if ((pathString.startsWith("WEB-INF/lib/") || pathString.startsWith("WEB-INF/lib-provided/")) && !this.support.isZip(details.getFile())) { details.exclude(); } @@ -68,8 +66,7 @@ public class BootWar extends War implements BootArchive { @Override public void copy() { - this.support.configureManifest(this, getMainClassName(), "WEB-INF/classes/", - "WEB-INF/lib/"); + this.support.configureManifest(this, getMainClassName(), "WEB-INF/classes/", "WEB-INF/lib/"); super.copy(); } @@ -81,8 +78,7 @@ public class BootWar extends War implements BootArchive { @Override public String getMainClassName() { if (this.mainClassName == null) { - String manifestStartClass = (String) getManifest().getAttributes() - .get("Start-Class"); + String manifestStartClass = (String) getManifest().getAttributes().get("Start-Class"); if (manifestStartClass != null) { setMainClassName(manifestStartClass); } @@ -139,9 +135,8 @@ public class BootWar extends War implements BootArchive { */ public void providedClasspath(Object... classpath) { FileCollection existingClasspath = this.providedClasspath; - this.providedClasspath = getProject().files( - (existingClasspath != null) ? existingClasspath : Collections.emptyList(), - classpath); + this.providedClasspath = getProject() + .files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath); } /** @@ -186,8 +181,7 @@ public class BootWar extends War implements BootArchive { */ protected ZipCompression resolveZipCompression(FileCopyDetails details) { String relativePath = details.getRelativePath().getPathString(); - if (relativePath.startsWith("WEB-INF/lib/") - || relativePath.startsWith("WEB-INF/lib-provided/")) { + if (relativePath.startsWith("WEB-INF/lib/") || relativePath.startsWith("WEB-INF/lib-provided/")) { return ZipCompression.STORED; } return ZipCompression.DEFLATED; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java index f9b63730fd8..30e7d0f1f86 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java @@ -53,8 +53,8 @@ import org.springframework.boot.loader.tools.FileUtils; */ class BootZipCopyAction implements CopyAction { - static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, - Calendar.FEBRUARY, 1, 0, 0, 0).getTimeInMillis(); + static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0) + .getTimeInMillis(); private final File output; @@ -72,10 +72,9 @@ class BootZipCopyAction implements CopyAction { private final String encoding; - BootZipCopyAction(File output, boolean preserveFileTimestamps, - boolean includeDefaultLoader, Spec requiresUnpack, - Spec exclusions, LaunchScriptConfiguration launchScript, - Function compressionResolver, + BootZipCopyAction(File output, boolean preserveFileTimestamps, boolean includeDefaultLoader, + Spec requiresUnpack, Spec exclusions, + LaunchScriptConfiguration launchScript, Function compressionResolver, String encoding) { this.output = output; this.preserveFileTimestamps = preserveFileTimestamps; @@ -104,8 +103,7 @@ class BootZipCopyAction implements CopyAction { throw new GradleException("Failed to create " + this.output, ex); } try { - stream.process(new ZipStreamAction(zipStream, this.output, - this.preserveFileTimestamps, this.requiresUnpack, + stream.process(new ZipStreamAction(zipStream, this.output, this.preserveFileTimestamps, this.requiresUnpack, createExclusionSpec(loaderEntries), this.compressionResolver)); } finally { @@ -119,13 +117,11 @@ class BootZipCopyAction implements CopyAction { return () -> true; } - private Spec createExclusionSpec( - Spec loaderEntries) { + private Spec createExclusionSpec(Spec loaderEntries) { return Specs.union(loaderEntries, this.exclusions); } - private Spec writeLoaderClassesIfNecessary( - ZipArchiveOutputStream out) { + private Spec writeLoaderClassesIfNecessary(ZipArchiveOutputStream out) { if (!this.includeDefaultLoader) { return Specs.satisfyNone(); } @@ -133,8 +129,8 @@ class BootZipCopyAction implements CopyAction { } private Spec writeLoaderClasses(ZipArchiveOutputStream out) { - try (ZipInputStream in = new ZipInputStream(getClass() - .getResourceAsStream("/META-INF/loader/spring-boot-loader.jar"))) { + try (ZipInputStream in = new ZipInputStream( + getClass().getResourceAsStream("/META-INF/loader/spring-boot-loader.jar"))) { Set entries = new HashSet<>(); java.util.zip.ZipEntry entry; while ((entry = in.getNextEntry()) != null) { @@ -159,15 +155,13 @@ class BootZipCopyAction implements CopyAction { } } - private void writeDirectory(ZipArchiveEntry entry, ZipArchiveOutputStream out) - throws IOException { + private void writeDirectory(ZipArchiveEntry entry, ZipArchiveOutputStream out) throws IOException { prepareEntry(entry, UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM); out.putArchiveEntry(entry); out.closeArchiveEntry(); } - private void writeClass(ZipArchiveEntry entry, ZipInputStream in, - ZipArchiveOutputStream out) throws IOException { + private void writeClass(ZipArchiveEntry entry, ZipInputStream in, ZipArchiveOutputStream out) throws IOException { prepareEntry(entry, UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM); out.putArchiveEntry(entry); byte[] buffer = new byte[4096]; @@ -188,19 +182,18 @@ class BootZipCopyAction implements CopyAction { private void writeLaunchScriptIfNecessary(FileOutputStream fileStream) { try { if (this.launchScript != null) { - fileStream.write(new DefaultLaunchScript(this.launchScript.getScript(), - this.launchScript.getProperties()).toByteArray()); + fileStream + .write(new DefaultLaunchScript(this.launchScript.getScript(), this.launchScript.getProperties()) + .toByteArray()); this.output.setExecutable(true); } } catch (IOException ex) { - throw new GradleException("Failed to write launch script to " + this.output, - ex); + throw new GradleException("Failed to write launch script to " + this.output, ex); } } - private static final class ZipStreamAction - implements CopyActionProcessingStreamAction { + private static final class ZipStreamAction implements CopyActionProcessingStreamAction { private final ZipArchiveOutputStream zipStream; @@ -214,9 +207,8 @@ class BootZipCopyAction implements CopyAction { private final Function compressionType; - private ZipStreamAction(ZipArchiveOutputStream zipStream, File output, - boolean preserveFileTimestamps, Spec requiresUnpack, - Spec exclusions, + private ZipStreamAction(ZipArchiveOutputStream zipStream, File output, boolean preserveFileTimestamps, + Spec requiresUnpack, Spec exclusions, Function compressionType) { this.zipStream = zipStream; this.output = output; @@ -240,14 +232,12 @@ class BootZipCopyAction implements CopyAction { } } catch (IOException ex) { - throw new GradleException( - "Failed to add " + details + " to " + this.output, ex); + throw new GradleException("Failed to add " + details + " to " + this.output, ex); } } private void createDirectory(FileCopyDetailsInternal details) throws IOException { - ZipArchiveEntry archiveEntry = new ZipArchiveEntry( - details.getRelativePath().getPathString() + '/'); + ZipArchiveEntry archiveEntry = new ZipArchiveEntry(details.getRelativePath().getPathString() + '/'); archiveEntry.setUnixMode(UnixStat.DIR_FLAG | details.getMode()); archiveEntry.setTime(getTime(details)); this.zipStream.putArchiveEntry(archiveEntry); @@ -268,8 +258,8 @@ class BootZipCopyAction implements CopyAction { this.zipStream.closeArchiveEntry(); } - private void prepareStoredEntry(FileCopyDetailsInternal details, - ZipArchiveEntry archiveEntry) throws IOException { + private void prepareStoredEntry(FileCopyDetailsInternal details, ZipArchiveEntry archiveEntry) + throws IOException { archiveEntry.setMethod(java.util.zip.ZipEntry.STORED); archiveEntry.setSize(details.getSize()); archiveEntry.setCompressedSize(details.getSize()); @@ -277,14 +267,12 @@ class BootZipCopyAction implements CopyAction { details.copyTo(crcStream); archiveEntry.setCrc(crcStream.getCrc()); if (this.requiresUnpack.isSatisfiedBy(details)) { - archiveEntry - .setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile())); + archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile())); } } private long getTime(FileCopyDetails details) { - return this.preserveFileTimestamps ? details.getLastModified() - : CONSTANT_TIME_FOR_ZIP_ENTRIES; + return this.preserveFileTimestamps ? details.getLastModified() : CONSTANT_TIME_FOR_ZIP_ENTRIES; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java index a5f56df3858..147c19a876f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,10 +51,10 @@ public class LaunchScriptConfiguration implements Serializable { LaunchScriptConfiguration(AbstractArchiveTask archiveTask) { Project project = archiveTask.getProject(); putIfMissing(this.properties, "initInfoProvides", archiveTask.getBaseName()); - putIfMissing(this.properties, "initInfoShortDescription", - removeLineBreaks(project.getDescription()), archiveTask.getBaseName()); - putIfMissing(this.properties, "initInfoDescription", - augmentLineBreaks(project.getDescription()), archiveTask.getBaseName()); + putIfMissing(this.properties, "initInfoShortDescription", removeLineBreaks(project.getDescription()), + archiveTask.getBaseName()); + putIfMissing(this.properties, "initInfoDescription", augmentLineBreaks(project.getDescription()), + archiveTask.getBaseName()); } /** @@ -132,24 +132,20 @@ public class LaunchScriptConfiguration implements Serializable { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result - + ((this.properties == null) ? 0 : this.properties.hashCode()); + result = prime * result + ((this.properties == null) ? 0 : this.properties.hashCode()); result = prime * result + ((this.script == null) ? 0 : this.script.hashCode()); return result; } private String removeLineBreaks(String string) { - return (string != null) ? WHITE_SPACE_PATTERN.matcher(string).replaceAll(" ") - : null; + return (string != null) ? WHITE_SPACE_PATTERN.matcher(string).replaceAll(" ") : null; } private String augmentLineBreaks(String string) { - return (string != null) ? LINE_FEED_PATTERN.matcher(string).replaceAll("\n# ") - : null; + return (string != null) ? LINE_FEED_PATTERN.matcher(string).replaceAll("\n# ") : null; } - private void putIfMissing(Map properties, String key, - String... valueCandidates) { + private void putIfMissing(Map properties, String key, String... valueCandidates) { if (!properties.containsKey(key)) { for (String candidate : valueCandidates) { if (candidate != null && !candidate.isEmpty()) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/run/BootRun.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/run/BootRun.java index f204e2b8e89..99eea75b402 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/run/BootRun.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/run/BootRun.java @@ -61,8 +61,7 @@ public class BootRun extends JavaExec { * @param sourceSet the source set */ public void sourceResources(SourceSet sourceSet) { - setClasspath(getProject() - .files(sourceSet.getResources().getSrcDirs(), getClasspath()) + setClasspath(getProject().files(sourceSet.getResources().getSrcDirs(), getClasspath()) .filter((file) -> !file.equals(sourceSet.getOutput().getResourcesDir()))); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/classpath/BootRunClasspathApplication.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/classpath/BootRunClasspathApplication.java index fa1f3cad366..44f579e99ee 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/classpath/BootRunClasspathApplication.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/classpath/BootRunClasspathApplication.java @@ -32,8 +32,7 @@ public class BootRunClasspathApplication { public static void main(String[] args) { int i = 1; - for (String entry : ManagementFactory.getRuntimeMXBean().getClassPath() - .split(File.pathSeparator)) { + for (String entry : ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) { System.out.println(i++ + ". " + entry); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/GettingStartedDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/GettingStartedDocumentationTests.java index e9a7dcd3451..288f0fce3a5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/GettingStartedDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/GettingStartedDocumentationTests.java @@ -38,8 +38,7 @@ public class GettingStartedDocumentationTests { @TestTemplate public void typicalPluginsAppliesExceptedPlugins() { - this.gradleBuild.script("src/main/gradle/getting-started/typical-plugins") - .build("verify"); + this.gradleBuild.script("src/main/gradle/getting-started/typical-plugins").build("verify"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java index 2b290b164cc..c877616a0bf 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java @@ -42,20 +42,16 @@ public class IntegratingWithActuatorDocumentationTests { @TestTemplate public void basicBuildInfo() throws IOException { - this.gradleBuild - .script("src/main/gradle/integrating-with-actuator/build-info-basic") - .build("bootBuildInfo"); - assertThat(new File(this.gradleBuild.getProjectDir(), - "build/resources/main/META-INF/build-info.properties")).isFile(); + this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-basic").build("bootBuildInfo"); + assertThat(new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties")) + .isFile(); } @TestTemplate public void buildInfoCustomValues() throws IOException { - this.gradleBuild.script( - "src/main/gradle/integrating-with-actuator/build-info-custom-values") + this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-custom-values") .build("bootBuildInfo"); - File file = new File(this.gradleBuild.getProjectDir(), - "build/resources/main/META-INF/build-info.properties"); + File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); assertThat(properties).containsEntry("build.artifact", "example-app"); @@ -66,11 +62,9 @@ public class IntegratingWithActuatorDocumentationTests { @TestTemplate public void buildInfoAdditional() throws IOException { - this.gradleBuild - .script("src/main/gradle/integrating-with-actuator/build-info-additional") + this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-additional") .build("bootBuildInfo"); - File file = new File(this.gradleBuild.getProjectDir(), - "build/resources/main/META-INF/build-info.properties"); + File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); assertThat(properties).containsEntry("build.a", "alpha"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java index f64dd178321..989d6ba1900 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java @@ -39,32 +39,27 @@ public class ManagingDependenciesDocumentationTests { @TestTemplate public void dependenciesExampleEvaluatesSuccessfully() { - this.gradleBuild.script("src/main/gradle/managing-dependencies/dependencies") - .build(); + this.gradleBuild.script("src/main/gradle/managing-dependencies/dependencies").build(); } @TestTemplate public void customManagedVersions() { - assertThat(this.gradleBuild - .script("src/main/gradle/managing-dependencies/custom-version") - .build("slf4jVersion").getOutput()).contains("1.7.20"); + assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/custom-version").build("slf4jVersion") + .getOutput()).contains("1.7.20"); } @TestTemplate public void dependencyManagementInIsolation() { - assertThat(this.gradleBuild - .script("src/main/gradle/managing-dependencies/configure-bom") - .build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter "); + assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom") + .build("dependencyManagement").getOutput()).contains("org.springframework.boot:spring-boot-starter "); } @TestTemplate public void dependencyManagementInIsolationWithPluginsBlock() { Assume.assumeTrue(this.gradleBuild.getDsl() == Dsl.KOTLIN); - assertThat(this.gradleBuild.script( - "src/main/gradle/managing-dependencies/configure-bom-with-plugins") - .build("dependencyManagement").getOutput()).contains( - "org.springframework.boot:spring-boot-starter TEST-SNAPSHOT"); + assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom-with-plugins") + .build("dependencyManagement").getOutput()) + .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java index 168f3ad5b9b..e62426e3c90 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java @@ -49,14 +49,12 @@ public class PackagingDocumentationTests { @TestTemplate public void warContainerDependencyEvaluatesSuccessfully() { - this.gradleBuild.script("src/main/gradle/packaging/war-container-dependency") - .build(); + this.gradleBuild.script("src/main/gradle/packaging/war-container-dependency").build(); } @TestTemplate public void bootJarMainClass() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-main-class") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -68,8 +66,7 @@ public class PackagingDocumentationTests { @TestTemplate public void bootJarManifestMainClass() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-manifest-main-class") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-manifest-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -81,8 +78,7 @@ public class PackagingDocumentationTests { @TestTemplate public void applicationPluginMainClass() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/application-plugin-main-class") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/application-plugin-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -94,8 +90,7 @@ public class PackagingDocumentationTests { @TestTemplate public void springBootDslMainClass() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/spring-boot-dsl-main-class") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/spring-boot-dsl-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -107,23 +102,19 @@ public class PackagingDocumentationTests { @TestTemplate public void bootWarIncludeDevtools() throws IOException { - jarFile(new File(this.gradleBuild.getProjectDir(), - "spring-boot-devtools-1.2.3.RELEASE.jar")); - this.gradleBuild.script("src/main/gradle/packaging/boot-war-include-devtools") - .build("bootWar"); + jarFile(new File(this.gradleBuild.getProjectDir(), "spring-boot-devtools-1.2.3.RELEASE.jar")); + this.gradleBuild.script("src/main/gradle/packaging/boot-war-include-devtools").build("bootWar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { - assertThat(jar.getEntry("WEB-INF/lib/spring-boot-devtools-1.2.3.RELEASE.jar")) - .isNotNull(); + assertThat(jar.getEntry("WEB-INF/lib/spring-boot-devtools-1.2.3.RELEASE.jar")).isNotNull(); } } @TestTemplate public void bootJarRequiresUnpack() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-requires-unpack") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-requires-unpack").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -136,36 +127,28 @@ public class PackagingDocumentationTests { @TestTemplate public void bootJarIncludeLaunchScript() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/boot-jar-include-launch-script") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-include-launch-script").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); - assertThat(FileCopyUtils.copyToString(new FileReader(file))) - .startsWith("#!/bin/bash"); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).startsWith("#!/bin/bash"); } @TestTemplate public void bootJarLaunchScriptProperties() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/boot-jar-launch-script-properties") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-launch-script-properties").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); - assertThat(FileCopyUtils.copyToString(new FileReader(file))) - .contains("example-app.log"); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).contains("example-app.log"); } @TestTemplate public void bootJarCustomLaunchScript() throws IOException { - File customScriptFile = new File(this.gradleBuild.getProjectDir(), - "src/custom.script"); + File customScriptFile = new File(this.gradleBuild.getProjectDir(), "src/custom.script"); customScriptFile.getParentFile().mkdirs(); FileCopyUtils.copy("custom", new FileWriter(customScriptFile)); - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-custom-launch-script") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-custom-launch-script").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -174,8 +157,7 @@ public class PackagingDocumentationTests { @TestTemplate public void bootWarPropertiesLauncher() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/boot-war-properties-launcher") - .build("bootWar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-war-properties-launcher").build("bootWar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war"); assertThat(file).isFile(); @@ -187,8 +169,7 @@ public class PackagingDocumentationTests { @TestTemplate public void bootJarAndJar() { - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-and-jar") - .build("assemble"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-and-jar").build("assemble"); File jar = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(jar).isFile(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java index 743ae5b87be..5d9439a93fb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java @@ -39,17 +39,14 @@ public class PublishingDocumentationTests { @TestTemplate public void mavenUpload() throws IOException { - assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven") - .build("deployerRepository").getOutput()) - .contains("https://repo.example.com"); + assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven").build("deployerRepository").getOutput()) + .contains("https://repo.example.com"); } @TestTemplate public void mavenPublish() throws IOException { - assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven-publish") - .build("publishingConfiguration").getOutput()) - .contains("MavenPublication") - .contains("https://repo.example.com"); + assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven-publish").build("publishingConfiguration") + .getOutput()).contains("MavenPublication").contains("https://repo.example.com"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java index c5de622e504..20d295f4803 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java @@ -40,39 +40,31 @@ public class RunningDocumentationTests { @TestTemplate public void bootRunMain() throws IOException { - assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-main") - .build("configuredMainClass").getOutput()) - .contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-main").build("configuredMainClass") + .getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate public void applicationPluginMainClassName() { - assertThat(this.gradleBuild - .script("src/main/gradle/running/application-plugin-main-class-name") - .build("configuredMainClass").getOutput()) - .contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/main/gradle/running/application-plugin-main-class-name") + .build("configuredMainClass").getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate public void springBootDslMainClassName() throws IOException { - assertThat(this.gradleBuild - .script("src/main/gradle/running/spring-boot-dsl-main-class-name") - .build("configuredMainClass").getOutput()) - .contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/main/gradle/running/spring-boot-dsl-main-class-name") + .build("configuredMainClass").getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate public void bootRunSourceResources() throws IOException { - assertThat(this.gradleBuild - .script("src/main/gradle/running/boot-run-source-resources") - .build("configuredClasspath").getOutput()) - .contains(new File("src/main/resources").getPath()); + assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-source-resources") + .build("configuredClasspath").getOutput()).contains(new File("src/main/resources").getPath()); } @TestTemplate public void bootRunDisableOptimizedLaunch() throws IOException { - assertThat(this.gradleBuild - .script("src/main/gradle/running/boot-run-disable-optimized-launch") + assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-disable-optimized-launch") .build("optimizedLaunch").getOutput()).contains("false"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java index 21a367caa54..d08b4d59be5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java @@ -44,24 +44,21 @@ public class BuildInfoDslIntegrationTests { @Test public void basicJar() throws IOException { - assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace") - .task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); - assertThat(properties).containsEntry("build.name", - this.gradleBuild.getProjectDir().getName()); - assertThat(properties).containsEntry("build.artifact", - this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.group", "com.example"); assertThat(properties).containsEntry("build.version", "1.0"); } @Test public void jarWithCustomName() throws IOException { - assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace") - .task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); - assertThat(properties).containsEntry("build.name", - this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", "foo"); assertThat(properties).containsEntry("build.group", "com.example"); assertThat(properties).containsEntry("build.version", "1.0"); @@ -69,24 +66,21 @@ public class BuildInfoDslIntegrationTests { @Test public void basicWar() throws IOException { - assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace") - .task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); - assertThat(properties).containsEntry("build.name", - this.gradleBuild.getProjectDir().getName()); - assertThat(properties).containsEntry("build.artifact", - this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.group", "com.example"); assertThat(properties).containsEntry("build.version", "1.0"); } @Test public void warWithCustomName() throws IOException { - assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace") - .task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); - assertThat(properties).containsEntry("build.name", - this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", "foo"); assertThat(properties).containsEntry("build.group", "com.example"); assertThat(properties).containsEntry("build.version", "1.0"); @@ -94,13 +88,11 @@ public class BuildInfoDslIntegrationTests { @Test public void additionalProperties() throws IOException { - assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace") - .task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); - assertThat(properties).containsEntry("build.name", - this.gradleBuild.getProjectDir().getName()); - assertThat(properties).containsEntry("build.artifact", - this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); + assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.group", "com.example"); assertThat(properties).containsEntry("build.version", "1.0"); assertThat(properties).containsEntry("build.a", "alpha"); @@ -109,13 +101,12 @@ public class BuildInfoDslIntegrationTests { @Test public void classesDependency() throws IOException { - assertThat(this.gradleBuild.build("classes", "--stacktrace") - .task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("classes", "--stacktrace").task(":bootBuildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); } private Properties buildInfoProperties() { - File file = new File(this.gradleBuild.getProjectDir(), - "build/resources/main/META-INF/build-info.properties"); + File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = new Properties(); try (FileReader reader = new FileReader(file)) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleBuildFieldSetter.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleBuildFieldSetter.java index c77f99b4c23..b4fafbf81e8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleBuildFieldSetter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleBuildFieldSetter.java @@ -40,8 +40,7 @@ final class GradleBuildFieldSetter implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) throws Exception { - Field field = ReflectionUtils.findField(context.getRequiredTestClass(), - "gradleBuild"); + Field field = ReflectionUtils.findField(context.getRequiredTestClass(), "gradleBuild"); field.setAccessible(true); field.set(context.getRequiredTestInstance(), this.gradleBuild); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java index 76333face01..d9313334a30 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java @@ -35,17 +35,14 @@ import org.springframework.boot.gradle.testkit.GradleBuildExtension; * * @author Andy Wilkinson */ -public final class GradleCompatibilityExtension - implements TestTemplateInvocationContextProvider { +public final class GradleCompatibilityExtension implements TestTemplateInvocationContextProvider { - private static final List GRADLE_VERSIONS = Arrays.asList("default", "5.0", - "5.1.1", "5.2.1", "5.3.1", "5.4.1"); + private static final List GRADLE_VERSIONS = Arrays.asList("default", "5.0", "5.1.1", "5.2.1", "5.3.1", + "5.4.1"); @Override - public Stream provideTestTemplateInvocationContexts( - ExtensionContext context) { - return GRADLE_VERSIONS.stream() - .map(GradleVersionTestTemplateInvocationContext::new); + public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { + return GRADLE_VERSIONS.stream().map(GradleVersionTestTemplateInvocationContext::new); } @Override @@ -53,8 +50,7 @@ public final class GradleCompatibilityExtension return true; } - private static final class GradleVersionTestTemplateInvocationContext - implements TestTemplateInvocationContext { + private static final class GradleVersionTestTemplateInvocationContext implements TestTemplateInvocationContext { private final String gradleVersion; @@ -73,8 +69,7 @@ public final class GradleCompatibilityExtension if (!this.gradleVersion.equals("default")) { gradleBuild.gradleVersion(this.gradleVersion); } - return Arrays.asList(new GradleBuildFieldSetter(gradleBuild), - new GradleBuildExtension()); + return Arrays.asList(new GradleBuildFieldSetter(gradleBuild), new GradleBuildExtension()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleMultiDslExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleMultiDslExtension.java index cf84e56f7f9..a184896c277 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleMultiDslExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleMultiDslExtension.java @@ -39,8 +39,7 @@ import org.springframework.boot.gradle.testkit.GradleBuildExtension; public class GradleMultiDslExtension implements TestTemplateInvocationContextProvider { @Override - public Stream provideTestTemplateInvocationContexts( - ExtensionContext context) { + public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { return Stream.of(Dsl.values()).map(DslTestTemplateInvocationContext::new); } @@ -49,8 +48,7 @@ public class GradleMultiDslExtension implements TestTemplateInvocationContextPro return true; } - private static final class DslTestTemplateInvocationContext - implements TestTemplateInvocationContext { + private static final class DslTestTemplateInvocationContext implements TestTemplateInvocationContext { private final Dsl dsl; @@ -60,8 +58,7 @@ public class GradleMultiDslExtension implements TestTemplateInvocationContextPro @Override public List getAdditionalExtensions() { - return Arrays.asList(new GradleBuildFieldSetter(new GradleBuild(this.dsl)), - new GradleBuildExtension()); + return Arrays.asList(new GradleBuildFieldSetter(new GradleBuild(this.dsl)), new GradleBuildExtension()); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java index deb6b3e2eb0..430fe735631 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java @@ -49,120 +49,100 @@ public class ApplicationPluginActionIntegrationTests { @TestTemplate public void noBootDistributionWithoutApplicationPluginApplied() { - assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot") - .getOutput()).contains("boot exists = false"); + assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot").getOutput()) + .contains("boot exists = false"); } @TestTemplate public void applyingApplicationPluginCreatesBootDistribution() { - assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot", - "-PapplyApplicationPlugin").getOutput()).contains("boot exists = true"); + assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot", "-PapplyApplicationPlugin") + .getOutput()).contains("boot exists = true"); } @TestTemplate public void noBootStartScriptsTaskWithoutApplicationPluginApplied() { - assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts") - .getOutput()).contains("bootStartScripts exists = false"); + assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts").getOutput()) + .contains("bootStartScripts exists = false"); } @TestTemplate public void applyingApplicationPluginCreatesBootStartScriptsTask() { - assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts", - "-PapplyApplicationPlugin").getOutput()) - .contains("bootStartScripts exists = true"); + assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts", "-PapplyApplicationPlugin") + .getOutput()).contains("bootStartScripts exists = true"); } @TestTemplate public void createsBootStartScriptsTaskUsesApplicationPluginsDefaultJvmOpts() { - assertThat(this.gradleBuild - .build("startScriptsDefaultJvmOpts", "-PapplyApplicationPlugin") - .getOutput()).contains( - "bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]"); + assertThat(this.gradleBuild.build("startScriptsDefaultJvmOpts", "-PapplyApplicationPlugin").getOutput()) + .contains("bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]"); } @TestTemplate public void zipDistributionForJarCanBeBuilt() throws IOException { - assertThat( - this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); - File distribution = new File(this.gradleBuild.getProjectDir(), - "build/distributions/" + name + "-boot.zip"); + File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip"); assertThat(distribution).isFile(); - assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", - name + "-boot/lib/", name + "-boot/lib/" + name + ".jar", - name + "-boot/bin/", name + "-boot/bin/" + name, + assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/", + name + "-boot/lib/" + name + ".jar", name + "-boot/bin/", name + "-boot/bin/" + name, name + "-boot/bin/" + name + ".bat"); } @TestTemplate public void tarDistributionForJarCanBeBuilt() throws IOException { - assertThat( - this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); - File distribution = new File(this.gradleBuild.getProjectDir(), - "build/distributions/" + name + "-boot.tar"); + File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); - assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", - name + "-boot/lib/", name + "-boot/lib/" + name + ".jar", - name + "-boot/bin/", name + "-boot/bin/" + name, + assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/", + name + "-boot/lib/" + name + ".jar", name + "-boot/bin/", name + "-boot/bin/" + name, name + "-boot/bin/" + name + ".bat"); } @TestTemplate public void zipDistributionForWarCanBeBuilt() throws IOException { - assertThat( - this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); - File distribution = new File(this.gradleBuild.getProjectDir(), - "build/distributions/" + name + "-boot.zip"); + File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip"); assertThat(distribution).isFile(); - assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", - name + "-boot/lib/", name + "-boot/lib/" + name + ".war", - name + "-boot/bin/", name + "-boot/bin/" + name, + assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/", + name + "-boot/lib/" + name + ".war", name + "-boot/bin/", name + "-boot/bin/" + name, name + "-boot/bin/" + name + ".bat"); } @TestTemplate public void tarDistributionForWarCanBeBuilt() throws IOException { - assertThat( - this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); - File distribution = new File(this.gradleBuild.getProjectDir(), - "build/distributions/" + name + "-boot.tar"); + File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); - assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", - name + "-boot/lib/", name + "-boot/lib/" + name + ".war", - name + "-boot/bin/", name + "-boot/bin/" + name, + assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/", + name + "-boot/lib/" + name + ".war", name + "-boot/bin/", name + "-boot/bin/" + name, name + "-boot/bin/" + name + ".bat"); } @TestTemplate public void applicationNameCanBeUsedToCustomizeDistributionName() throws IOException { - assertThat( - this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); - File distribution = new File(this.gradleBuild.getProjectDir(), - "build/distributions/custom-boot.tar"); + assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/custom-boot.tar"); assertThat(distribution).isFile(); String name = this.gradleBuild.getProjectDir().getName(); - assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder("custom-boot/", - "custom-boot/lib/", "custom-boot/lib/" + name + ".jar", - "custom-boot/bin/", "custom-boot/bin/custom", + assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder("custom-boot/", "custom-boot/lib/", + "custom-boot/lib/" + name + ".jar", "custom-boot/bin/", "custom-boot/bin/custom", "custom-boot/bin/custom.bat"); } @TestTemplate public void scriptsHaveCorrectPermissions() throws IOException { - assertThat( - this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); - File distribution = new File(this.gradleBuild.getProjectDir(), - "build/distributions/" + name + "-boot.tar"); + File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); tarEntries(distribution, (entry) -> { int filePermissions = entry.getMode() & 0777; @@ -188,8 +168,7 @@ public class ApplicationPluginActionIntegrationTests { private List tarEntryNames(File distribution) throws IOException { List entryNames = new ArrayList<>(); - try (TarArchiveInputStream input = new TarArchiveInputStream( - new FileInputStream(distribution))) { + try (TarArchiveInputStream input = new TarArchiveInputStream(new FileInputStream(distribution))) { TarArchiveEntry entry; while ((entry = input.getNextTarEntry()) != null) { entryNames.add(entry.getName()); @@ -198,10 +177,8 @@ public class ApplicationPluginActionIntegrationTests { return entryNames; } - private void tarEntries(File distribution, Consumer consumer) - throws IOException { - try (TarArchiveInputStream input = new TarArchiveInputStream( - new FileInputStream(distribution))) { + private void tarEntries(File distribution, Consumer consumer) throws IOException { + try (TarArchiveInputStream input = new TarArchiveInputStream(new FileInputStream(distribution))) { TarArchiveEntry entry; while ((entry = input.getNextTarEntry()) != null) { consumer.accept(entry); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java index 358d5987794..d374500f668 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java @@ -43,35 +43,28 @@ public class DependencyManagementPluginActionIntegrationTests { @TestTemplate public void noDependencyManagementIsAppliedByDefault() { - assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement") - .task(":doesNotHaveDependencyManagement").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement").task(":doesNotHaveDependencyManagement") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void bomIsImportedWhenDependencyManagementPluginIsApplied() { - assertThat(this.gradleBuild - .build("hasDependencyManagement", "-PapplyDependencyManagementPlugin") - .task(":hasDependencyManagement").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("hasDependencyManagement", "-PapplyDependencyManagementPlugin") + .task(":hasDependencyManagement").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void helpfulErrorWhenVersionlessDependencyFailsToResolve() throws IOException { - File examplePackage = new File(this.gradleBuild.getProjectDir(), - "src/main/java/com/example"); + File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example"); examplePackage.mkdirs(); - FileSystemUtils.copyRecursively(new File("src/test/java/com/example"), - examplePackage); + FileSystemUtils.copyRecursively(new File("src/test/java/com/example"), examplePackage); BuildResult result = this.gradleBuild.buildAndFail("compileJava"); - assertThat(result.task(":compileJava").getOutcome()) - .isEqualTo(TaskOutcome.FAILED); + assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.FAILED); String output = result.getOutput(); assertThat(output).contains("During the build, one or more dependencies that " + "were declared without a version failed to resolve:"); assertThat(output).contains("org.springframework.boot:spring-boot-starter-web:"); - assertThat(output).contains("Did you forget to apply the " - + "io.spring.dependency-management plugin to the " + assertThat(output).contains("Did you forget to apply the " + "io.spring.dependency-management plugin to the " + this.gradleBuild.getProjectDir().getName() + " project?"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java index 42a8fb98b59..71ebe701f18 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java @@ -49,9 +49,8 @@ public class JavaPluginActionIntegrationTests { @TestTemplate public void applyingJavaPluginCreatesBootJarTask() { - assertThat(this.gradleBuild - .build("taskExists", "-PtaskName=bootJar", "-PapplyJavaPlugin") - .getOutput()).contains("bootJar exists = true"); + assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootJar", "-PapplyJavaPlugin").getOutput()) + .contains("bootJar exists = true"); } @TestTemplate @@ -62,16 +61,14 @@ public class JavaPluginActionIntegrationTests { @TestTemplate public void applyingJavaPluginCreatesBootRunTask() { - assertThat(this.gradleBuild - .build("taskExists", "-PtaskName=bootRun", "-PapplyJavaPlugin") - .getOutput()).contains("bootRun exists = true"); + assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootRun", "-PapplyJavaPlugin").getOutput()) + .contains("bootRun exists = true"); } @TestTemplate public void javaCompileTasksUseUtf8Encoding() { - assertThat(this.gradleBuild.build("javaCompileEncoding", "-PapplyJavaPlugin") - .getOutput()).contains("compileJava = UTF-8") - .contains("compileTestJava = UTF-8"); + assertThat(this.gradleBuild.build("javaCompileEncoding", "-PapplyJavaPlugin").getOutput()) + .contains("compileJava = UTF-8").contains("compileTestJava = UTF-8"); } @TestTemplate @@ -106,8 +103,7 @@ public class JavaPluginActionIntegrationTests { public void errorMessageIsHelpfulWhenMainClassCannotBeResolved() { BuildResult result = this.gradleBuild.buildAndFail("build", "-PapplyJavaPlugin"); assertThat(result.task(":bootJar").getOutcome()).isEqualTo(TaskOutcome.FAILED); - assertThat(result.getOutput()).contains( - "Main class name has not been configured and it could not be resolved"); + assertThat(result.getOutput()).contains("Main class name has not been configured and it could not be resolved"); } @TestTemplate @@ -118,42 +114,33 @@ public class JavaPluginActionIntegrationTests { File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs"); assertThat(buildLibs.listFiles()).containsExactlyInAnyOrder( new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".jar"), - new File(buildLibs, - this.gradleBuild.getProjectDir().getName() + "-boot.jar")); + new File(buildLibs, this.gradleBuild.getProjectDir().getName() + "-boot.jar")); } @TestTemplate - public void additionalMetadataLocationsConfiguredWhenProcessorIsPresent() - throws IOException { + public void additionalMetadataLocationsConfiguredWhenProcessorIsPresent() throws IOException { createMinimalMainSource(); File libs = new File(this.gradleBuild.getProjectDir(), "libs"); libs.mkdirs(); - new JarOutputStream(new FileOutputStream( - new File(libs, "spring-boot-configuration-processor-1.2.3.jar"))).close(); + new JarOutputStream(new FileOutputStream(new File(libs, "spring-boot-configuration-processor-1.2.3.jar"))) + .close(); BuildResult result = this.gradleBuild.build("compileJava"); - assertThat(result.task(":compileJava").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains( - "compileJava compiler args: [-parameters, -Aorg.springframework.boot." - + "configurationprocessor.additionalMetadataLocations=" - + new File(this.gradleBuild.getProjectDir(), "src/main/resources") - .getCanonicalPath()); + assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.getOutput()).contains("compileJava compiler args: [-parameters, -Aorg.springframework.boot." + + "configurationprocessor.additionalMetadataLocations=" + + new File(this.gradleBuild.getProjectDir(), "src/main/resources").getCanonicalPath()); } @TestTemplate - public void additionalMetadataLocationsNotConfiguredWhenProcessorIsAbsent() - throws IOException { + public void additionalMetadataLocationsNotConfiguredWhenProcessorIsAbsent() throws IOException { createMinimalMainSource(); BuildResult result = this.gradleBuild.build("compileJava"); - assertThat(result.task(":compileJava").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()) - .contains("compileJava compiler args: [-parameters]"); + assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.getOutput()).contains("compileJava compiler args: [-parameters]"); } private void createMinimalMainSource() throws IOException { - File examplePackage = new File(this.gradleBuild.getProjectDir(), - "src/main/java/com/example"); + File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example"); examplePackage.mkdirs(); new File(examplePackage, "Application.java").createNewFile(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java index eb38a28055f..0c34193164d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java @@ -36,29 +36,26 @@ public class KotlinPluginActionIntegrationTests { @TestTemplate public void noKotlinVersionPropertyWithoutKotlinPlugin() { - assertThat(this.gradleBuild.build("kotlinVersion").getOutput()) - .contains("Kotlin version: none"); + assertThat(this.gradleBuild.build("kotlinVersion").getOutput()).contains("Kotlin version: none"); } @TestTemplate public void kotlinVersionPropertyIsSet() { - String output = this.gradleBuild.build("kotlinVersion", "dependencies", - "--configuration", "compileClasspath").getOutput(); + String output = this.gradleBuild.build("kotlinVersion", "dependencies", "--configuration", "compileClasspath") + .getOutput(); assertThat(output).containsPattern("Kotlin version: [0-9]\\.[0-9]\\.[0-9]+"); } @TestTemplate public void kotlinCompileTasksUseJavaParametersFlagByDefault() { assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput()) - .contains("compileKotlin java parameters: true") - .contains("compileTestKotlin java parameters: true"); + .contains("compileKotlin java parameters: true").contains("compileTestKotlin java parameters: true"); } @TestTemplate public void kotlinCompileTasksCanOverrideDefaultJavaParametersFlag() { assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput()) - .contains("compileKotlin java parameters: false") - .contains("compileTestKotlin java parameters: false"); + .contains("compileKotlin java parameters: false").contains("compileTestKotlin java parameters: false"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MainClassConventionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MainClassConventionTests.java index fc116ba7c0e..c9ddf005e28 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MainClassConventionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MainClassConventionTests.java @@ -47,29 +47,27 @@ public class MainClassConventionTests { @Test public void mainClassNameProjectPropertyIsUsed() throws Exception { - this.project.getExtensions().getByType(ExtraPropertiesExtension.class) - .set("mainClassName", "com.example.MainClass"); + this.project.getExtensions().getByType(ExtraPropertiesExtension.class).set("mainClassName", + "com.example.MainClass"); assertThat(this.convention.call()).isEqualTo("com.example.MainClass"); } @Test public void springBootExtensionMainClassNameIsUsed() throws Exception { - SpringBootExtension extension = this.project.getExtensions().create("springBoot", - SpringBootExtension.class, this.project); + SpringBootExtension extension = this.project.getExtensions().create("springBoot", SpringBootExtension.class, + this.project); extension.setMainClassName("com.example.MainClass"); assertThat(this.convention.call()).isEqualTo("com.example.MainClass"); } @Test - public void springBootExtensionMainClassNameIsUsedInPreferenceToMainClassNameProjectProperty() - throws Exception { - this.project.getExtensions().getByType(ExtraPropertiesExtension.class) - .set("mainClassName", "com.example.ProjectPropertyMainClass"); - SpringBootExtension extension = this.project.getExtensions().create("springBoot", - SpringBootExtension.class, this.project); + public void springBootExtensionMainClassNameIsUsedInPreferenceToMainClassNameProjectProperty() throws Exception { + this.project.getExtensions().getByType(ExtraPropertiesExtension.class).set("mainClassName", + "com.example.ProjectPropertyMainClass"); + SpringBootExtension extension = this.project.getExtensions().create("springBoot", SpringBootExtension.class, + this.project); extension.setMainClassName("com.example.SpringBootExtensionMainClass"); - assertThat(this.convention.call()) - .isEqualTo("com.example.SpringBootExtensionMainClass"); + assertThat(this.convention.call()).isEqualTo("com.example.SpringBootExtensionMainClass"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MavenPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MavenPluginActionIntegrationTests.java index bf3af132e06..97928fd2108 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MavenPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/MavenPluginActionIntegrationTests.java @@ -36,8 +36,7 @@ public class MavenPluginActionIntegrationTests { @TestTemplate public void clearsConf2ScopeMappingsOfUploadBootArchivesTask() { - assertThat(this.gradleBuild.build("conf2ScopeMappings").getOutput()) - .contains("Conf2ScopeMappings = 0"); + assertThat(this.gradleBuild.build("conf2ScopeMappings").getOutput()).contains("Conf2ScopeMappings = 0"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java index 14e357e29ed..88eed0f09a4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java @@ -41,8 +41,8 @@ public class SpringBootPluginIntegrationTests { @Test public void failFastWithVersionOfGradleLowerThanRequired() { BuildResult result = this.gradleBuild.gradleVersion("4.9").buildAndFail(); - assertThat(result.getOutput()).contains("Spring Boot plugin requires Gradle 4.10" - + " or later. The current version is Gradle 4.9"); + assertThat(result.getOutput()) + .contains("Spring Boot plugin requires Gradle 4.10" + " or later. The current version is Gradle 4.9"); } @Test @@ -56,19 +56,17 @@ public class SpringBootPluginIntegrationTests { } @Test - public void unresolvedDependenciesAreAnalyzedWhenDependencyResolutionFails() - throws IOException { + public void unresolvedDependenciesAreAnalyzedWhenDependencyResolutionFails() throws IOException { createMinimalMainSource(); BuildResult result = this.gradleBuild.buildAndFail("compileJava"); - assertThat(result.getOutput()).contains( - "During the build, one or more dependencies that were declared without a" + assertThat(result.getOutput()) + .contains("During the build, one or more dependencies that were declared without a" + " version failed to resolve:") .contains(" org.springframework.boot:spring-boot-starter:"); } private void createMinimalMainSource() throws IOException { - File examplePackage = new File(this.gradleBuild.getProjectDir(), - "src/main/java/com/example"); + File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example"); examplePackage.mkdirs(); new File(examplePackage, "Application.java").createNewFile(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java index 595e960a7e7..6da554754d6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java @@ -46,9 +46,8 @@ public class WarPluginActionIntegrationTests { @TestTemplate public void applyingWarPluginCreatesBootWarTask() { - assertThat(this.gradleBuild - .build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin") - .getOutput()).contains("bootWar exists = true"); + assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin").getOutput()) + .contains("bootWar exists = true"); } @TestTemplate @@ -66,16 +65,14 @@ public class WarPluginActionIntegrationTests { File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs"); assertThat(buildLibs.listFiles()).containsExactlyInAnyOrder( new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war"), - new File(buildLibs, - this.gradleBuild.getProjectDir().getName() + "-boot.war")); + new File(buildLibs, this.gradleBuild.getProjectDir().getName() + "-boot.war")); } @TestTemplate public void errorMessageIsHelpfulWhenMainClassCannotBeResolved() { BuildResult result = this.gradleBuild.buildAndFail("build", "-PapplyWarPlugin"); assertThat(result.task(":bootWar").getOutcome()).isEqualTo(TaskOutcome.FAILED); - assertThat(result.getOutput()).contains( - "Main class name has not been configured and it could not be resolved"); + assertThat(result.getOutput()).contains("Main class name has not been configured and it could not be resolved"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java index 7b560c7aabd..2e82719b923 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java @@ -46,21 +46,18 @@ public class BuildInfoIntegrationTests { @TestTemplate public void defaultValues() { - assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); Properties buildInfoProperties = buildInfoProperties(); assertThat(buildInfoProperties).containsKey("build.time"); assertThat(buildInfoProperties).containsEntry("build.artifact", "unspecified"); assertThat(buildInfoProperties).containsEntry("build.group", ""); - assertThat(buildInfoProperties).containsEntry("build.name", - this.gradleBuild.getProjectDir().getName()); + assertThat(buildInfoProperties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(buildInfoProperties).containsEntry("build.version", "unspecified"); } @TestTemplate public void basicExecution() { - assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); Properties buildInfoProperties = buildInfoProperties(); assertThat(buildInfoProperties).containsKey("build.time"); assertThat(buildInfoProperties).containsEntry("build.artifact", "foo"); @@ -72,49 +69,43 @@ public class BuildInfoIntegrationTests { @TestTemplate public void notUpToDateWhenExecutedTwiceAsTimeChanges() { - assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void upToDateWhenExecutedTwiceWithFixedTime() { - assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate public void notUpToDateWhenExecutedTwiceWithFixedTimeAndChangedProjectVersion() { - assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - BuildResult result = this.gradleBuild.build("buildInfo", "-PnullTime", - "-PprojectVersion=0.2.0"); + assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + BuildResult result = this.gradleBuild.build("buildInfo", "-PnullTime", "-PprojectVersion=0.2.0"); assertThat(result.task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void reproducibleOutputWithFixedTime() - throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, - IOException, InterruptedException { - assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - File buildInfoProperties = new File(this.gradleBuild.getProjectDir(), - "build/build-info.properties"); + throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException, InterruptedException { + assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + File buildInfoProperties = new File(this.gradleBuild.getProjectDir(), "build/build-info.properties"); String firstHash = FileUtils.sha1Hash(buildInfoProperties); assertThat(buildInfoProperties.delete()).isTrue(); Thread.sleep(1500); - assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String secondHash = FileUtils.sha1Hash(buildInfoProperties); assertThat(firstHash).isEqualTo(secondHash); } private Properties buildInfoProperties() { - File file = new File(this.gradleBuild.getProjectDir(), - "build/build-info.properties"); + File file = new File(this.gradleBuild.getProjectDir(), "build/build-info.properties"); assertThat(file).isFile(); Properties properties = new Properties(); try (FileReader reader = new FileReader(file)) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java index 4d26094d9f6..47d1a5913de 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java @@ -111,8 +111,7 @@ public class BuildInfoTests { Instant now = Instant.now(); BuildInfo task = createTask(createProject("test")); task.getProperties().setTime(now); - assertThat(buildInfoProperties(task)).containsEntry("build.time", - DateTimeFormatter.ISO_INSTANT.format(now)); + assertThat(buildInfoProperties(task)).containsEntry("build.time", DateTimeFormatter.ISO_INSTANT.format(now)); } @Test @@ -126,8 +125,7 @@ public class BuildInfoTests { private Project createProject(String projectName) { File projectDir = new File(this.temp, projectName); - return ProjectBuilder.builder().withProjectDir(projectDir).withName(projectName) - .build(); + return ProjectBuilder.builder().withProjectDir(projectDir).withName(projectName).build(); } private BuildInfo createTask(Project project) { @@ -136,8 +134,7 @@ public class BuildInfoTests { private Properties buildInfoProperties(BuildInfo task) { task.generateBuildProperties(); - return buildInfoProperties( - new File(task.getDestinationDir(), "build-info.properties")); + return buildInfoProperties(new File(task.getDestinationDir(), "build-info.properties")); } private Properties buildInfoProperties(File file) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java index 20c623edfa0..6b99c666223 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java @@ -49,80 +49,72 @@ public abstract class AbstractBootArchiveIntegrationTests { } @TestTemplate - public void basicBuild() throws InvalidRunnerConfigurationException, - UnexpectedBuildFailure, IOException { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + public void basicBuild() throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException { + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate - public void reproducibleArchive() throws InvalidRunnerConfigurationException, - UnexpectedBuildFailure, IOException, InterruptedException { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - File jar = new File(this.gradleBuild.getProjectDir(), "build/libs") - .listFiles()[0]; + public void reproducibleArchive() + throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException, InterruptedException { + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + File jar = new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0]; String firstHash = FileUtils.sha1Hash(jar); Thread.sleep(1500); - assertThat(this.gradleBuild.build("clean", this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("clean", this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); String secondHash = FileUtils.sha1Hash(jar); assertThat(firstHash).isEqualTo(secondHash); } @TestTemplate - public void upToDateWhenBuiltTwice() throws InvalidRunnerConfigurationException, - UnexpectedBuildFailure, IOException { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + public void upToDateWhenBuiltTwice() + throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException { + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate public void upToDateWhenBuiltTwiceWithLaunchScriptIncluded() - throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, - IOException { - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) - .task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException { + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate public void notUpToDateWhenLaunchScriptWasNotIncludedAndThenIsIncluded() { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void notUpToDateWhenLaunchScriptWasIncludedAndThenIsNotIncluded() { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void notUpToDateWhenLaunchScriptPropertyChanges() { - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", - "-PlaunchScriptProperty=foo", this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", - "-PlaunchScriptProperty=bar", this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", "-PlaunchScriptProperty=foo", this.taskName) + .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", "-PlaunchScriptProperty=bar", this.taskName) + .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate public void applicationPluginMainClassNameIsUsed() throws IOException { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - try (JarFile jarFile = new JarFile( - new File(this.gradleBuild.getProjectDir(), "build/libs") - .listFiles()[0])) { + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.CustomMain"); } @@ -130,11 +122,9 @@ public abstract class AbstractBootArchiveIntegrationTests { @TestTemplate public void springBootExtensionMainClassNameIsUsed() throws IOException { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - try (JarFile jarFile = new JarFile( - new File(this.gradleBuild.getProjectDir(), "build/libs") - .listFiles()[0])) { + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); + try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.CustomMain"); } @@ -142,8 +132,8 @@ public abstract class AbstractBootArchiveIntegrationTests { @TestTemplate public void duplicatesAreHandledGracefully() throws IOException { - assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.SUCCESS); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java index 9059decee92..b6c0940f48e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java @@ -72,8 +72,7 @@ public abstract class AbstractBootArchiveTests { private T task; - protected AbstractBootArchiveTests(Class taskClass, String launcherClass, - String libPath, String classesPath) { + protected AbstractBootArchiveTests(Class taskClass, String launcherClass, String libPath, String classesPath) { this.taskClass = taskClass; this.launcherClass = launcherClass; this.libPath = libPath; @@ -86,10 +85,8 @@ public abstract class AbstractBootArchiveTests { File projectDir = new File(this.temp, "project"); projectDir.mkdirs(); this.project = ProjectBuilder.builder().withProjectDir(projectDir).build(); - this.project - .setDescription("Test project for " + this.taskClass.getSimpleName()); - this.task = configure( - this.project.getTasks().create("testArchive", this.taskClass)); + this.project.setDescription("Test project for " + this.taskClass.getSimpleName()); + this.task = configure(this.project.getTasks().create("testArchive", this.taskClass)); } catch (IOException ex) { throw new RuntimeException(ex); @@ -102,17 +99,12 @@ public abstract class AbstractBootArchiveTests { executeTask(); assertThat(this.task.getArchivePath()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")) - .isEqualTo(this.launcherClass); - assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.Main"); - assertThat(jarFile.getManifest().getMainAttributes() - .getValue("Spring-Boot-Classes")).isEqualTo(this.classesPath); - assertThat( - jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")) - .isEqualTo(this.libPath); - assertThat(jarFile.getManifest().getMainAttributes() - .getValue("Spring-Boot-Version")).isNotNull(); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main"); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) + .isEqualTo(this.classesPath); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Version")).isNotNull(); } } @@ -131,16 +123,13 @@ public abstract class AbstractBootArchiveTests { public void classpathFoldersArePackagedBeneathClassesPath() throws IOException { this.task.setMainClassName("com.example.Main"); File classpathFolder = new File(this.temp, "classes"); - File applicationClass = new File(classpathFolder, - "com/example/Application.class"); + File applicationClass = new File(classpathFolder, "com/example/Application.class"); applicationClass.getParentFile().mkdirs(); applicationClass.createNewFile(); this.task.classpath(classpathFolder); executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat( - jarFile.getEntry(this.classesPath + "com/example/Application.class")) - .isNotNull(); + assertThat(jarFile.getEntry(this.classesPath + "com/example/Application.class")).isNotNull(); } } @@ -151,20 +140,16 @@ public abstract class AbstractBootArchiveTests { File moduleInfoClass = new File(classpathFolder, "module-info.class"); moduleInfoClass.getParentFile().mkdirs(); moduleInfoClass.createNewFile(); - File applicationClass = new File(classpathFolder, - "com/example/Application.class"); + File applicationClass = new File(classpathFolder, "com/example/Application.class"); applicationClass.getParentFile().mkdirs(); applicationClass.createNewFile(); this.task.classpath(classpathFolder); this.task.execute(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat( - jarFile.getEntry(this.classesPath + "com/example/Application.class")) - .isNotNull(); + assertThat(jarFile.getEntry(this.classesPath + "com/example/Application.class")).isNotNull(); assertThat(jarFile.getEntry("com/example/Application.class")).isNull(); assertThat(jarFile.getEntry("module-info.class")).isNotNull(); - assertThat(jarFile.getEntry(this.classesPath + "/module-info.class")) - .isNull(); + assertThat(jarFile.getEntry(this.classesPath + "/module-info.class")).isNull(); } } @@ -207,24 +192,18 @@ public abstract class AbstractBootArchiveTests { this.task.setMainClassName("com.example.Main"); executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getEntry( - "org/springframework/boot/loader/LaunchedURLClassLoader.class")) - .isNotNull(); + assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNotNull(); assertThat(jarFile.getEntry("org/springframework/boot/loader/")).isNotNull(); } } @Test - public void loaderIsWrittenToTheRootOfTheJarWhenUsingThePropertiesLauncher() - throws IOException { + public void loaderIsWrittenToTheRootOfTheJarWhenUsingThePropertiesLauncher() throws IOException { this.task.setMainClassName("com.example.Main"); executeTask(); - this.task.getManifest().getAttributes().put("Main-Class", - "org.springframework.boot.loader.PropertiesLauncher"); + this.task.getManifest().getAttributes().put("Main-Class", "org.springframework.boot.loader.PropertiesLauncher"); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getEntry( - "org/springframework/boot/loader/LaunchedURLClassLoader.class")) - .isNotNull(); + assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNotNull(); assertThat(jarFile.getEntry("org/springframework/boot/loader/")).isNotNull(); } } @@ -236,8 +215,7 @@ public abstract class AbstractBootArchiveTests { this.task.requiresUnpack("**/one.jar"); executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getEntry(this.libPath + "one.jar").getComment()) - .startsWith("UNPACK:"); + assertThat(jarFile.getEntry(this.libPath + "one.jar").getComment()).startsWith("UNPACK:"); assertThat(jarFile.getEntry(this.libPath + "two.jar").getComment()).isNull(); } } @@ -249,8 +227,7 @@ public abstract class AbstractBootArchiveTests { this.task.requiresUnpack((element) -> element.getName().endsWith("two.jar")); executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getEntry(this.libPath + "two.jar").getComment()) - .startsWith("UNPACK:"); + assertThat(jarFile.getEntry(this.libPath + "two.jar").getComment()).startsWith("UNPACK:"); assertThat(jarFile.getEntry(this.libPath + "one.jar").getComment()).isNull(); } } @@ -267,8 +244,7 @@ public abstract class AbstractBootArchiveTests { assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())) .startsWith(new DefaultLaunchScript(null, properties).toByteArray()); try { - Set permissions = Files - .getPosixFilePermissions(this.task.getArchivePath().toPath()); + Set permissions = Files.getPosixFilePermissions(this.task.getArchivePath().toPath()); assertThat(permissions).contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { @@ -280,12 +256,10 @@ public abstract class AbstractBootArchiveTests { public void customLaunchScriptCanBePrepended() throws IOException { this.task.setMainClassName("com.example.Main"); File customScript = new File(this.temp, "custom.script"); - Files.write(customScript.toPath(), Arrays.asList("custom script"), - StandardOpenOption.CREATE); + Files.write(customScript.toPath(), Arrays.asList("custom script"), StandardOpenOption.CREATE); this.task.launchScript((configuration) -> configuration.setScript(customScript)); executeTask(); - assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())) - .startsWith("custom script".getBytes()); + assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())).startsWith("custom script".getBytes()); } @Test @@ -293,46 +267,38 @@ public abstract class AbstractBootArchiveTests { this.task.setMainClassName("com.example.Main"); this.task.launchScript((configuration) -> { configuration.getProperties().put("initInfoProvides", "provides"); - configuration.getProperties().put("initInfoShortDescription", - "short description"); + configuration.getProperties().put("initInfoShortDescription", "short description"); configuration.getProperties().put("initInfoDescription", "description"); }); executeTask(); byte[] bytes = Files.readAllBytes(this.task.getArchivePath().toPath()); assertThat(bytes).containsSequence("Provides: provides".getBytes()); - assertThat(bytes) - .containsSequence("Short-Description: short description".getBytes()); + assertThat(bytes).containsSequence("Short-Description: short description".getBytes()); assertThat(bytes).containsSequence("Description: description".getBytes()); } @Test public void customMainClassInTheManifestIsHonored() throws IOException { this.task.setMainClassName("com.example.Main"); - this.task.getManifest().getAttributes().put("Main-Class", - "com.example.CustomLauncher"); + this.task.getManifest().getAttributes().put("Main-Class", "com.example.CustomLauncher"); executeTask(); assertThat(this.task.getArchivePath()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")) .isEqualTo("com.example.CustomLauncher"); - assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.Main"); - assertThat(jarFile.getEntry( - "org/springframework/boot/loader/LaunchedURLClassLoader.class")) - .isNull(); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main"); + assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNull(); } } @Test public void customStartClassInTheManifestIsHonored() throws IOException { this.task.setMainClassName("com.example.Main"); - this.task.getManifest().getAttributes().put("Start-Class", - "com.example.CustomMain"); + this.task.getManifest().getAttributes().put("Start-Class", "com.example.CustomMain"); executeTask(); assertThat(this.task.getArchivePath()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")) - .isEqualTo(this.launcherClass); + assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.CustomMain"); } @@ -348,8 +314,7 @@ public abstract class AbstractBootArchiveTests { Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - assertThat(entry.getTime()) - .isEqualTo(BootZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES); + assertThat(entry.getTime()).isEqualTo(BootZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES); } } } @@ -357,8 +322,7 @@ public abstract class AbstractBootArchiveTests { @Test public void reproducibleOrderingCanBeEnabled() throws IOException { this.task.setMainClassName("com.example.Main"); - this.task.from(newFile("bravo.txt"), newFile("alpha.txt"), - newFile("charlie.txt")); + this.task.from(newFile("bravo.txt"), newFile("alpha.txt"), newFile("charlie.txt")); this.task.setReproducibleFileOrder(true); executeTask(); assertThat(this.task.getArchivePath()).exists(); @@ -382,8 +346,7 @@ public abstract class AbstractBootArchiveTests { executeTask(); assertThat(this.task.getArchivePath()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar")) - .isNull(); + assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar")).isNull(); } } @@ -395,8 +358,7 @@ public abstract class AbstractBootArchiveTests { executeTask(); assertThat(this.task.getArchivePath()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { - assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar")) - .isNotNull(); + assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar")).isNotNull(); } } @@ -422,23 +384,19 @@ public abstract class AbstractBootArchiveTests { } @Test - public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() - throws IOException { + public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException { this.task.setMainClassName("com.example.Main"); File classpathFolder = new File(this.temp, "classes"); - File applicationClass = new File(classpathFolder, - "com/example/Application.class"); + File applicationClass = new File(classpathFolder, "com/example/Application.class"); applicationClass.getParentFile().mkdirs(); applicationClass.createNewFile(); - this.task.classpath(classpathFolder, jarFile("first-library.jar"), - jarFile("second-library.jar"), jarFile("third-library.jar")); + this.task.classpath(classpathFolder, jarFile("first-library.jar"), jarFile("second-library.jar"), + jarFile("third-library.jar")); this.task.requiresUnpack("second-library.jar"); executeTask(); - assertThat(getEntryNames(this.task.getArchivePath())).containsSubsequence( - "org/springframework/boot/loader/", - this.classesPath + "com/example/Application.class", - this.libPath + "first-library.jar", this.libPath + "second-library.jar", - this.libPath + "third-library.jar"); + assertThat(getEntryNames(this.task.getArchivePath())).containsSubsequence("org/springframework/boot/loader/", + this.classesPath + "com/example/Application.class", this.libPath + "first-library.jar", + this.libPath + "second-library.jar", this.libPath + "third-library.jar"); } protected File jarFile(String name) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java index 56b5f2cdd6e..a32d1b9fb32 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java @@ -32,16 +32,14 @@ import static org.assertj.core.api.Assertions.assertThat; public class BootJarTests extends AbstractBootArchiveTests { public BootJarTests() { - super(BootJar.class, "org.springframework.boot.loader.JarLauncher", - "BOOT-INF/lib/", "BOOT-INF/classes/"); + super(BootJar.class, "org.springframework.boot.loader.JarLauncher", "BOOT-INF/lib/", "BOOT-INF/classes/"); } @Test public void contentCanBeAddedToBootInfUsingCopySpecFromGetter() throws IOException { BootJar bootJar = getTask(); bootJar.setMainClassName("com.example.Application"); - bootJar.getBootInf().into("test") - .from(new File("build.gradle").getAbsolutePath()); + bootJar.getBootInf().into("test").from(new File("build.gradle").getAbsolutePath()); bootJar.copy(); try (JarFile jarFile = new JarFile(bootJar.getArchivePath())) { assertThat(jarFile.getJarEntry("BOOT-INF/test/build.gradle")).isNotNull(); @@ -52,8 +50,7 @@ public class BootJarTests extends AbstractBootArchiveTests { public void contentCanBeAddedToBootInfUsingCopySpecAction() throws IOException { BootJar bootJar = getTask(); bootJar.setMainClassName("com.example.Application"); - bootJar.bootInf((copySpec) -> copySpec.into("test") - .from(new File("build.gradle").getAbsolutePath())); + bootJar.bootInf((copySpec) -> copySpec.into("test").from(new File("build.gradle").getAbsolutePath())); bootJar.copy(); try (JarFile jarFile = new JarFile(bootJar.getArchivePath())) { assertThat(jarFile.getJarEntry("BOOT-INF/test/build.gradle")).isNotNull(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java index aa9a6552133..ffc3cee76d5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java @@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class BootWarTests extends AbstractBootArchiveTests { public BootWarTests() { - super(BootWar.class, "org.springframework.boot.loader.WarLauncher", - "WEB-INF/lib/", "WEB-INF/classes/"); + super(BootWar.class, "org.springframework.boot.loader.WarLauncher", "WEB-INF/lib/", "WEB-INF/classes/"); } @Test @@ -72,37 +71,30 @@ public class BootWarTests extends AbstractBootArchiveTests { } @Test - public void devtoolsJarIsExcludedByDefaultWhenItsOnTheProvidedClasspath() - throws IOException { + public void devtoolsJarIsExcludedByDefaultWhenItsOnTheProvidedClasspath() throws IOException { getTask().setMainClassName("com.example.Main"); getTask().providedClasspath(newFile("spring-boot-devtools-0.1.2.jar")); executeTask(); assertThat(getTask().getArchivePath()).exists(); try (JarFile jarFile = new JarFile(getTask().getArchivePath())) { - assertThat(jarFile - .getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar")) - .isNull(); + assertThat(jarFile.getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar")).isNull(); } } @Test - public void devtoolsJarCanBeIncludedWhenItsOnTheProvidedClasspath() - throws IOException { + public void devtoolsJarCanBeIncludedWhenItsOnTheProvidedClasspath() throws IOException { getTask().setMainClassName("com.example.Main"); getTask().providedClasspath(jarFile("spring-boot-devtools-0.1.2.jar")); getTask().setExcludeDevtools(false); executeTask(); assertThat(getTask().getArchivePath()).exists(); try (JarFile jarFile = new JarFile(getTask().getArchivePath())) { - assertThat(jarFile - .getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar")) - .isNotNull(); + assertThat(jarFile.getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar")).isNotNull(); } } @Test - public void webappResourcesInDirectoriesThatOverlapWithLoaderCanBePackaged() - throws IOException { + public void webappResourcesInDirectoriesThatOverlapWithLoaderCanBePackaged() throws IOException { File webappFolder = new File(this.temp, "src/main/webapp"); webappFolder.mkdirs(); File orgFolder = new File(webappFolder, "org"); @@ -124,8 +116,8 @@ public class BootWarTests extends AbstractBootArchiveTests { getTask().classpath(jarFile("library.jar")); getTask().providedClasspath(jarFile("provided-library.jar")); executeTask(); - assertThat(getEntryNames(getTask().getArchivePath())).containsSubsequence( - "WEB-INF/lib/library.jar", "WEB-INF/lib-provided/provided-library.jar"); + assertThat(getEntryNames(getTask().getArchivePath())).containsSubsequence("WEB-INF/lib/library.jar", + "WEB-INF/lib-provided/provided-library.jar"); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfigurationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfigurationTests.java index 624955272e9..c856a8eb07c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfigurationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfigurationTests.java @@ -44,50 +44,50 @@ public class LaunchScriptConfigurationTests { @Test public void initInfoProvidesUsesArchiveBaseNameByDefault() { given(this.task.getBaseName()).willReturn("base-name"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoProvides", "base-name"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoProvides", + "base-name"); } @Test public void initInfoShortDescriptionUsesDescriptionByDefault() { given(this.project.getDescription()).willReturn("Project description"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoShortDescription", "Project description"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoShortDescription", + "Project description"); } @Test public void initInfoShortDescriptionUsesArchiveBaseNameWhenDescriptionIsNull() { given(this.task.getBaseName()).willReturn("base-name"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoShortDescription", "base-name"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoShortDescription", + "base-name"); } @Test public void initInfoShortDescriptionUsesSingleLineVersionOfMultiLineProjectDescription() { given(this.project.getDescription()).willReturn("Project\ndescription"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoShortDescription", "Project description"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoShortDescription", + "Project description"); } @Test public void initInfoDescriptionUsesArchiveBaseNameWhenDescriptionIsNull() { given(this.task.getBaseName()).willReturn("base-name"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoDescription", "base-name"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoDescription", + "base-name"); } @Test public void initInfoDescriptionUsesProjectDescriptionByDefault() { given(this.project.getDescription()).willReturn("Project description"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoDescription", "Project description"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoDescription", + "Project description"); } @Test public void initInfoDescriptionUsesCorrectlyFormattedMultiLineProjectDescription() { given(this.project.getDescription()).willReturn("The\nproject\ndescription"); - assertThat(new LaunchScriptConfiguration(this.task).getProperties()) - .containsEntry("initInfoDescription", "The\n# project\n# description"); + assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoDescription", + "The\n# project\n# description"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java index 3bdfc5f905b..a2d6e344c97 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java @@ -43,23 +43,20 @@ public class MavenIntegrationTests { @TestTemplate public void bootJarCanBeUploaded() throws FileNotFoundException, IOException { BuildResult result = this.gradleBuild.build("uploadBootArchives"); - assertThat(result.task(":uploadBootArchives").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.task(":uploadBootArchives").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("jar")).isFile(); assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0") - .noPackaging().noDependencies()); + .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies()); } @TestTemplate public void bootWarCanBeUploaded() throws IOException { BuildResult result = this.gradleBuild.build("uploadBootArchives"); - assertThat(result.task(":uploadBootArchives").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.task(":uploadBootArchives").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("war")).isFile(); - assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0") - .packaging("war").noDependencies()); + assertThat(artifactWithSuffix("pom")) + .is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0").packaging("war").noDependencies()); } private File artifactWithSuffix(String suffix) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java index a1de469ffa5..0bfbe251304 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java @@ -47,8 +47,7 @@ public class MavenPublishingIntegrationTests { assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("jar")).isFile(); assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0") - .noPackaging().noDependencies()); + .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies()); } @TestTemplate @@ -56,9 +55,9 @@ public class MavenPublishingIntegrationTests { BuildResult result = this.gradleBuild.build("publish"); assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("war")).isFile(); - assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0") - .packaging("war").noDependencies()); + assertThat(artifactWithSuffix("pom")) + .is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0").packaging("war").noDependencies()); } private File artifactWithSuffix(String suffix) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java index 9e1c3830823..62f483e07be 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ class PomCondition extends Condition { } private PomCondition(Set expectedContents, Set notExpectedContents) { - super(new TextDescription("Pom file containing %s and not containing %s", - expectedContents, notExpectedContents)); + super(new TextDescription("Pom file containing %s and not containing %s", expectedContents, + notExpectedContents)); this.expectedContents = expectedContents; this.notExpectedContents = notExpectedContents; } @@ -73,8 +73,8 @@ class PomCondition extends Condition { @Override public Description description() { - return new TextDescription("Pom file containing %s and not containing %s", - this.expectedContents, this.notExpectedContents); + return new TextDescription("Pom file containing %s and not containing %s", this.expectedContents, + this.notExpectedContents); } PomCondition groupId(String groupId) { @@ -83,8 +83,7 @@ class PomCondition extends Condition { } PomCondition artifactId(String artifactId) { - this.expectedContents - .add(String.format("%s", artifactId)); + this.expectedContents.add(String.format("%s", artifactId)); return this; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java index f5ec26b8cbf..4ba86a6d8ec 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java @@ -46,12 +46,9 @@ public class BootRunIntegrationTests { new File(this.gradleBuild.getProjectDir(), "src/main/resources").mkdirs(); BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()) - .contains("1. " + canonicalPathOf("build/classes/java/main")); - assertThat(result.getOutput()) - .contains("2. " + canonicalPathOf("build/resources/main")); - assertThat(result.getOutput()) - .doesNotContain(canonicalPathOf("src/main/resources")); + assertThat(result.getOutput()).contains("1. " + canonicalPathOf("build/classes/java/main")); + assertThat(result.getOutput()).contains("2. " + canonicalPathOf("build/resources/main")); + assertThat(result.getOutput()).doesNotContain(canonicalPathOf("src/main/resources")); } @TestTemplate @@ -59,40 +56,31 @@ public class BootRunIntegrationTests { copyClasspathApplication(); BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()) - .contains("1. " + canonicalPathOf("src/main/resources")); - assertThat(result.getOutput()) - .contains("2. " + canonicalPathOf("build/classes/java/main")); - assertThat(result.getOutput()) - .doesNotContain(canonicalPathOf("build/resources/main")); + assertThat(result.getOutput()).contains("1. " + canonicalPathOf("src/main/resources")); + assertThat(result.getOutput()).contains("2. " + canonicalPathOf("build/classes/java/main")); + assertThat(result.getOutput()).doesNotContain(canonicalPathOf("build/resources/main")); } @TestTemplate public void springBootExtensionMainClassNameIsUsed() throws IOException { BuildResult result = this.gradleBuild.build("echoMainClassName"); - assertThat(result.task(":echoMainClassName").getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); - assertThat(result.getOutput()) - .contains("Main class name = com.example.CustomMainClass"); + assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(result.getOutput()).contains("Main class name = com.example.CustomMainClass"); } @TestTemplate public void applicationPluginMainClassNameIsUsed() throws IOException { BuildResult result = this.gradleBuild.build("echoMainClassName"); - assertThat(result.task(":echoMainClassName").getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); - assertThat(result.getOutput()) - .contains("Main class name = com.example.CustomMainClass"); + assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(result.getOutput()).contains("Main class name = com.example.CustomMainClass"); } @TestTemplate public void applicationPluginMainClassNameIsNotUsedWhenItIsNull() throws IOException { copyClasspathApplication(); BuildResult result = this.gradleBuild.build("echoMainClassName"); - assertThat(result.task(":echoMainClassName").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains( - "Main class name = com.example.classpath.BootRunClasspathApplication"); + assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.getOutput()).contains("Main class name = com.example.classpath.BootRunClasspathApplication"); } @TestTemplate @@ -100,8 +88,7 @@ public class BootRunIntegrationTests { copyJvmArgsApplication(); BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains("1. -Xverify:none") - .contains("2. -XX:TieredStopAtLevel=1"); + assertThat(result.getOutput()).contains("1. -Xverify:none").contains("2. -XX:TieredStopAtLevel=1"); } @TestTemplate @@ -109,8 +96,7 @@ public class BootRunIntegrationTests { copyJvmArgsApplication(); BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).doesNotContain("-Xverify:none") - .doesNotContain("-XX:TieredStopAtLevel=1"); + assertThat(result.getOutput()).doesNotContain("-Xverify:none").doesNotContain("-XX:TieredStopAtLevel=1"); } @TestTemplate @@ -118,9 +104,8 @@ public class BootRunIntegrationTests { copyJvmArgsApplication(); BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains("1. -Dcom.bar=baz") - .contains("2. -Dcom.foo=bar").contains("3. -Xverify:none") - .contains("4. -XX:TieredStopAtLevel=1"); + assertThat(result.getOutput()).contains("1. -Dcom.bar=baz").contains("2. -Dcom.foo=bar") + .contains("3. -Xverify:none").contains("4. -XX:TieredStopAtLevel=1"); } private void copyClasspathApplication() throws IOException { @@ -132,11 +117,9 @@ public class BootRunIntegrationTests { } private void copyApplication(String name) throws IOException { - File output = new File(this.gradleBuild.getProjectDir(), - "src/main/java/com/example/" + name); + File output = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example/" + name); output.mkdirs(); - FileSystemUtils.copyRecursively(new File("src/test/java/com/example/" + name), - output); + FileSystemUtils.copyRecursively(new File("src/test/java/com/example/" + name), output); } private String canonicalPathOf(String path) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java index 327bf76901a..8f59c7090b8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java @@ -80,15 +80,11 @@ public class GradleBuild { } private List pluginClasspath() { - return Arrays.asList(new File("bin"), new File("build/classes/java/main"), - new File("build/resources/main"), - new File(pathOfJarContaining(LaunchScript.class)), - new File(pathOfJarContaining(ClassVisitor.class)), + return Arrays.asList(new File("bin"), new File("build/classes/java/main"), new File("build/resources/main"), + new File(pathOfJarContaining(LaunchScript.class)), new File(pathOfJarContaining(ClassVisitor.class)), new File(pathOfJarContaining(DependencyManagementPlugin.class)), - new File(pathOfJarContaining(PropertiesKt.class)), - new File(pathOfJarContaining(KotlinLogger.class)), - new File(pathOfJarContaining(KotlinPlugin.class)), - new File(pathOfJarContaining(KotlinProject.class)), + new File(pathOfJarContaining(PropertiesKt.class)), new File(pathOfJarContaining(KotlinLogger.class)), + new File(pathOfJarContaining(KotlinPlugin.class)), new File(pathOfJarContaining(KotlinProject.class)), new File(pathOfJarContaining(KotlinGradleSubplugin.class)), new File(pathOfJarContaining(ArchiveEntry.class))); } @@ -98,8 +94,7 @@ public class GradleBuild { } public GradleBuild script(String script) { - this.script = script.endsWith(this.dsl.getExtension()) ? script - : script + this.dsl.getExtension(); + this.script = script.endsWith(this.dsl.getExtension()) ? script : script + this.dsl.getExtension(); return this; } @@ -124,10 +119,8 @@ public class GradleBuild { public GradleRunner prepareRunner(String... arguments) throws IOException { String scriptContent = FileCopyUtils.copyToString(new FileReader(this.script)) .replace("{version}", getBootVersion()) - .replace("{dependency-management-plugin-version}", - getDependencyManagementPluginVersion()); - FileCopyUtils.copy(scriptContent, new FileWriter( - new File(this.projectDir, "build" + this.dsl.getExtension()))); + .replace("{dependency-management-plugin-version}", getDependencyManagementPluginVersion()); + FileCopyUtils.copy(scriptContent, new FileWriter(new File(this.projectDir, "build" + this.dsl.getExtension()))); FileSystemUtils.copyRecursively(new File("src/test/resources/repository"), new File(this.projectDir, "repository")); GradleRunner gradleRunner = GradleRunner.create().withProjectDir(this.projectDir) @@ -172,16 +165,13 @@ public class GradleBuild { private static String getDependencyManagementPluginVersion() { try { - URL location = DependencyManagementExtension.class.getProtectionDomain() - .getCodeSource().getLocation(); + URL location = DependencyManagementExtension.class.getProtectionDomain().getCodeSource().getLocation(); try (JarFile jar = new JarFile(new File(location.toURI()))) { - return jar.getManifest().getMainAttributes() - .getValue("Implementation-Version"); + return jar.getManifest().getMainAttributes().getValue("Implementation-Version"); } } catch (Exception ex) { - throw new IllegalStateException( - "Failed to find dependency management plugin version", ex); + throw new IllegalStateException("Failed to find dependency management plugin version", ex); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuildExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuildExtension.java index 67e65cda8fa..2541121a416 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuildExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuildExtension.java @@ -34,8 +34,7 @@ import org.springframework.util.ReflectionUtils; */ public class GradleBuildExtension implements BeforeEachCallback, AfterEachCallback { - private static final Pattern GRADLE_VERSION_PATTERN = Pattern - .compile("\\[Gradle .+\\]"); + private static final Pattern GRADLE_VERSION_PATTERN = Pattern.compile("\\[Gradle .+\\]"); private Dsl dsl = Dsl.GROOVY; @@ -51,8 +50,7 @@ public class GradleBuildExtension implements BeforeEachCallback, AfterEachCallba private GradleBuild extractGradleBuild(ExtensionContext context) throws Exception { Object testInstance = context.getRequiredTestInstance(); - Field gradleBuildField = ReflectionUtils.findField(testInstance.getClass(), - "gradleBuild"); + Field gradleBuildField = ReflectionUtils.findField(testInstance.getClass(), "gradleBuild"); gradleBuildField.setAccessible(true); GradleBuild gradleBuild = (GradleBuild) gradleBuildField.get(testInstance); return gradleBuild; @@ -68,8 +66,7 @@ public class GradleBuildExtension implements BeforeEachCallback, AfterEachCallba private URL getScriptForTestMethod(ExtensionContext context) { Class testClass = context.getRequiredTestClass(); - String name = testClass.getSimpleName() + "-" - + removeGradleVersion(context.getRequiredTestMethod().getName()) + String name = testClass.getSimpleName() + "-" + removeGradleVersion(context.getRequiredTestMethod().getName()) + this.dsl.getExtension(); return testClass.getResource(name); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java index e0435c95477..e3bb5ad3538 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java @@ -60,12 +60,11 @@ public final class BuildPropertiesWriter { } File parent = file.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { - throw new IllegalStateException("Cannot create parent directory for '" - + this.outputFile.getAbsolutePath() + "'"); + throw new IllegalStateException( + "Cannot create parent directory for '" + this.outputFile.getAbsolutePath() + "'"); } if (!file.createNewFile()) { - throw new IllegalStateException("Cannot create target file '" - + this.outputFile.getAbsolutePath() + "'"); + throw new IllegalStateException("Cannot create target file '" + this.outputFile.getAbsolutePath() + "'"); } } @@ -76,12 +75,10 @@ public final class BuildPropertiesWriter { properties.put("build.name", project.getName()); properties.put("build.version", project.getVersion()); if (project.getTime() != null) { - properties.put("build.time", - DateTimeFormatter.ISO_INSTANT.format(project.getTime())); + properties.put("build.time", DateTimeFormatter.ISO_INSTANT.format(project.getTime())); } if (project.getAdditionalProperties() != null) { - project.getAdditionalProperties() - .forEach((name, value) -> properties.put("build." + name, value)); + project.getAdditionalProperties().forEach((name, value) -> properties.put("build." + name, value)); } return properties; } @@ -103,8 +100,8 @@ public final class BuildPropertiesWriter { private final Map additionalProperties; - public ProjectDetails(String group, String artifact, String version, String name, - Instant time, Map additionalProperties) { + public ProjectDetails(String group, String artifact, String version, String name, Instant time, + Map additionalProperties) { this.group = group; this.artifact = artifact; this.name = name; @@ -114,8 +111,7 @@ public final class BuildPropertiesWriter { this.additionalProperties = additionalProperties; } - private static void validateAdditionalProperties( - Map additionalProperties) { + private static void validateAdditionalProperties(Map additionalProperties) { if (additionalProperties != null) { additionalProperties.forEach((name, value) -> { if (value == null) { @@ -154,8 +150,7 @@ public final class BuildPropertiesWriter { /** * Exception thrown when an additional property with a null value is encountered. */ - public static class NullAdditionalPropertyValueException - extends IllegalArgumentException { + public static class NullAdditionalPropertyValueException extends IllegalArgumentException { public NullAdditionalPropertyValueException(String name) { super("Additional property '" + name + "' is illegal as its value is null"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java index f8015d5fdd6..d135d64d038 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class DefaultLaunchScript implements LaunchScript { private static final int BUFFER_SIZE = 4096; - private static final Pattern PLACEHOLDER_PATTERN = Pattern - .compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})"); + private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})"); private static final Set FILE_PATH_KEYS = Collections .unmodifiableSet(Collections.singleton("inlinedConfScript")); @@ -79,8 +78,7 @@ public class DefaultLaunchScript implements LaunchScript { } } - private void copy(InputStream inputStream, OutputStream outputStream) - throws IOException { + private void copy(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { @@ -89,8 +87,7 @@ public class DefaultLaunchScript implements LaunchScript { outputStream.flush(); } - private String expandPlaceholders(String content, Map properties) - throws IOException { + private String expandPlaceholders(String content, Map properties) throws IOException { StringBuffer expanded = new StringBuffer(); Matcher matcher = PLACEHOLDER_PATTERN.matcher(content); while (matcher.find()) { @@ -107,8 +104,7 @@ public class DefaultLaunchScript implements LaunchScript { } } else { - value = (defaultValue != null) ? defaultValue.substring(1) - : matcher.group(0); + value = (defaultValue != null) ? defaultValue.substring(1) : matcher.group(0); } matcher.appendReplacement(expanded, value.replace("$", "\\$")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java index 0ee2d16e307..e9fbe817195 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ public abstract class FileUtils { * @param outputDirectory the output directory * @param originDirectory the origin directory */ - public static void removeDuplicatesFromOutputDirectory(File outputDirectory, - File originDirectory) { + public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) { if (originDirectory.isDirectory()) { for (String name : originDirectory.list()) { File targetFile = new File(outputDirectory, name); @@ -48,8 +47,7 @@ public abstract class FileUtils { targetFile.delete(); } else { - FileUtils.removeDuplicatesFromOutputDirectory(targetFile, - new File(originDirectory, name)); + FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name)); } } } @@ -64,8 +62,8 @@ public abstract class FileUtils { */ public static String sha1Hash(File file) throws IOException { try { - try (DigestInputStream inputStream = new DigestInputStream( - new FileInputStream(file), MessageDigest.getInstance("SHA-1"))) { + try (DigestInputStream inputStream = new DigestInputStream(new FileInputStream(file), + MessageDigest.getInstance("SHA-1"))) { byte[] buffer = new byte[4098]; while (inputStream.read(buffer) != -1) { // Read the entire stream diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java index e9cea026941..32da883a3cb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,8 +82,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { * @throws IOException if the file cannot be opened * @throws FileNotFoundException if the file cannot be found */ - public JarWriter(File file, LaunchScript launchScript) - throws FileNotFoundException, IOException { + public JarWriter(File file, LaunchScript launchScript) throws FileNotFoundException, IOException { FileOutputStream fileOutputStream = new FileOutputStream(file); if (launchScript != null) { fileOutputStream.write(launchScript.toByteArray()); @@ -96,8 +95,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { private void setExecutableFilePermission(File file) { try { Path path = file.toPath(); - Set permissions = new HashSet<>( - Files.getPosixFilePermissions(path)); + Set permissions = new HashSet<>(Files.getPosixFilePermissions(path)); permissions.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(path, permissions); } @@ -129,14 +127,13 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { this.writeEntries(jarFile, new IdentityEntryTransformer(), unpackHandler); } - void writeEntries(JarFile jarFile, EntryTransformer entryTransformer, - UnpackHandler unpackHandler) throws IOException { + void writeEntries(JarFile jarFile, EntryTransformer entryTransformer, UnpackHandler unpackHandler) + throws IOException { Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarArchiveEntry entry = new JarArchiveEntry(entries.nextElement()); setUpEntry(jarFile, entry); - try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( - jarFile.getInputStream(entry))) { + try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry))) { EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true); JarArchiveEntry transformedEntry = entryTransformer.transform(entry); if (transformedEntry != null) { @@ -147,8 +144,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { } private void setUpEntry(JarFile jarFile, JarArchiveEntry entry) throws IOException { - try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( - jarFile.getInputStream(entry))) { + try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry))) { if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) { new CrcAndSize(inputStream).setupStoredEntry(entry); } @@ -176,8 +172,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { * @param library the library * @throws IOException if the write fails */ - public void writeNestedLibrary(String destination, Library library) - throws IOException { + public void writeNestedLibrary(String destination, Library library) throws IOException { File file = library.getFile(); JarArchiveEntry entry = new JarArchiveEntry(destination + library.getName()); entry.setTime(getNestedLibraryTime(file)); @@ -222,13 +217,11 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { @Override public void writeLoaderClasses(String loaderJarResourceName) throws IOException { URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName); - try (JarInputStream inputStream = new JarInputStream( - new BufferedInputStream(loaderJar.openStream()))) { + try (JarInputStream inputStream = new JarInputStream(new BufferedInputStream(loaderJar.openStream()))) { JarEntry entry; while ((entry = inputStream.getNextJarEntry()) != null) { if (entry.getName().endsWith(".class")) { - writeEntry(new JarArchiveEntry(entry), - new InputStreamEntryWriter(inputStream, false)); + writeEntry(new JarArchiveEntry(entry), new InputStreamEntryWriter(inputStream, false)); } } } @@ -243,8 +236,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { this.jarOutput.close(); } - private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter) - throws IOException { + private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter) throws IOException { writeEntry(entry, entryWriter, NEVER_UNPACK); } @@ -256,8 +248,8 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { * @param unpackHandler handles possible unpacking for the entry * @throws IOException in case of I/O errors */ - private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter, - UnpackHandler unpackHandler) throws IOException { + private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter, UnpackHandler unpackHandler) + throws IOException { String parent = entry.getName(); if (parent.endsWith("/")) { parent = parent.substring(0, parent.length() - 1); @@ -283,16 +275,15 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { } } - private EntryWriter addUnpackCommentIfNecessary(JarArchiveEntry entry, - EntryWriter entryWriter, UnpackHandler unpackHandler) throws IOException { + private EntryWriter addUnpackCommentIfNecessary(JarArchiveEntry entry, EntryWriter entryWriter, + UnpackHandler unpackHandler) throws IOException { if (entryWriter == null || !unpackHandler.requiresUnpack(entry.getName())) { return entryWriter; } ByteArrayOutputStream output = new ByteArrayOutputStream(); entryWriter.write(output); entry.setComment("UNPACK:" + unpackHandler.sha1Hash(entry.getName())); - return new InputStreamEntryWriter(new ByteArrayInputStream(output.toByteArray()), - true); + return new InputStreamEntryWriter(new ByteArrayInputStream(output.toByteArray()), true); } /** @@ -357,8 +348,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { super(in); this.header = new byte[4]; this.headerLength = in.read(this.header); - this.headerStream = new ByteArrayInputStream(this.header, 0, - this.headerLength); + this.headerStream = new ByteArrayInputStream(this.header, 0, this.headerLength); } @Override @@ -381,8 +371,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { @Override public int read(byte[] b, int off, int len) throws IOException { - int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) - : -1; + int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) : -1; if (read <= 0) { return readRemainder(b, off, len); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java index 9ea9bd3c852..966ac446cca 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class JavaExecutable { public JavaExecutable() { String javaHome = System.getProperty("java.home"); - Assert.state(StringUtils.hasLength(javaHome), - "Unable to find java executable due to missing 'java.home'"); + Assert.state(StringUtils.hasLength(javaHome), "Unable to find java executable due to missing 'java.home'"); this.file = findInJavaHome(javaHome); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java index 822baf6fffe..abce278ba6d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,7 @@ public abstract class MainClassFinder { private static final Type STRING_ARRAY_TYPE = Type.getType(String[].class); - private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE, - STRING_ARRAY_TYPE); + private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE, STRING_ARRAY_TYPE); private static final String MAIN_METHOD_NAME = "main"; @@ -104,8 +103,7 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the folder cannot be read */ - public static String findSingleMainClass(File rootFolder, String annotationName) - throws IOException { + public static String findSingleMainClass(File rootFolder, String annotationName) throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(rootFolder, callback); return callback.getMainClassName(); @@ -120,14 +118,12 @@ public abstract class MainClassFinder { * @return the first callback result or {@code null} * @throws IOException in case of I/O errors */ - static T doWithMainClasses(File rootFolder, MainClassCallback callback) - throws IOException { + static T doWithMainClasses(File rootFolder, MainClassCallback callback) throws IOException { if (!rootFolder.exists()) { return null; // nothing to do } if (!rootFolder.isDirectory()) { - throw new IllegalArgumentException( - "Invalid root folder '" + rootFolder + "'"); + throw new IllegalArgumentException("Invalid root folder '" + rootFolder + "'"); } String prefix = rootFolder.getAbsolutePath() + "/"; Deque stack = new ArrayDeque<>(); @@ -138,10 +134,8 @@ public abstract class MainClassFinder { try (InputStream inputStream = new FileInputStream(file)) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { - String className = convertToClassName(file.getAbsolutePath(), - prefix); - T result = callback.doWith(new MainClass(className, - classDescriptor.getAnnotationNames())); + String className = convertToClassName(file.getAbsolutePath(), prefix); + T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } @@ -170,8 +164,7 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ - public static String findMainClass(JarFile jarFile, String classesLocation) - throws IOException { + public static String findMainClass(JarFile jarFile, String classesLocation) throws IOException { return doWithMainClasses(jarFile, classesLocation, MainClass::getName); } @@ -182,8 +175,7 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ - public static String findSingleMainClass(JarFile jarFile, String classesLocation) - throws IOException { + public static String findSingleMainClass(JarFile jarFile, String classesLocation) throws IOException { return findSingleMainClass(jarFile, classesLocation, null); } @@ -198,8 +190,8 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ - public static String findSingleMainClass(JarFile jarFile, String classesLocation, - String annotationName) throws IOException { + public static String findSingleMainClass(JarFile jarFile, String classesLocation, String annotationName) + throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(jarFile, classesLocation, callback); return callback.getMainClassName(); @@ -214,19 +206,16 @@ public abstract class MainClassFinder { * @return the first callback result or {@code null} * @throws IOException in case of I/O errors */ - static T doWithMainClasses(JarFile jarFile, String classesLocation, - MainClassCallback callback) throws IOException { + static T doWithMainClasses(JarFile jarFile, String classesLocation, MainClassCallback callback) + throws IOException { List classEntries = getClassEntries(jarFile, classesLocation); classEntries.sort(new ClassEntryComparator()); for (JarEntry entry : classEntries) { - try (InputStream inputStream = new BufferedInputStream( - jarFile.getInputStream(entry))) { + try (InputStream inputStream = new BufferedInputStream(jarFile.getInputStream(entry))) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { - String className = convertToClassName(entry.getName(), - classesLocation); - T result = callback.doWith(new MainClass(className, - classDescriptor.getAnnotationNames())); + String className = convertToClassName(entry.getName(), classesLocation); + T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } @@ -246,15 +235,13 @@ public abstract class MainClassFinder { return name; } - private static List getClassEntries(JarFile source, - String classesLocation) { + private static List getClassEntries(JarFile source, String classesLocation) { classesLocation = (classesLocation != null) ? classesLocation : ""; Enumeration sourceEntries = source.entries(); List classEntries = new ArrayList<>(); while (sourceEntries.hasMoreElements()) { JarEntry entry = sourceEntries.nextElement(); - if (entry.getName().startsWith(classesLocation) - && entry.getName().endsWith(DOT_CLASS)) { + if (entry.getName().startsWith(classesLocation) && entry.getName().endsWith(DOT_CLASS)) { classEntries.add(entry); } } @@ -309,10 +296,8 @@ public abstract class MainClassFinder { } @Override - public MethodVisitor visitMethod(int access, String name, String desc, - String signature, String[] exceptions) { - if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC) - && MAIN_METHOD_NAME.equals(name) + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC) && MAIN_METHOD_NAME.equals(name) && MAIN_METHOD_TYPE.getDescriptor().equals(desc)) { this.mainMethodFound = true; } @@ -372,8 +357,7 @@ public abstract class MainClassFinder { */ MainClass(String name, Set annotationNames) { this.name = name; - this.annotationNames = Collections - .unmodifiableSet(new HashSet<>(annotationNames)); + this.annotationNames = Collections.unmodifiableSet(new HashSet<>(annotationNames)); } String getName() { @@ -418,8 +402,7 @@ public abstract class MainClassFinder { * Find a single main class, throwing an {@link IllegalStateException} if multiple * candidates exist. */ - private static final class SingleMainClassCallback - implements MainClassCallback { + private static final class SingleMainClassCallback implements MainClassCallback { private final Set mainClasses = new LinkedHashSet<>(); @@ -449,11 +432,9 @@ public abstract class MainClassFinder { } if (matchingMainClasses.size() > 1) { throw new IllegalStateException( - "Unable to find a single main class from the following candidates " - + matchingMainClasses); + "Unable to find a single main class from the following candidates " + matchingMainClasses); } - return (matchingMainClasses.isEmpty() ? null - : matchingMainClasses.iterator().next().getName()); + return (matchingMainClasses.isEmpty() ? null : matchingMainClasses.iterator().next().getName()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java index 90379212d45..41ca179a9ad 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java @@ -84,8 +84,8 @@ public class Repackager { throw new IllegalArgumentException("Source file must be provided"); } if (!source.exists() || !source.isFile()) { - throw new IllegalArgumentException("Source must refer to an existing file, " - + "got " + source.getAbsolutePath()); + throw new IllegalArgumentException( + "Source must refer to an existing file, " + "got " + source.getAbsolutePath()); } this.source = source.getAbsoluteFile(); this.layoutFactory = layoutFactory; @@ -96,8 +96,7 @@ public class Repackager { * main class takes too long. * @param listener the listener to add */ - public void addMainClassTimeoutWarningListener( - MainClassTimeoutWarningListener listener) { + public void addMainClassTimeoutWarningListener(MainClassTimeoutWarningListener listener) { this.mainClassTimeoutListeners.add(listener); } @@ -168,8 +167,7 @@ public class Repackager { * @throws IOException if the file cannot be repackaged * @since 1.3.0 */ - public void repackage(File destination, Libraries libraries, - LaunchScript launchScript) throws IOException { + public void repackage(File destination, Libraries libraries, LaunchScript launchScript) throws IOException { if (destination == null || destination.isDirectory()) { throw new IllegalArgumentException("Invalid destination"); } @@ -206,8 +204,7 @@ public class Repackager { if (this.layoutFactory != null) { return this.layoutFactory; } - List factories = SpringFactoriesLoader - .loadFactories(LayoutFactory.class, null); + List factories = SpringFactoriesLoader.loadFactories(LayoutFactory.class, null); if (factories.isEmpty()) { return new DefaultLayoutFactory(); } @@ -226,20 +223,19 @@ public class Repackager { private boolean alreadyRepackaged() throws IOException { try (JarFile jarFile = new JarFile(this.source)) { Manifest manifest = jarFile.getManifest(); - return (manifest != null && manifest.getMainAttributes() - .getValue(BOOT_VERSION_ATTRIBUTE) != null); + return (manifest != null && manifest.getMainAttributes().getValue(BOOT_VERSION_ATTRIBUTE) != null); } } - private void repackage(JarFile sourceJar, File destination, Libraries libraries, - LaunchScript launchScript) throws IOException { + private void repackage(JarFile sourceJar, File destination, Libraries libraries, LaunchScript launchScript) + throws IOException { WritableLibraries writeableLibraries = new WritableLibraries(libraries); try (JarWriter writer = new JarWriter(destination, launchScript)) { writer.writeManifest(buildManifest(sourceJar)); writeLoaderClasses(writer); if (this.layout instanceof RepackagingLayout) { - writer.writeEntries(sourceJar, new RenamingEntryTransformer( - ((RepackagingLayout) this.layout).getRepackagedClassesLocation()), + writer.writeEntries(sourceJar, + new RenamingEntryTransformer(((RepackagingLayout) this.layout).getRepackagedClassesLocation()), writeableLibraries); } else { @@ -294,8 +290,7 @@ public class Repackager { } String launcherClassName = this.layout.getLauncherClassName(); if (launcherClassName != null) { - manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, - launcherClassName); + manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, launcherClassName); if (startClass == null) { throw new IllegalStateException("Unable to find main class"); } @@ -306,10 +301,8 @@ public class Repackager { } String bootVersion = getClass().getPackage().getImplementationVersion(); manifest.getMainAttributes().putValue(BOOT_VERSION_ATTRIBUTE, bootVersion); - manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, - (this.layout instanceof RepackagingLayout) - ? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() - : this.layout.getClassesLocation()); + manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, (this.layout instanceof RepackagingLayout) + ? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() : this.layout.getClassesLocation()); String lib = this.layout.getLibraryDestination("", LibraryScope.COMPILE); if (StringUtils.hasLength(lib)) { manifest.getMainAttributes().putValue(BOOT_LIB_ATTRIBUTE, lib); @@ -330,14 +323,13 @@ public class Repackager { } protected String findMainMethod(JarFile source) throws IOException { - return MainClassFinder.findSingleMainClass(source, - this.layout.getClassesLocation(), SPRING_BOOT_APPLICATION_CLASS_NAME); + return MainClassFinder.findSingleMainClass(source, this.layout.getClassesLocation(), + SPRING_BOOT_APPLICATION_CLASS_NAME); } private void renameFile(File file, File dest) { if (!file.renameTo(dest)) { - throw new IllegalStateException( - "Unable to rename '" + file + "' to '" + dest + "'"); + throw new IllegalStateException("Unable to rename '" + file + "' to '" + dest + "'"); } } @@ -379,15 +371,12 @@ public class Repackager { if (entry.getName().equals("META-INF/INDEX.LIST")) { return null; } - if ((entry.getName().startsWith("META-INF/") - && !entry.getName().equals("META-INF/aop.xml") - && !entry.getName().endsWith(".kotlin_module")) - || entry.getName().startsWith("BOOT-INF/") + if ((entry.getName().startsWith("META-INF/") && !entry.getName().equals("META-INF/aop.xml") + && !entry.getName().endsWith(".kotlin_module")) || entry.getName().startsWith("BOOT-INF/") || entry.getName().equals("module-info.class")) { return entry; } - JarArchiveEntry renamedEntry = new JarArchiveEntry( - this.namePrefix + entry.getName()); + JarArchiveEntry renamedEntry = new JarArchiveEntry(this.namePrefix + entry.getName()); renamedEntry.setTime(entry.getTime()); renamedEntry.setSize(entry.getSize()); renamedEntry.setMethod(entry.getMethod()); @@ -424,14 +413,13 @@ public class Repackager { private WritableLibraries(Libraries libraries) throws IOException { libraries.doWithLibraries((library) -> { if (isZip(library.getFile())) { - String libraryDestination = Repackager.this.layout - .getLibraryDestination(library.getName(), library.getScope()); + String libraryDestination = Repackager.this.layout.getLibraryDestination(library.getName(), + library.getScope()); if (libraryDestination != null) { - Library existing = this.libraryEntryNames.putIfAbsent( - libraryDestination + library.getName(), library); + Library existing = this.libraryEntryNames.putIfAbsent(libraryDestination + library.getName(), + library); if (existing != null) { - throw new IllegalStateException( - "Duplicate library " + library.getName()); + throw new IllegalStateException("Duplicate library " + library.getName()); } } } @@ -448,16 +436,14 @@ public class Repackager { public String sha1Hash(String name) throws IOException { Library library = this.libraryEntryNames.get(name); if (library == null) { - throw new IllegalArgumentException( - "No library found for entry name '" + name + "'"); + throw new IllegalArgumentException("No library found for entry name '" + name + "'"); } return FileUtils.sha1Hash(library.getFile()); } private void write(JarWriter writer) throws IOException { for (Entry entry : this.libraryEntryNames.entrySet()) { - writer.writeNestedLibrary( - entry.getKey().substring(0, entry.getKey().lastIndexOf('/') + 1), + writer.writeNestedLibrary(entry.getKey().substring(0, entry.getKey().lastIndexOf('/') + 1), entry.getValue()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java index 0d82bb8dcac..c4438a06f89 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,8 @@ public class RunProcess { return run(waitForProcess, Arrays.asList(args), Collections.emptyMap()); } - public int run(boolean waitForProcess, Collection args, - Map environmentVariables) throws IOException { + public int run(boolean waitForProcess, Collection args, Map environmentVariables) + throws IOException { ProcessBuilder builder = new ProcessBuilder(this.command); builder.directory(this.workingDirectory); builder.command().addAll(args); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java index 22b98b7ae22..94b7898bff6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -170,8 +170,7 @@ public class DefaultLaunchScriptTests { public void expandVariables() throws Exception { File file = this.temporaryFolder.newFile(); FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file); - DefaultLaunchScript script = new DefaultLaunchScript(file, - createProperties("a:e", "b:o")); + DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); assertThat(content).isEqualTo("hello"); } @@ -180,8 +179,7 @@ public class DefaultLaunchScriptTests { public void expandVariablesMultiLine() throws Exception { File file = this.temporaryFolder.newFile(); FileCopyUtils.copy("h{{a}}l\nl{{b}}".getBytes(), file); - DefaultLaunchScript script = new DefaultLaunchScript(file, - createProperties("a:e", "b:o")); + DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); assertThat(content).isEqualTo("hel\nlo"); } @@ -208,8 +206,7 @@ public class DefaultLaunchScriptTests { public void expandVariablesWithDefaultsOverride() throws Exception { File file = this.temporaryFolder.newFile(); FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file); - DefaultLaunchScript script = new DefaultLaunchScript(file, - createProperties("a:a")); + DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a")); String content = new String(script.toByteArray()); assertThat(content).isEqualTo("hallo"); } @@ -224,8 +221,7 @@ public class DefaultLaunchScriptTests { } private void assertThatPlaceholderCanBeReplaced(String placeholder) throws Exception { - DefaultLaunchScript script = new DefaultLaunchScript(null, - createProperties(placeholder + ":__test__")); + DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties(placeholder + ":__test__")); String content = new String(script.toByteArray()); assertThat(content).contains("__test__"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java index 6308d71c6c2..abc3858f628 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "logback.xml"); file.createNewFile(); new File(this.originDirectory, "logback.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isFalse(); } @@ -72,8 +71,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "sub/logback.xml"); file.createNewFile(); new File(this.originDirectory, "sub/logback.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isFalse(); } @@ -84,8 +82,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "sub/logback.xml"); file.createNewFile(); new File(this.originDirectory, "sub/different.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isTrue(); } @@ -94,8 +91,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "logback.xml"); file.createNewFile(); new File(this.originDirectory, "different.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isTrue(); } @@ -105,8 +101,7 @@ public class FileUtilsTests { try (OutputStream outputStream = new FileOutputStream(file)) { outputStream.write(new byte[] { 1, 2, 3 }); } - assertThat(FileUtils.sha1Hash(file)) - .isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); + assertThat(FileUtils.sha1Hash(file)).isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 8569bc680ca..46f39050281 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class LayoutsTests { assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class); assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class); assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class); - assertThat(Layouts.forFile(new File("te.st.jar"))) - .isInstanceOf(Layouts.Jar.class); + assertThat(Layouts.forFile(new File("te.st.jar"))).isInstanceOf(Layouts.Jar.class); } @Test @@ -45,41 +44,31 @@ public class LayoutsTests { assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class); assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class); assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class); - assertThat(Layouts.forFile(new File("te.st.war"))) - .isInstanceOf(Layouts.War.class); + assertThat(Layouts.forFile(new File("te.st.war"))).isInstanceOf(Layouts.War.class); } @Test public void unknownFile() { - assertThatIllegalStateException() - .isThrownBy(() -> Layouts.forFile(new File("test.txt"))) + assertThatIllegalStateException().isThrownBy(() -> Layouts.forFile(new File("test.txt"))) .withMessageContaining("Unable to deduce layout for 'test.txt'"); } @Test public void jarLayout() { Layout layout = new Layouts.Jar(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) - .isEqualTo("BOOT-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) - .isEqualTo("BOOT-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) - .isEqualTo("BOOT-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) - .isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("BOOT-INF/lib/"); } @Test public void warLayout() { Layout layout = new Layouts.War(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) - .isEqualTo("WEB-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) - .isEqualTo("WEB-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) - .isEqualTo("WEB-INF/lib-provided/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) - .isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isEqualTo("WEB-INF/lib-provided/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("WEB-INF/lib/"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index e48c2446131..1b7682c985c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,18 +81,16 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); assertThatIllegalStateException() - .isThrownBy(() -> MainClassFinder - .findSingleMainClass(this.testJarFile.getJarFile(), "")) - .withMessageContaining("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); + .isThrownBy(() -> MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "")) + .withMessageContaining( + "Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]"); } @Test public void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class); - String mainClass = MainClassFinder.findSingleMainClass( - this.testJarFile.getJarFile(), "", + String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "", "org.springframework.boot.loader.tools.sample.SomeApplication"); assertThat(mainClass).isEqualTo("a.b.c.E"); } @@ -101,8 +99,7 @@ public class MainClassFinderTests { public void findMainClassInJarSubLocation() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); - String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), - "a/"); + String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "a/"); assertThat(actual).isEqualTo("B"); } @@ -137,18 +134,16 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); assertThatIllegalStateException() - .isThrownBy(() -> MainClassFinder - .findSingleMainClass(this.testJarFile.getJarSource())) - .withMessageContaining("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); + .isThrownBy(() -> MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource())) + .withMessageContaining( + "Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]"); } @Test public void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class); - String mainClass = MainClassFinder.findSingleMainClass( - this.testJarFile.getJarSource(), + String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource(), "org.springframework.boot.loader.tools.sample.SomeApplication"); assertThat(mainClass).isEqualTo("a.b.c.E"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index f38286f7f69..6604db55711 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -96,14 +96,12 @@ public class RepackagerTests { @Test public void missingSource() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Repackager(new File("missing"))); + assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(new File("missing"))); } @Test public void directorySource() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Repackager(this.temporaryFolder.getRoot())); + assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.temporaryFolder.getRoot())); } @Test @@ -116,8 +114,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -134,8 +131,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -148,8 +144,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -163,8 +158,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -174,17 +168,15 @@ public class RepackagerTests { this.testJarFile.addClass("a/b/D.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - assertThatIllegalStateException() - .isThrownBy(() -> repackager.repackage(NO_LIBRARIES)) - .withMessageContaining("Unable to find a single main class " - + "from the following candidates [a.b.C, a.b.D]"); + assertThatIllegalStateException().isThrownBy(() -> repackager.repackage(NO_LIBRARIES)).withMessageContaining( + "Unable to find a single main class " + "from the following candidates [a.b.C, a.b.D]"); } @Test public void noMainClass() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); - assertThatIllegalStateException().isThrownBy( - () -> new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES)) + assertThatIllegalStateException() + .isThrownBy(() -> new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES)) .withMessageContaining("Unable to find main class"); } @@ -196,8 +188,7 @@ public class RepackagerTests { repackager.setLayout(new Layouts.None()); repackager.repackage(file, NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isFalse(); } @@ -230,8 +221,7 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.setBackupSource(false); repackager.repackage(NO_LIBRARIES); - assertThat(new File(file.getParent(), file.getName() + ".original")) - .doesNotExist(); + assertThat(new File(file.getParent(), file.getName() + ".original")).doesNotExist(); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -242,8 +232,7 @@ public class RepackagerTests { File dest = this.temporaryFolder.newFile("different.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); - assertThat(new File(source.getParent(), source.getName() + ".original")) - .doesNotExist(); + assertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist(); assertThat(hasLauncherClasses(source)).isFalse(); assertThat(hasLauncherClasses(dest)).isTrue(); } @@ -252,8 +241,7 @@ public class RepackagerTests { public void nullDestination() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - assertThatIllegalArgumentException() - .isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)) + assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)) .withMessageContaining("Invalid destination"); } @@ -261,8 +249,8 @@ public class RepackagerTests { public void destinationIsDirectory() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - assertThatIllegalArgumentException().isThrownBy( - () -> repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES)) + assertThatIllegalArgumentException() + .isThrownBy(() -> repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES)) .withMessageContaining("Invalid destination"); } @@ -281,8 +269,7 @@ public class RepackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - assertThatIllegalArgumentException() - .isThrownBy(() -> repackager.repackage(file, null)) + assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(file, null)) .withMessageContaining("Libraries must not be null"); } @@ -295,8 +282,7 @@ public class RepackagerTests { File libNonJarFile = this.temporaryFolder.newFile(); FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); - this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), - libJarFileToUnpack); + this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack); File file = this.testJarFile.getFile(); libJarFile.setLastModified(JAN_1_1980); Repackager repackager = new Repackager(file); @@ -306,8 +292,7 @@ public class RepackagerTests { callback.library(new Library(libNonJarFile, LibraryScope.COMPILE)); }); assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFile.getName())).isTrue(); - assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())) - .isTrue(); + assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())).isTrue(); assertThat(hasEntry(file, "BOOT-INF/lib/" + libNonJarFile.getName())).isFalse(); JarEntry entry = getEntry(file, "BOOT-INF/lib/" + libJarFile.getName()); assertThat(entry.getTime()).isEqualTo(JAN_1_1985); @@ -324,13 +309,10 @@ public class RepackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - assertThatIllegalStateException() - .isThrownBy(() -> repackager.repackage((callback) -> { - callback.library( - new Library(libJarFile, LibraryScope.COMPILE, false)); - callback.library( - new Library(libJarFile, LibraryScope.COMPILE, false)); - })).withMessageContaining("Duplicate library"); + assertThatIllegalStateException().isThrownBy(() -> repackager.repackage((callback) -> { + callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); + callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); + })).withMessageContaining("Duplicate library"); } @Test @@ -345,16 +327,12 @@ public class RepackagerTests { LibraryScope scope = mock(LibraryScope.class); given(layout.getLauncherClassName()).willReturn("testLauncher"); given(layout.getLibraryDestination(anyString(), eq(scope))).willReturn("test/"); - given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))) - .willReturn("test-lib/"); + given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))).willReturn("test-lib/"); repackager.setLayout(layout); - repackager.repackage( - (callback) -> callback.library(new Library(libJarFile, scope))); + repackager.repackage((callback) -> callback.library(new Library(libJarFile, scope))); assertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue(); - assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")) - .isEqualTo("test-lib/"); - assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")) - .isEqualTo("testLauncher"); + assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo("test-lib/"); + assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")).isEqualTo("testLauncher"); } @Test @@ -369,12 +347,9 @@ public class RepackagerTests { LibraryScope scope = mock(LibraryScope.class); given(layout.getLauncherClassName()).willReturn("testLauncher"); repackager.setLayout(layout); - repackager.repackage( - (callback) -> callback.library(new Library(libJarFile, scope))); - assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")) - .isNull(); - assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")) - .isEqualTo("testLauncher"); + repackager.repackage((callback) -> callback.library(new Library(libJarFile, scope))); + assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isNull(); + assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")).isEqualTo("testLauncher"); } @Test @@ -384,8 +359,7 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes()) - .containsKey(new Attributes.Name("Spring-Boot-Version")); + assertThat(actualManifest.getMainAttributes()).containsKey(new Attributes.Name("Spring-Boot-Version")); } @Test @@ -395,24 +369,23 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes()) - .containsEntry(new Attributes.Name("Spring-Boot-Lib"), "BOOT-INF/lib/"); - assertThat(actualManifest.getMainAttributes()).containsEntry( - new Attributes.Name("Spring-Boot-Classes"), "BOOT-INF/classes/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"), + "BOOT-INF/lib/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"), + "BOOT-INF/classes/"); } @Test public void executableWarLayoutAttributes() throws Exception { - this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", - ClassWithMainMethod.class); + this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile("war"); Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes()) - .containsEntry(new Attributes.Name("Spring-Boot-Lib"), "WEB-INF/lib/"); - assertThat(actualManifest.getMainAttributes()).containsEntry( - new Attributes.Name("Spring-Boot-Classes"), "WEB-INF/classes/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"), + "WEB-INF/lib/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"), + "WEB-INF/classes/"); } @Test @@ -432,15 +405,11 @@ public class RepackagerTests { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - repackager.repackage((callback) -> callback - .library(new Library(nestedFile, LibraryScope.COMPILE))); + repackager.repackage((callback) -> callback.library(new Library(nestedFile, LibraryScope.COMPILE))); try (JarFile jarFile = new JarFile(file)) { - assertThat( - jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()) - .isEqualTo(ZipEntry.STORED); - assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()) - .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()).isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()).isEqualTo(ZipEntry.STORED); } } @@ -457,8 +426,7 @@ public class RepackagerTests { assertThat(hasLauncherClasses(source)).isFalse(); assertThat(hasLauncherClasses(dest)).isTrue(); try { - assertThat(Files.getPosixFilePermissions(dest.toPath())) - .contains(PosixFilePermission.OWNER_EXECUTE); + assertThat(Files.getPosixFilePermissions(dest.toPath())).contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows @@ -466,8 +434,7 @@ public class RepackagerTests { } @Test - public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() - throws Exception { + public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); File nestedFile = nested.getFile(); @@ -476,21 +443,18 @@ public class RepackagerTests { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - repackager.repackage((callback) -> callback - .library(new Library(nestedFile, LibraryScope.COMPILE, true))); + repackager.repackage((callback) -> callback.library(new Library(nestedFile, LibraryScope.COMPILE, true))); try (JarFile jarFile = new JarFile(file)) { assertThat(jarFile.getEntry(name).getComment()).startsWith("UNPACK:"); } } @Test - public void existingSourceEntriesTakePrecedenceOverStandardLibraries() - throws Exception { + public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); File nestedFile = nested.getFile(); - this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), - nested.getFile()); + this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile()); this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -502,16 +466,14 @@ public class RepackagerTests { callback.library(new Library(nestedFile, LibraryScope.COMPILE)); }); try (JarFile jarFile = new JarFile(file)) { - assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()) - .isEqualTo(sourceLength); + assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()).isEqualTo(sourceLength); } } @Test public void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/INDEX.LIST", - this.temporaryFolder.newFile("INDEX.LIST")); + this.testJarFile.addFile("META-INF/INDEX.LIST", this.temporaryFolder.newFile("INDEX.LIST")); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); @@ -545,11 +507,9 @@ public class RepackagerTests { } @Test - public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() - throws Exception { + public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/aop.xml", - this.temporaryFolder.newFile("aop.xml")); + this.testJarFile.addFile("META-INF/aop.xml", this.temporaryFolder.newFile("aop.xml")); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); @@ -578,10 +538,8 @@ public class RepackagerTests { } @Test - public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() - throws IOException { - this.testJarFile.addClass("com/example/Application.class", - ClassWithMainMethod.class); + public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException { + this.testJarFile.addClass("com/example/Application.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); File libraryOne = createLibrary(); @@ -593,31 +551,23 @@ public class RepackagerTests { callback.library(new Library(libraryTwo, LibraryScope.COMPILE, true)); callback.library(new Library(libraryThree, LibraryScope.COMPILE, false)); }); - assertThat(getEntryNames(dest)).containsSubsequence( - "org/springframework/boot/loader/", - "BOOT-INF/classes/com/example/Application.class", - "BOOT-INF/lib/" + libraryOne.getName(), - "BOOT-INF/lib/" + libraryTwo.getName(), - "BOOT-INF/lib/" + libraryThree.getName()); + assertThat(getEntryNames(dest)).containsSubsequence("org/springframework/boot/loader/", + "BOOT-INF/classes/com/example/Application.class", "BOOT-INF/lib/" + libraryOne.getName(), + "BOOT-INF/lib/" + libraryTwo.getName(), "BOOT-INF/lib/" + libraryThree.getName()); } @Test - public void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() - throws IOException { + public void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() throws IOException { File library = createLibrary(); - this.testJarFile.addClass("WEB-INF/classes/com/example/Application.class", - ClassWithMainMethod.class); + this.testJarFile.addClass("WEB-INF/classes/com/example/Application.class", ClassWithMainMethod.class); this.testJarFile.addFile("WEB-INF/lib/" + library.getName(), library); File source = this.testJarFile.getFile("war"); File dest = this.temporaryFolder.newFile("dest.war"); Repackager repackager = new Repackager(source); repackager.setLayout(new Layouts.War()); - repackager.repackage(dest, (callback) -> callback - .library(new Library(library, LibraryScope.COMPILE, true))); - assertThat(getEntryNames(dest)).containsSubsequence( - "org/springframework/boot/loader/", - "WEB-INF/classes/com/example/Application.class", - "WEB-INF/lib/" + library.getName()); + repackager.repackage(dest, (callback) -> callback.library(new Library(library, LibraryScope.COMPILE, true))); + assertThat(getEntryNames(dest)).containsSubsequence("org/springframework/boot/loader/", + "WEB-INF/classes/com/example/Application.class", "WEB-INF/lib/" + library.getName()); JarEntry unpackLibrary = getEntry(dest, "WEB-INF/lib/" + library.getName()); assertThat(unpackLibrary.getComment()).startsWith("UNPACK:"); } @@ -633,15 +583,13 @@ public class RepackagerTests { Layout layout = mock(Layout.class); LibraryScope scope = mock(LibraryScope.class); repackager.setLayout(layout); - repackager.repackage( - (callback) -> callback.library(new Library(libJarFile, scope))); - assertThat(getEntryNames(file)).containsExactly("META-INF/", - "META-INF/MANIFEST.MF", "a/", "a/b/", "a/b/C.class"); + repackager.repackage((callback) -> callback.library(new Library(libJarFile, scope))); + assertThat(getEntryNames(file)).containsExactly("META-INF/", "META-INF/MANIFEST.MF", "a/", "a/b/", + "a/b/C.class"); } @Test - public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() - throws IOException { + public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException { File source = this.temporaryFolder.newFile("source.jar"); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) { { @@ -676,26 +624,22 @@ public class RepackagerTests { } @Test - public void kotlinModuleMetadataMovesBeneathBootInfClassesWhenRepackaged() - throws Exception { + public void kotlinModuleMetadataMovesBeneathBootInfClassesWhenRepackaged() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/test.kotlin_module", - this.temporaryFolder.newFile("test.kotlin_module")); + this.testJarFile.addFile("META-INF/test.kotlin_module", this.temporaryFolder.newFile("test.kotlin_module")); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); try (JarFile jarFile = new JarFile(dest)) { assertThat(jarFile.getEntry("META-INF/test.kotlin_module")).isNull(); - assertThat(jarFile.getEntry("BOOT-INF/classes/META-INF/test.kotlin_module")) - .isNotNull(); + assertThat(jarFile.getEntry("BOOT-INF/classes/META-INF/test.kotlin_module")).isNotNull(); } } private File createLibrary() throws IOException { TestJarFile library = new TestJarFile(this.temporaryFolder); - library.addClass("com/example/library/Library.class", - ClassWithoutMainMethod.class); + library.addClass("com/example/library/Library.class", ClassWithoutMainMethod.class); return library.getFile(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java index 599f09ab376..fc85fb10280 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,12 +55,11 @@ public class TestJarFile { addClass(filename, classToCopy, null); } - public void addClass(String filename, Class classToCopy, Long time) - throws IOException { + public void addClass(String filename, Class classToCopy, Long time) throws IOException { File file = getFilePath(filename); file.getParentFile().mkdirs(); - InputStream inputStream = getClass().getResourceAsStream( - "/" + classToCopy.getName().replace('.', '/') + ".class"); + InputStream inputStream = getClass() + .getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class"); copyToFile(inputStream, file); if (time != null) { file.setLastModified(time); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java index f75d3d4c925..42460ebd4f3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class ZipHeaderPeekInputStreamTests { @Test - public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() - throws IOException { + public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 }))) { assertThat(in.hasZipHeader()).isTrue(); @@ -42,8 +41,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void hasZipHeaderReturnsFalseWhenStreamDoesNotStartWithZipHeader() - throws IOException { + public void hasZipHeaderReturnsFalseWhenStreamDoesNotStartWithZipHeader() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { assertThat(in.hasZipHeader()).isFalse(); @@ -88,8 +86,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() - throws IOException { + public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { byte[] bytes = new byte[8]; @@ -101,10 +98,8 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() - throws IOException { - try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 10 }))) { + public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException { + try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 10 }))) { byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(1); assertThat(bytes).containsExactly(10, 0, 0, 0, 0, 0, 0, 0); @@ -112,8 +107,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() - throws IOException { + public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }))) { byte[] bytes = new byte[8]; @@ -124,8 +118,7 @@ public class ZipHeaderPeekInputStreamTests { @Test public void readMoreThanEntireStreamWhenStreamLengthIsZero() throws IOException { - try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[0]))) { + try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[0]))) { byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(-1); assertThat(bytes).containsExactly(0, 0, 0, 0, 0, 0, 0, 0); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java index d4ea3931f98..859fd0a6c1a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,16 +58,14 @@ public abstract class ExecutableArchiveLauncher extends Launcher { mainClass = manifest.getMainAttributes().getValue("Start-Class"); } if (mainClass == null) { - throw new IllegalStateException( - "No 'Start-Class' manifest entry specified in " + this); + throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this); } return mainClass; } @Override protected List getClassPathArchives() throws Exception { - List archives = new ArrayList<>( - this.archive.getNestedArchives(this::isNestedArchive)); + List archives = new ArrayList<>(this.archive.getNestedArchives(this::isNestedArchive)); postProcessClassPathArchives(archives); return archives; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java index 89c3ad6e6d9..bc61f289dea 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Handler.setUseFastConnectionExceptions(true); try { try { @@ -86,8 +85,8 @@ public class LaunchedURLClassLoader extends URLClassLoader { // This should never happen as the IllegalArgumentException indicates // that the package has already been defined and, therefore, // getPackage(name) should not return null. - throw new AssertionError("Package " + name + " has already been " - + "defined but it could not be found"); + throw new AssertionError( + "Package " + name + " has already been " + "defined but it could not be found"); } } return super.loadClass(name, resolve); @@ -118,8 +117,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { // indicates that the package has already been defined and, // therefore, getPackage(name) should not have returned null. throw new AssertionError( - "Package " + packageName + " has already been defined " - + "but it could not be found"); + "Package " + packageName + " has already been defined " + "but it could not be found"); } } } @@ -135,10 +133,8 @@ public class LaunchedURLClassLoader extends URLClassLoader { try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { - JarFile jarFile = ((JarURLConnection) connection) - .getJarFile(); - if (jarFile.getEntry(classEntryName) != null - && jarFile.getEntry(packageEntryName) != null + JarFile jarFile = ((JarURLConnection) connection).getJarFile(); + if (jarFile.getEntry(classEntryName) != null && jarFile.getEntry(packageEntryName) != null && jarFile.getManifest() != null) { definePackage(packageName, jarFile.getManifest(), url); return null; @@ -182,8 +178,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { } } - private static class UseFastConnectionExceptionsEnumeration - implements Enumeration { + private static class UseFastConnectionExceptionsEnumeration implements Enumeration { private final Enumeration delegate; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java index 031cafdaea9..914294ef412 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,8 +81,7 @@ public abstract class Launcher { * @param classLoader the classloader * @throws Exception if the launch fails */ - protected void launch(String[] args, String mainClass, ClassLoader classLoader) - throws Exception { + protected void launch(String[] args, String mainClass, ClassLoader classLoader) throws Exception { Thread.currentThread().setContextClassLoader(classLoader); createMainMethodRunner(mainClass, args, classLoader).run(); } @@ -94,8 +93,7 @@ public abstract class Launcher { * @param classLoader the classloader * @return the main method runner */ - protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, - ClassLoader classLoader) { + protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) { return new MainMethodRunner(mainClass, args); } @@ -123,11 +121,9 @@ public abstract class Launcher { } File root = new File(path); if (!root.exists()) { - throw new IllegalStateException( - "Unable to determine code source archive from " + root); + throw new IllegalStateException("Unable to determine code source archive from " + root); } - return (root.isDirectory() ? new ExplodedArchive(root) - : new JarFileArchive(root)); + return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java index 33397a7daec..d8192b9a17c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class MainMethodRunner { } public void run() throws Exception { - Class mainClass = Thread.currentThread().getContextClassLoader() - .loadClass(this.mainClassName); + Class mainClass = Thread.currentThread().getContextClassLoader().loadClass(this.mainClassName); Method mainMethod = mainClass.getDeclaredMethod("main", String[].class); mainMethod.invoke(null, new Object[] { this.args }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java index 8935582dc07..0257d9e4b70 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -269,8 +269,7 @@ public class PropertiesLauncher extends Launcher { // Try a URL connection content-length header... URLConnection connection = url.openConnection(); try { - connection.setUseCaches( - connection.getClass().getSimpleName().startsWith("JNLP")); + connection.setUseCaches(connection.getClass().getSimpleName().startsWith("JNLP")); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod("HEAD"); @@ -320,8 +319,7 @@ public class PropertiesLauncher extends Launcher { String[] additionalArgs = args; args = new String[defaultArgs.length + additionalArgs.length]; System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length); - System.arraycopy(additionalArgs, 0, args, defaultArgs.length, - additionalArgs.length); + System.arraycopy(additionalArgs, 0, args, defaultArgs.length, additionalArgs.length); } return args; } @@ -330,8 +328,7 @@ public class PropertiesLauncher extends Launcher { protected String getMainClass() throws Exception { String mainClass = getProperty(MAIN, "Start-Class"); if (mainClass == null) { - throw new IllegalStateException( - "No '" + MAIN + "' or 'Start-Class' specified"); + throw new IllegalStateException("No '" + MAIN + "' or 'Start-Class' specified"); } return mainClass; } @@ -342,8 +339,7 @@ public class PropertiesLauncher extends Launcher { for (Archive archive : archives) { urls.add(archive.getUrl()); } - ClassLoader loader = new LaunchedURLClassLoader(urls.toArray(new URL[0]), - getClass().getClassLoader()); + ClassLoader loader = new LaunchedURLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader()); debug("Classpath: " + urls); String customLoaderClassName = getProperty("loader.classLoader"); if (customLoaderClassName != null) { @@ -354,10 +350,8 @@ public class PropertiesLauncher extends Launcher { } @SuppressWarnings("unchecked") - private ClassLoader wrapWithCustomClassLoader(ClassLoader parent, - String loaderClassName) throws Exception { - Class loaderClass = (Class) Class - .forName(loaderClassName, true, parent); + private ClassLoader wrapWithCustomClassLoader(ClassLoader parent, String loaderClassName) throws Exception { + Class loaderClass = (Class) Class.forName(loaderClassName, true, parent); try { return loaderClass.getConstructor(ClassLoader.class).newInstance(parent); @@ -366,8 +360,7 @@ public class PropertiesLauncher extends Launcher { // Ignore and try with URLs } try { - return loaderClass.getConstructor(URL[].class, ClassLoader.class) - .newInstance(new URL[0], parent); + return loaderClass.getConstructor(URL[].class, ClassLoader.class).newInstance(new URL[0], parent); } catch (NoSuchMethodException ex) { // Ignore and try without any arguments @@ -383,21 +376,18 @@ public class PropertiesLauncher extends Launcher { return getProperty(propertyKey, manifestKey, null); } - private String getPropertyWithDefault(String propertyKey, String defaultValue) - throws Exception { + private String getPropertyWithDefault(String propertyKey, String defaultValue) throws Exception { return getProperty(propertyKey, null, defaultValue); } - private String getProperty(String propertyKey, String manifestKey, - String defaultValue) throws Exception { + private String getProperty(String propertyKey, String manifestKey, String defaultValue) throws Exception { if (manifestKey == null) { manifestKey = propertyKey.replace('.', '-'); manifestKey = toCamelCase(manifestKey); } String property = SystemPropertyUtils.getProperty(propertyKey); if (property != null) { - String value = SystemPropertyUtils.resolvePlaceholders(this.properties, - property); + String value = SystemPropertyUtils.resolvePlaceholders(this.properties, property); debug("Property '" + propertyKey + "' from environment: " + value); return value; } @@ -414,10 +404,8 @@ public class PropertiesLauncher extends Launcher { if (manifest != null) { String value = manifest.getMainAttributes().getValue(manifestKey); if (value != null) { - debug("Property '" + manifestKey - + "' from home directory manifest: " + value); - return SystemPropertyUtils.resolvePlaceholders(this.properties, - value); + debug("Property '" + manifestKey + "' from home directory manifest: " + value); + return SystemPropertyUtils.resolvePlaceholders(this.properties, value); } } } @@ -434,8 +422,7 @@ public class PropertiesLauncher extends Launcher { return SystemPropertyUtils.resolvePlaceholders(this.properties, value); } } - return (defaultValue != null) - ? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue) + return (defaultValue != null) ? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue) : defaultValue; } @@ -445,8 +432,7 @@ public class PropertiesLauncher extends Launcher { for (String path : this.paths) { for (Archive archive : getClassPathArchives(path)) { if (archive instanceof ExplodedArchive) { - List nested = new ArrayList<>( - archive.getNestedArchives(new ArchiveEntryFilter())); + List nested = new ArrayList<>(archive.getNestedArchives(new ArchiveEntryFilter())); nested.add(0, archive); lib.addAll(nested); } @@ -509,8 +495,7 @@ public class PropertiesLauncher extends Launcher { private List getNestedArchives(String path) throws Exception { Archive parent = this.parent; String root = path; - if (!root.equals("/") && root.startsWith("/") - || parent.getUrl().equals(this.home.toURI().toURL())) { + if (!root.equals("/") && root.startsWith("/") || parent.getUrl().equals(this.home.toURI().toURL())) { // If home dir is same as parent archive, no need to add it twice. return null; } @@ -539,8 +524,7 @@ public class PropertiesLauncher extends Launcher { } EntryFilter filter = new PrefixMatchingArchiveFilter(root); List archives = new ArrayList<>(parent.getNestedArchives(filter)); - if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar") - && parent != this.parent) { + if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar") && parent != this.parent) { // You can't find the root with an entry filter so it has to be added // explicitly. But don't add the root of the parent archive. archives.add(parent); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java index 8ffe72c4dfa..7964a282620 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class WarLauncher extends ExecutableArchiveLauncher { return entry.getName().equals(WEB_INF_CLASSES); } else { - return entry.getName().startsWith(WEB_INF_LIB) - || entry.getName().startsWith(WEB_INF_LIB_PROVIDED); + return entry.getName().startsWith(WEB_INF_LIB) || entry.getName().startsWith(WEB_INF_LIB_PROVIDED); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java index 8b5b6d43be3..b403121a3d7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java @@ -42,8 +42,7 @@ import java.util.jar.Manifest; */ public class ExplodedArchive implements Archive { - private static final Set SKIPPED_NAMES = new HashSet<>( - Arrays.asList(".", "..")); + private static final Set SKIPPED_NAMES = new HashSet<>(Arrays.asList(".", "..")); private final File root; @@ -116,8 +115,7 @@ public class ExplodedArchive implements Archive { protected Archive getNestedArchive(Entry entry) throws IOException { File file = ((FileEntry) entry).getFile(); - return (file.isDirectory() ? new ExplodedArchive(file) - : new JarFileArchive(file)); + return (file.isDirectory() ? new ExplodedArchive(file) : new JarFileArchive(file)); } @Override @@ -163,13 +161,11 @@ public class ExplodedArchive implements Archive { throw new NoSuchElementException(); } File file = this.current; - if (file.isDirectory() - && (this.recursive || file.getParentFile().equals(this.root))) { + if (file.isDirectory() && (this.recursive || file.getParentFile().equals(this.root))) { this.stack.addFirst(listFiles(file)); } this.current = poll(); - String name = file.toURI().getPath() - .substring(this.root.toURI().getPath().length()); + String name = file.toURI().getPath().substring(this.root.toURI().getPath().length()); return new FileEntry(name, file); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java index fd90f9157d6..31dd40b00cc 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java @@ -104,8 +104,7 @@ public class JarFileArchive implements Archive { return new JarFileArchive(jarFile); } catch (Exception ex) { - throw new IllegalStateException( - "Failed to get nested archive for entry " + entry.getName(), ex); + throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex); } } @@ -133,14 +132,12 @@ public class JarFileArchive implements Archive { int attempts = 0; while (attempts++ < 1000) { String fileName = new File(this.jarFile.getName()).getName(); - File unpackFolder = new File(parent, - fileName + "-spring-boot-libs-" + UUID.randomUUID()); + File unpackFolder = new File(parent, fileName + "-spring-boot-libs-" + UUID.randomUUID()); if (unpackFolder.mkdirs()) { return unpackFolder; } } - throw new IllegalStateException( - "Failed to create unpack folder in directory '" + parent + "'"); + throw new IllegalStateException("Failed to create unpack folder in directory '" + parent + "'"); } private void unpack(JarEntry entry, File file) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java index eb21d0c5709..4223e415356 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,8 +109,7 @@ public class RandomAccessDataFile implements RandomAccessData { return this.fileAccess.readByte(this.offset + position); } - private int read(byte[] bytes, long position, int offset, int length) - throws IOException { + private int read(byte[] bytes, long position, int offset, int length) throws IOException { if (position > this.length) { return -1; } @@ -172,8 +171,7 @@ public class RandomAccessDataFile implements RandomAccessData { if (cappedLen <= 0) { return -1; } - return (int) moveOn( - RandomAccessDataFile.this.read(b, this.position, off, cappedLen)); + return (int) moveOn(RandomAccessDataFile.this.read(b, this.position, off, cappedLen)); } @Override @@ -216,8 +214,7 @@ public class RandomAccessDataFile implements RandomAccessData { openIfNecessary(); } - private int read(byte[] bytes, long position, int offset, int length) - throws IOException { + private int read(byte[] bytes, long position, int offset, int length) throws IOException { synchronized (this.monitor) { openIfNecessary(); this.randomAccessFile.seek(position); @@ -231,8 +228,8 @@ public class RandomAccessDataFile implements RandomAccessData { this.randomAccessFile = new RandomAccessFile(this.file, "r"); } catch (FileNotFoundException ex) { - throw new IllegalArgumentException(String.format("File %s must exist", - this.file.getAbsolutePath())); + throw new IllegalArgumentException( + String.format("File %s must exist", this.file.getAbsolutePath())); } } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java index 813570c016c..efaee044b70 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,8 +104,8 @@ final class AsciiBytes { return false; } for (int i = 0; i < postfix.length; i++) { - if (this.bytes[this.offset + (this.length - 1) - - i] != postfix.bytes[postfix.offset + (postfix.length - 1) - i]) { + if (this.bytes[this.offset + (this.length - 1) - i] != postfix.bytes[postfix.offset + (postfix.length - 1) + - i]) { return false; } } @@ -229,8 +229,7 @@ final class AsciiBytes { this.string = EMPTY_STRING; } else { - this.string = new String(this.bytes, this.offset, this.length, - StandardCharsets.UTF_8); + this.string = new String(this.bytes, this.offset, this.length, StandardCharsets.UTF_8); } } return this.string; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java index b7744f823a9..c3bfb8a399d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java @@ -62,8 +62,8 @@ class CentralDirectoryEndRecord { this.size++; if (this.size > this.block.length) { if (this.size >= MAXIMUM_SIZE || this.size > data.getSize()) { - throw new IOException("Unable to find ZIP central directory " - + "records after reading " + this.size + " bytes"); + throw new IOException( + "Unable to find ZIP central directory " + "records after reading " + this.size + " bytes"); } this.block = createBlockFromEndOfData(data, this.size + READ_BLOCK_SIZE); } @@ -71,20 +71,17 @@ class CentralDirectoryEndRecord { } } - private byte[] createBlockFromEndOfData(RandomAccessData data, int size) - throws IOException { + private byte[] createBlockFromEndOfData(RandomAccessData data, int size) throws IOException { int length = (int) Math.min(data.getSize(), size); return data.read(data.getSize() - length, length); } private boolean isValid() { - if (this.block.length < MINIMUM_SIZE - || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { + if (this.block.length < MINIMUM_SIZE || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { return false; } // Total size must be the structure size + comment - long commentLength = Bytes.littleEndianValue(this.block, - this.offset + COMMENT_LENGTH_OFFSET, 2); + long commentLength = Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2); return this.size == MINIMUM_SIZE + commentLength; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java index e1f3efd17b0..cc79edf5555 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java @@ -53,8 +53,8 @@ final class CentralDirectoryFileHeader implements FileHeader { CentralDirectoryFileHeader() { } - CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, - byte[] extra, AsciiBytes comment, long localHeaderOffset) { + CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, byte[] extra, AsciiBytes comment, + long localHeaderOffset) { this.header = header; this.headerOffset = headerOffset; this.name = name; @@ -63,8 +63,8 @@ final class CentralDirectoryFileHeader implements FileHeader { this.localHeaderOffset = localHeaderOffset; } - void load(byte[] data, int dataOffset, RandomAccessData variableData, - int variableOffset, JarEntryFilter filter) throws IOException { + void load(byte[] data, int dataOffset, RandomAccessData variableData, int variableOffset, JarEntryFilter filter) + throws IOException { // Load fixed part this.header = data; this.headerOffset = dataOffset; @@ -75,8 +75,7 @@ final class CentralDirectoryFileHeader implements FileHeader { // Load variable part dataOffset += 46; if (variableData != null) { - data = variableData.read(variableOffset + 46, - nameLength + extraLength + commentLength); + data = variableData.read(variableOffset + 46, nameLength + extraLength + commentLength); dataOffset = 0; } this.name = new AsciiBytes(data, dataOffset, (int) nameLength); @@ -87,12 +86,10 @@ final class CentralDirectoryFileHeader implements FileHeader { this.comment = NO_COMMENT; if (extraLength > 0) { this.extra = new byte[(int) extraLength]; - System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, - this.extra.length); + System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, this.extra.length); } if (commentLength > 0) { - this.comment = new AsciiBytes(data, - (int) (dataOffset + nameLength + extraLength), (int) commentLength); + this.comment = new AsciiBytes(data, (int) (dataOffset + nameLength + extraLength), (int) commentLength); } } @@ -127,12 +124,10 @@ final class CentralDirectoryFileHeader implements FileHeader { * @return the date and time as milliseconds since the epoch */ private long decodeMsDosFormatDateTime(long datetime) { - LocalDateTime localDateTime = LocalDateTime.of( - (int) (((datetime >> 25) & 0x7f) + 1980), (int) ((datetime >> 21) & 0x0f), - (int) ((datetime >> 16) & 0x1f), (int) ((datetime >> 11) & 0x1f), + LocalDateTime localDateTime = LocalDateTime.of((int) (((datetime >> 25) & 0x7f) + 1980), + (int) ((datetime >> 21) & 0x0f), (int) ((datetime >> 16) & 0x1f), (int) ((datetime >> 11) & 0x1f), (int) ((datetime >> 5) & 0x3f), (int) ((datetime << 1) & 0x3e)); - return localDateTime.toEpochSecond( - ZoneId.systemDefault().getRules().getOffset(localDateTime)) * 1000; + return localDateTime.toEpochSecond(ZoneId.systemDefault().getRules().getOffset(localDateTime)) * 1000; } public long getCrc() { @@ -170,12 +165,11 @@ final class CentralDirectoryFileHeader implements FileHeader { public CentralDirectoryFileHeader clone() { byte[] header = new byte[46]; System.arraycopy(this.header, this.headerOffset, header, 0, header.length); - return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, - this.localHeaderOffset); + return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, this.localHeaderOffset); } - public static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, - int offset, JarEntryFilter filter) throws IOException { + public static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, int offset, + JarEntryFilter filter) throws IOException { CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); byte[] bytes = data.read(offset, 46); fileHeader.load(bytes, 0, data, offset, filter); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java index 67e313d3215..86df6a5839e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ class CentralDirectoryParser { * @return the actual archive data without any prefix bytes * @throws IOException on error */ - public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) - throws IOException { + public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException { CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data); if (skipPrefixBytes) { data = getArchiveData(endRecord, data); @@ -60,22 +59,20 @@ class CentralDirectoryParser { return data; } - private void parseEntries(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) throws IOException { + private void parseEntries(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) + throws IOException { byte[] bytes = centralDirectoryData.read(0, centralDirectoryData.getSize()); CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); int dataOffset = 0; for (int i = 0; i < endRecord.getNumberOfRecords(); i++) { fileHeader.load(bytes, dataOffset, null, 0, null); visitFileHeader(dataOffset, fileHeader); - dataOffset += CENTRAL_DIRECTORY_HEADER_BASE_SIZE - + fileHeader.getName().length() + fileHeader.getComment().length() - + fileHeader.getExtra().length; + dataOffset += CENTRAL_DIRECTORY_HEADER_BASE_SIZE + fileHeader.getName().length() + + fileHeader.getComment().length() + fileHeader.getExtra().length; } } - private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, - RandomAccessData data) { + private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, RandomAccessData data) { long offset = endRecord.getStartOfArchive(data); if (offset == 0) { return data; @@ -83,8 +80,7 @@ class CentralDirectoryParser { return data.getSubsection(offset, data.getSize() - offset); } - private void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + private void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { for (CentralDirectoryVisitor visitor : this.visitors) { visitor.visitStart(endRecord, centralDirectoryData); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java index 51f7d33a587..993986f742f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.boot.loader.data.RandomAccessData; */ interface CentralDirectoryVisitor { - void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData); + void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData); void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java index 1a743112612..4852470c6ac 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java @@ -54,8 +54,7 @@ public class Handler extends URLStreamHandler { private static final String PARENT_DIR = "/../"; - private static final String[] FALLBACK_HANDLERS = { - "sun.net.www.protocol.jar.Handler" }; + private static final String[] FALLBACK_HANDLERS = { "sun.net.www.protocol.jar.Handler" }; private static SoftReference> rootFileCache; @@ -88,15 +87,13 @@ public class Handler extends URLStreamHandler { } } - private boolean isUrlInJarFile(URL url, JarFile jarFile) - throws MalformedURLException { + private boolean isUrlInJarFile(URL url, JarFile jarFile) throws MalformedURLException { // Try the path first to save building a new url string each time return url.getPath().startsWith(jarFile.getUrl().getPath()) && url.toString().startsWith(jarFile.getUrlString()); } - private URLConnection openFallbackConnection(URL url, Exception reason) - throws IOException { + private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException { try { return openConnection(getFallbackHandler(), url); } @@ -142,8 +139,7 @@ public class Handler extends URLStreamHandler { throw new IllegalStateException("Unable to find fallback handler"); } - private URLConnection openConnection(URLStreamHandler handler, URL url) - throws Exception { + private URLConnection openConnection(URLStreamHandler handler, URL url) throws Exception { return new URL(null, url.toExternalForm(), handler).openConnection(); } @@ -181,8 +177,7 @@ public class Handler extends URLStreamHandler { } int lastSlashIndex = file.lastIndexOf('/'); if (lastSlashIndex == -1) { - throw new IllegalArgumentException( - "No / found in context URL's file '" + file + "'"); + throw new IllegalArgumentException("No / found in context URL's file '" + file + "'"); } return file.substring(0, lastSlashIndex + 1) + spec; } @@ -190,8 +185,7 @@ public class Handler extends URLStreamHandler { private String trimToJarRoot(String file) { int lastSeparatorIndex = file.lastIndexOf(SEPARATOR); if (lastSeparatorIndex == -1) { - throw new IllegalArgumentException( - "No !/ found in context URL's file '" + file + "'"); + throw new IllegalArgumentException("No !/ found in context URL's file '" + file + "'"); } return file.substring(0, lastSeparatorIndex); } @@ -204,8 +198,7 @@ public class Handler extends URLStreamHandler { query = path.substring(queryIndex + 1); path = path.substring(0, queryIndex); } - setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, - context.getRef()); + setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, context.getRef()); } private String normalize(String file) { @@ -224,8 +217,7 @@ public class Handler extends URLStreamHandler { while ((parentDirIndex = file.indexOf(PARENT_DIR)) >= 0) { int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1); if (precedingSlashIndex >= 0) { - file = file.substring(0, precedingSlashIndex) - + file.substring(parentDirIndex + 3); + file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3); } else { file = file.substring(parentDirIndex + 4); @@ -345,8 +337,7 @@ public class Handler extends URLStreamHandler { * which are then swallowed. * @param useFastConnectionExceptions if fast connection exceptions can be used. */ - public static void setUseFastConnectionExceptions( - boolean useFastConnectionExceptions) { + public static void setUseFastConnectionExceptions(boolean useFastConnectionExceptions) { JarURLConnection.setUseFastExceptions(useFastConnectionExceptions); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java index 9dc63d73ca6..938739adce5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,14 +106,13 @@ public class JarFile extends java.util.jar.JarFile { * @param type the type of the jar file * @throws IOException if the file cannot be read */ - private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, - RandomAccessData data, JarFileType type) throws IOException { + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarFileType type) + throws IOException { this(rootFile, pathFromRoot, data, null, type, null); } - private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, - RandomAccessData data, JarEntryFilter filter, JarFileType type, - Supplier manifestSupplier) throws IOException { + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarEntryFilter filter, + JarFileType type, Supplier manifestSupplier) throws IOException { super(rootFile.getFile()); this.rootFile = rootFile; this.pathFromRoot = pathFromRoot; @@ -139,16 +138,13 @@ public class JarFile extends java.util.jar.JarFile { return new CentralDirectoryVisitor() { @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { } @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, - int dataOffset) { + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { AsciiBytes name = fileHeader.getName(); - if (name.startsWith(META_INF) - && name.endsWith(SIGNATURE_FILE_EXTENSION)) { + if (name.startsWith(META_INF) && name.endsWith(SIGNATURE_FILE_EXTENSION)) { JarFile.this.signed = true; } } @@ -252,8 +248,7 @@ public class JarFile extends java.util.jar.JarFile { return createJarFileFromEntry(entry); } catch (Exception ex) { - throw new IOException( - "Unable to open nested jar file '" + entry.getName() + "'", ex); + throw new IOException("Unable to open nested jar file '" + entry.getName() + "'", ex); } } @@ -272,22 +267,20 @@ public class JarFile extends java.util.jar.JarFile { } return null; }; - return new JarFile(this.rootFile, - this.pathFromRoot + "!/" - + entry.getName().substring(0, name.length() - 1), + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName().substring(0, name.length() - 1), this.data, filter, JarFileType.NESTED_DIRECTORY, this.manifestSupplier); } private JarFile createJarFileFromFileEntry(JarEntry entry) throws IOException { if (entry.getMethod() != ZipEntry.STORED) { - throw new IllegalStateException("Unable to open nested entry '" - + entry.getName() + "'. It has been compressed and nested " - + "jar files must be stored without compression. Please check the " - + "mechanism used to create your executable jar file"); + throw new IllegalStateException( + "Unable to open nested entry '" + entry.getName() + "'. It has been compressed and nested " + + "jar files must be stored without compression. Please check the " + + "mechanism used to create your executable jar file"); } RandomAccessData entryData = this.entries.getEntryData(entry.getName()); - return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), - entryData, JarFileType.NESTED_JAR); + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), entryData, + JarFileType.NESTED_JAR); } @Override @@ -344,8 +337,7 @@ public class JarFile extends java.util.jar.JarFile { // Fallback to JarInputStream to obtain certificates, not fast but hopefully not // happening that often. try { - try (JarInputStream inputStream = new JarInputStream( - getData().getInputStream())) { + try (JarInputStream inputStream = new JarInputStream(getData().getInputStream())) { java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry(); while (certEntry != null) { inputStream.closeEntry(); @@ -386,8 +378,8 @@ public class JarFile extends java.util.jar.JarFile { */ public static void registerUrlProtocolHandler() { String handlers = System.getProperty(PROTOCOL_HANDLER, ""); - System.setProperty(PROTOCOL_HANDLER, ("".equals(handlers) ? HANDLERS_PACKAGE - : handlers + "|" + HANDLERS_PACKAGE)); + System.setProperty(PROTOCOL_HANDLER, + ("".equals(handlers) ? HANDLERS_PACKAGE : handlers + "|" + HANDLERS_PACKAGE)); resetCachedUrlHandlers(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java index a5a59d52d6a..c917b6a8dfb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java @@ -59,8 +59,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { int version; try { Object runtimeVersion = Runtime.class.getMethod("version").invoke(null); - version = (int) runtimeVersion.getClass().getMethod("major") - .invoke(runtimeVersion); + version = (int) runtimeVersion.getClass().getMethod("major").invoke(runtimeVersion); } catch (Throwable ex) { version = BASE_VERSION; @@ -96,8 +95,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { .synchronizedMap(new LinkedHashMap(16, 0.75f, true) { @Override - protected boolean removeEldestEntry( - Map.Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { if (JarFileEntries.this.jarFile.isSigned()) { return false; } @@ -115,8 +113,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { } @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { int maxSize = endRecord.getNumberOfRecords(); this.centralDirectoryData = centralDirectoryData; this.hashCodes = new int[maxSize]; @@ -235,25 +232,21 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { // local directory to the central directory. We need to re-read // here to skip them RandomAccessData data = this.jarFile.getData(); - byte[] localHeader = data.read(entry.getLocalHeaderOffset(), - LOCAL_FILE_HEADER_SIZE); + byte[] localHeader = data.read(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE); long nameLength = Bytes.littleEndianValue(localHeader, 26, 2); long extraLength = Bytes.littleEndianValue(localHeader, 28, 2); - return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE - + nameLength + extraLength, entry.getCompressedSize()); + return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE + nameLength + extraLength, + entry.getCompressedSize()); } - private T getEntry(CharSequence name, Class type, - boolean cacheEntry) { + private T getEntry(CharSequence name, Class type, boolean cacheEntry) { T entry = doGetEntry(name, type, cacheEntry, null); if (!isMetaInfEntry(name) && isMultiReleaseJar()) { int version = RUNTIME_VERSION; - AsciiBytes nameAlias = (entry instanceof JarEntry) - ? ((JarEntry) entry).getAsciiBytesName() + AsciiBytes nameAlias = (entry instanceof JarEntry) ? ((JarEntry) entry).getAsciiBytesName() : new AsciiBytes(name.toString()); while (version > BASE_VERSION) { - T versionedEntry = doGetEntry("META-INF/versions/" + version + "/" + name, - type, cacheEntry, nameAlias); + T versionedEntry = doGetEntry("META-INF/versions/" + version + "/" + name, type, cacheEntry, nameAlias); if (versionedEntry != null) { return versionedEntry; } @@ -289,8 +282,8 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { return multiRelease; } - private T doGetEntry(CharSequence name, Class type, - boolean cacheEntry, AsciiBytes nameAlias) { + private T doGetEntry(CharSequence name, Class type, boolean cacheEntry, + AsciiBytes nameAlias) { int hashCode = AsciiBytes.hashCode(name); T entry = getEntry(hashCode, name, NO_SUFFIX, type, cacheEntry, nameAlias); if (entry == null) { @@ -300,8 +293,8 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { return entry; } - private T getEntry(int hashCode, CharSequence name, - char suffix, Class type, boolean cacheEntry, AsciiBytes nameAlias) { + private T getEntry(int hashCode, CharSequence name, char suffix, Class type, + boolean cacheEntry, AsciiBytes nameAlias) { int index = getFirstIndex(hashCode); while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { T entry = getEntry(index, type, cacheEntry, nameAlias); @@ -314,18 +307,13 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { } @SuppressWarnings("unchecked") - private T getEntry(int index, Class type, - boolean cacheEntry, AsciiBytes nameAlias) { + private T getEntry(int index, Class type, boolean cacheEntry, AsciiBytes nameAlias) { try { FileHeader cached = this.entriesCache.get(index); - FileHeader entry = (cached != null) ? cached - : CentralDirectoryFileHeader.fromRandomAccessData( - this.centralDirectoryData, - this.centralDirectoryOffsets[index], this.filter); - if (CentralDirectoryFileHeader.class.equals(entry.getClass()) - && type.equals(JarEntry.class)) { - entry = new JarEntry(this.jarFile, (CentralDirectoryFileHeader) entry, - nameAlias); + FileHeader entry = (cached != null) ? cached : CentralDirectoryFileHeader + .fromRandomAccessData(this.centralDirectoryData, this.centralDirectoryOffsets[index], this.filter); + if (CentralDirectoryFileHeader.class.equals(entry.getClass()) && type.equals(JarEntry.class)) { + entry = new JarEntry(this.jarFile, (CentralDirectoryFileHeader) entry, nameAlias); } if (cacheEntry && cached != entry) { this.entriesCache.put(index, entry); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java index 0acfc261d46..323b4416d87 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,13 +66,11 @@ final class JarURLConnection extends java.net.JarURLConnection { } } - private static final JarEntryName EMPTY_JAR_ENTRY_NAME = new JarEntryName( - new StringSequence("")); + private static final JarEntryName EMPTY_JAR_ENTRY_NAME = new JarEntryName(new StringSequence("")); private static final String READ_ACTION = "read"; - private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection - .notFound(); + private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection.notFound(); private final JarFile jarFile; @@ -84,8 +82,7 @@ final class JarURLConnection extends java.net.JarURLConnection { private JarEntry jarEntry; - private JarURLConnection(URL url, JarFile jarFile, JarEntryName jarEntryName) - throws IOException { + private JarURLConnection(URL url, JarFile jarFile, JarEntryName jarEntryName) throws IOException { // What we pass to super is ultimately ignored super(EMPTY_JAR_URL); this.url = url; @@ -162,13 +159,11 @@ final class JarURLConnection extends java.net.JarURLConnection { if (this.jarFile == null) { throw FILE_NOT_FOUND_EXCEPTION; } - if (this.jarEntryName.isEmpty() - && this.jarFile.getType() == JarFile.JarFileType.DIRECT) { + if (this.jarEntryName.isEmpty() && this.jarFile.getType() == JarFile.JarFileType.DIRECT) { throw new IOException("no entry name specified"); } connect(); - InputStream inputStream = (this.jarEntryName.isEmpty() - ? this.jarFile.getData().getInputStream() + InputStream inputStream = (this.jarEntryName.isEmpty() ? this.jarFile.getData().getInputStream() : this.jarFile.getInputStream(this.jarEntry)); if (inputStream == null) { throwFileNotFound(this.jarEntryName, this.jarFile); @@ -176,13 +171,11 @@ final class JarURLConnection extends java.net.JarURLConnection { return inputStream; } - private void throwFileNotFound(Object entry, JarFile jarFile) - throws FileNotFoundException { + private void throwFileNotFound(Object entry, JarFile jarFile) throws FileNotFoundException { if (Boolean.TRUE.equals(useFastExceptions.get())) { throw FILE_NOT_FOUND_EXCEPTION; } - throw new FileNotFoundException( - "JAR entry " + entry + " not found in " + jarFile.getName()); + throw new FileNotFoundException("JAR entry " + entry + " not found in " + jarFile.getName()); } @Override @@ -228,8 +221,7 @@ final class JarURLConnection extends java.net.JarURLConnection { throw FILE_NOT_FOUND_EXCEPTION; } if (this.permission == null) { - this.permission = new FilePermission( - this.jarFile.getRootJarFile().getFile().getPath(), READ_ACTION); + this.permission = new FilePermission(this.jarFile.getRootJarFile().getFile().getPath(), READ_ACTION); } return this.permission; } @@ -294,8 +286,7 @@ final class JarURLConnection extends java.net.JarURLConnection { } } - private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) - throws IOException { + private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) throws IOException { if (Boolean.TRUE.equals(useFastExceptions.get())) { return NOT_FOUND_CONNECTION; } @@ -331,8 +322,7 @@ final class JarURLConnection extends java.net.JarURLConnection { int c = source.charAt(i); if (c > 127) { try { - String encoded = URLEncoder.encode(String.valueOf((char) c), - "UTF-8"); + String encoded = URLEncoder.encode(String.valueOf((char) c), "UTF-8"); write(encoded, outputStream); } catch (UnsupportedEncodingException ex) { @@ -343,8 +333,7 @@ final class JarURLConnection extends java.net.JarURLConnection { if (c == '%') { if ((i + 2) >= length) { throw new IllegalArgumentException( - "Invalid encoded sequence \"" + source.substring(i) - + "\""); + "Invalid encoded sequence \"" + source.substring(i) + "\""); } c = decodeEscapeSequence(source, i); i += 2; @@ -358,8 +347,7 @@ final class JarURLConnection extends java.net.JarURLConnection { int hi = Character.digit(source.charAt(i + 1), 16); int lo = Character.digit(source.charAt(i + 2), 16); if (hi == -1 || lo == -1) { - throw new IllegalArgumentException( - "Invalid encoded sequence \"" + source.substring(i) + "\""); + throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); } return ((char) ((hi << 4) + lo)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java index 03712f593dd..de11cb19d0a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,8 +87,8 @@ public abstract class SystemPropertyUtils { return parseStringValue(properties, text, text, new HashSet<>()); } - private static String parseStringValue(Properties properties, String value, - String current, Set visitedPlaceholders) { + private static String parseStringValue(Properties properties, String value, String current, + Set visitedPlaceholders) { StringBuilder buf = new StringBuilder(current); @@ -96,29 +96,24 @@ public abstract class SystemPropertyUtils { while (startIndex != -1) { int endIndex = findPlaceholderEndIndex(buf, startIndex); if (endIndex != -1) { - String placeholder = buf - .substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); + String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); String originalPlaceholder = placeholder; if (!visitedPlaceholders.add(originalPlaceholder)) { - throw new IllegalArgumentException("Circular placeholder reference '" - + originalPlaceholder + "' in property definitions"); + throw new IllegalArgumentException( + "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the // placeholder // key. - placeholder = parseStringValue(properties, value, placeholder, - visitedPlaceholders); + placeholder = parseStringValue(properties, value, placeholder, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = resolvePlaceholder(properties, value, placeholder); if (propVal == null && VALUE_SEPARATOR != null) { int separatorIndex = placeholder.indexOf(VALUE_SEPARATOR); if (separatorIndex != -1) { - String actualPlaceholder = placeholder.substring(0, - separatorIndex); - String defaultValue = placeholder - .substring(separatorIndex + VALUE_SEPARATOR.length()); - propVal = resolvePlaceholder(properties, value, - actualPlaceholder); + String actualPlaceholder = placeholder.substring(0, separatorIndex); + String defaultValue = placeholder.substring(separatorIndex + VALUE_SEPARATOR.length()); + propVal = resolvePlaceholder(properties, value, actualPlaceholder); if (propVal == null) { propVal = defaultValue; } @@ -127,17 +122,13 @@ public abstract class SystemPropertyUtils { if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. - propVal = parseStringValue(properties, value, propVal, - visitedPlaceholders); - buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), - propVal); - startIndex = buf.indexOf(PLACEHOLDER_PREFIX, - startIndex + propVal.length()); + propVal = parseStringValue(properties, value, propVal, visitedPlaceholders); + buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); + startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length()); } else { // Proceed with unprocessed value. - startIndex = buf.indexOf(PLACEHOLDER_PREFIX, - endIndex + PLACEHOLDER_SUFFIX.length()); + startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length()); } visitedPlaceholders.remove(originalPlaceholder); } @@ -149,8 +140,7 @@ public abstract class SystemPropertyUtils { return buf.toString(); } - private static String resolvePlaceholder(Properties properties, String text, - String placeholderName) { + private static String resolvePlaceholder(Properties properties, String text, String placeholderName) { String propVal = getProperty(placeholderName, null, text); if (propVal != null) { return propVal; @@ -228,8 +218,7 @@ public abstract class SystemPropertyUtils { return -1; } - private static boolean substringMatch(CharSequence str, int index, - CharSequence substring) { + private static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for (int j = 0; j < substring.length(); j++) { int i = index + j; if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java index d4586a5c4ec..857eedc0b6b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public abstract class AbstractExecutableArchiveLauncherTests { protected File createJarArchive(String name, String entryPrefix) throws IOException { File archive = this.temp.newFile(name); - JarOutputStream jarOutputStream = new JarOutputStream( - new FileOutputStream(archive)); + JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(archive)); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/")); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/classes/")); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/lib/")); @@ -80,8 +79,7 @@ public abstract class AbstractExecutableArchiveLauncherTests { entryFile.mkdirs(); } else { - FileCopyUtils.copy(jarFile.getInputStream(entry), - new FileOutputStream(entryFile)); + FileCopyUtils.copy(jarFile.getInputStream(entry), new FileOutputStream(entryFile)); } } jarFile.close(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java index 1d5ff669d57..90fc5ca8ff8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java @@ -36,26 +36,22 @@ import static org.assertj.core.api.Assertions.assertThat; public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests { @Test - public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() - throws Exception { + public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { File explodedRoot = explode(createJarArchive("archive.jar", "BOOT-INF")); JarLauncher launcher = new JarLauncher(new ExplodedArchive(explodedRoot, true)); List archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(), + assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(), new File(explodedRoot, "BOOT-INF/lib/foo.jar").toURI().toURL()); } @Test - public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() - throws Exception { + public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { File jarRoot = createJarArchive("archive.jar", "BOOT-INF"); JarLauncher launcher = new JarLauncher(new JarFileArchive(jarRoot)); List archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/classes!/"), + assertThat(getUrls(archives)).containsOnly(new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/classes!/"), new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/lib/foo.jar!/")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java index 4b56e843915..90403793fa9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,33 +43,28 @@ public class LaunchedURLClassLoaderTests { @Test public void resolveResourceFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResource("demo/Application.java")).isNotNull(); } @Test public void resolveResourcesFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); - assertThat(loader.getResources("demo/Application.java").hasMoreElements()) - .isTrue(); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); + assertThat(loader.getResources("demo/Application.java").hasMoreElements()).isTrue(); } @Test public void resolveRootPathFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResource("")).isNotNull(); } @Test public void resolveRootResourcesFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResources("").hasMoreElements()).isTrue(); } @@ -79,8 +74,7 @@ public class LaunchedURLClassLoaderTests { TestJarCreator.createTestJar(file); JarFile jarFile = new JarFile(file); URL url = jarFile.getUrl(); - LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, - null); + LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null); URL resource = loader.getResource("nested.jar!/3.dat"); assertThat(resource.toString()).isEqualTo(url + "nested.jar!/3.dat"); assertThat(resource.openConnection().getInputStream().read()).isEqualTo(3); @@ -92,8 +86,7 @@ public class LaunchedURLClassLoaderTests { TestJarCreator.createTestJar(file); JarFile jarFile = new JarFile(file); URL url = jarFile.getUrl(); - LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, - null); + LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null); try { Thread.currentThread().interrupt(); URL resource = loader.getResource("nested.jar!/3.dat"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index 5f33aceed21..6dc3374c102 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -63,8 +63,7 @@ public class PropertiesLauncherTests { @Before public void setup() { this.contextClassLoader = Thread.currentThread().getContextClassLoader(); - System.setProperty("loader.home", - new File("src/test/resources").getAbsolutePath()); + System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath()); } @After @@ -83,16 +82,14 @@ public class PropertiesLauncherTests { public void testDefaultHome() { System.clearProperty("loader.home"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isEqualTo(new File(System.getProperty("user.dir"))); + assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("user.dir"))); } @Test public void testAlternateHome() throws Exception { System.setProperty("loader.home", "src/test/resources/home"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isEqualTo(new File(System.getProperty("loader.home"))); + assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("loader.home"))); assertThat(launcher.getMainClass()).isEqualTo("demo.HomeApplication"); } @@ -100,8 +97,7 @@ public class PropertiesLauncherTests { public void testNonExistentHome() { System.setProperty("loader.home", "src/test/resources/nonexistent"); assertThatIllegalStateException().isThrownBy(PropertiesLauncher::new) - .withMessageContaining("Invalid source folder") - .withCauseInstanceOf(IllegalArgumentException.class); + .withMessageContaining("Invalid source folder").withCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -116,8 +112,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.config.name", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("my.Application"); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[etc/]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[etc/]"); } @Test @@ -131,16 +126,14 @@ public class PropertiesLauncherTests { public void testUserSpecifiedDotPath() { System.setProperty("loader.path", "."); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[.]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[.]"); } @Test public void testUserSpecifiedSlashPath() throws Exception { System.setProperty("loader.path", "jars/"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]"); List archives = launcher.getClassPathArchives(); assertThat(archives).areExactly(1, endingWith("app.jar")); } @@ -150,8 +143,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/*"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -161,16 +153,14 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/app.jar]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @Test public void testUserSpecifiedRootOfJarPath() throws Exception { - System.setProperty("loader.path", - "jar:file:./src/test/resources/nested-jars/app.jar!/"); + System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) .isEqualTo("[jar:file:./src/test/resources/nested-jars/app.jar!/]"); @@ -190,8 +180,7 @@ public class PropertiesLauncherTests { @Test public void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception { - System.setProperty("loader.path", - "jar:file:./src/test/resources/nested-jars/app.jar!/./"); + System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/./"); PropertiesLauncher launcher = new PropertiesLauncher(); List archives = launcher.getClassPathArchives(); assertThat(archives).areExactly(1, endingWith("foo.jar!/")); @@ -217,8 +206,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() - throws Exception { + public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception { System.setProperty("loader.path", "nested-jars"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -231,8 +219,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "./jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/app.jar]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -242,8 +229,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.classLoader", URLClassLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/app.jar]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -312,25 +298,21 @@ public class PropertiesLauncherTests { public void testArgsEnhanced() throws Exception { System.setProperty("loader.args", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(Arrays.asList(launcher.getArgs("bar")).toString()) - .isEqualTo("[foo, bar]"); + assertThat(Arrays.asList(launcher.getArgs("bar")).toString()).isEqualTo("[foo, bar]"); } @SuppressWarnings("unchecked") @Test public void testLoadPathCustomizedUsingManifest() throws Exception { - System.setProperty("loader.home", - this.temporaryFolder.getRoot().getAbsolutePath()); + System.setProperty("loader.home", this.temporaryFolder.getRoot().getAbsolutePath()); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar"); - File manifestFile = new File(this.temporaryFolder.getRoot(), - "META-INF/MANIFEST.MF"); + File manifestFile = new File(this.temporaryFolder.getRoot(), "META-INF/MANIFEST.MF"); manifestFile.getParentFile().mkdirs(); manifest.write(new FileOutputStream(manifestFile)); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat((List) ReflectionTestUtils.getField(launcher, "paths")) - .containsExactly("/foo.jar", "/bar/"); + assertThat((List) ReflectionTestUtils.getField(launcher, "paths")).containsExactly("/foo.jar", "/bar/"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java index 802a48d5a4d..77efa2a9449 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java @@ -52,23 +52,22 @@ public abstract class TestJarCreator { writeNestedEntry("nested.jar", unpackNested, jarOutputStream); writeNestedEntry("another-nested.jar", unpackNested, jarOutputStream); writeNestedEntry("space nested.jar", unpackNested, jarOutputStream); - writeNestedMultiReleaseEntry("multi-release.jar", unpackNested, - jarOutputStream); + writeNestedMultiReleaseEntry("multi-release.jar", unpackNested, jarOutputStream); } } - private static void writeNestedEntry(String name, boolean unpackNested, - JarOutputStream jarOutputStream) throws Exception { + private static void writeNestedEntry(String name, boolean unpackNested, JarOutputStream jarOutputStream) + throws Exception { writeNestedEntry(name, unpackNested, jarOutputStream, false); } - private static void writeNestedMultiReleaseEntry(String name, boolean unpackNested, - JarOutputStream jarOutputStream) throws Exception { + private static void writeNestedMultiReleaseEntry(String name, boolean unpackNested, JarOutputStream jarOutputStream) + throws Exception { writeNestedEntry(name, unpackNested, jarOutputStream, true); } - private static void writeNestedEntry(String name, boolean unpackNested, - JarOutputStream jarOutputStream, boolean multiRelease) throws Exception { + private static void writeNestedEntry(String name, boolean unpackNested, JarOutputStream jarOutputStream, + boolean multiRelease) throws Exception { JarEntry nestedEntry = new JarEntry(name); byte[] nestedJarData = getNestedJarData(multiRelease); nestedEntry.setSize(nestedJarData.length); @@ -106,34 +105,30 @@ public abstract class TestJarCreator { return byteArrayOutputStream.toByteArray(); } - private static void writeManifest(JarOutputStream jarOutputStream, String name) - throws Exception { + private static void writeManifest(JarOutputStream jarOutputStream, String name) throws Exception { writeManifest(jarOutputStream, name, false); } - private static void writeManifest(JarOutputStream jarOutputStream, String name, - boolean multiRelease) throws Exception { + private static void writeManifest(JarOutputStream jarOutputStream, String name, boolean multiRelease) + throws Exception { writeDirEntry(jarOutputStream, "META-INF/"); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Built-By", name); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); if (multiRelease) { - manifest.getMainAttributes().putValue("Multi-Release", - Boolean.toString(true)); + manifest.getMainAttributes().putValue("Multi-Release", Boolean.toString(true)); } jarOutputStream.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); manifest.write(jarOutputStream); jarOutputStream.closeEntry(); } - private static void writeDirEntry(JarOutputStream jarOutputStream, String name) - throws IOException { + private static void writeDirEntry(JarOutputStream jarOutputStream, String name) throws IOException { jarOutputStream.putNextEntry(new JarEntry(name)); jarOutputStream.closeEntry(); } - private static void writeEntry(JarOutputStream jarOutputStream, String name, int data) - throws IOException { + private static void writeEntry(JarOutputStream jarOutputStream, String name, int data) throws IOException { jarOutputStream.putNextEntry(new JarEntry(name)); jarOutputStream.write(new byte[] { (byte) data }); jarOutputStream.closeEntry(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java index 00f932b6a8b..c6c02f1d678 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java @@ -36,26 +36,22 @@ import static org.assertj.core.api.Assertions.assertThat; public class WarLauncherTests extends AbstractExecutableArchiveLauncherTests { @Test - public void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() - throws Exception { + public void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception { File explodedRoot = explode(createJarArchive("archive.war", "WEB-INF")); WarLauncher launcher = new WarLauncher(new ExplodedArchive(explodedRoot, true)); List archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new File(explodedRoot, "WEB-INF/classes").toURI().toURL(), + assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "WEB-INF/classes").toURI().toURL(), new File(explodedRoot, "WEB-INF/lib/foo.jar").toURI().toURL()); } @Test - public void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() - throws Exception { + public void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() throws Exception { File jarRoot = createJarArchive("archive.war", "WEB-INF"); WarLauncher launcher = new WarLauncher(new JarFileArchive(jarRoot)); List archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new URL("jar:" + jarRoot.toURI().toURL() + "!/WEB-INF/classes!/"), + assertThat(getUrls(archives)).containsOnly(new URL("jar:" + jarRoot.toURI().toURL() + "!/WEB-INF/classes!/"), new URL("jar:" + jarRoot.toURI().toURL() + "!/WEB-INF/lib/foo.jar!/")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java index cf79c6e646a..ab5a6a5469c 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java @@ -69,15 +69,13 @@ public class ExplodedArchiveTests { File file = this.temporaryFolder.newFile(); TestJarCreator.createTestJar(file); - this.rootFolder = (StringUtils.hasText(folderName) - ? this.temporaryFolder.newFolder(folderName) + this.rootFolder = (StringUtils.hasText(folderName) ? this.temporaryFolder.newFolder(folderName) : this.temporaryFolder.newFolder()); JarFile jarFile = new JarFile(file); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - File destination = new File( - this.rootFolder.getAbsolutePath() + File.separator + entry.getName()); + File destination = new File(this.rootFolder.getAbsolutePath() + File.separator + entry.getName()); destination.getParentFile().mkdirs(); if (entry.isDirectory()) { destination.mkdir(); @@ -101,8 +99,7 @@ public class ExplodedArchiveTests { @Test public void getManifest() throws Exception { - assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")) - .isEqualTo("j1"); + assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test @@ -126,8 +123,7 @@ public class ExplodedArchiveTests { public void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString()) - .isEqualTo(this.rootFolder.toURI() + "nested.jar"); + assertThat(nested.getUrl().toString()).isEqualTo(this.rootFolder.toURI() + "nested.jar"); } @Test @@ -136,8 +132,7 @@ public class ExplodedArchiveTests { Archive nested = this.archive.getNestedArchive(entry); Map nestedEntries = getEntriesMap(nested); assertThat(nestedEntries.size()).isEqualTo(1); - assertThat(nested.getUrl().toString()) - .isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/"); + assertThat(nested.getUrl().toString()).isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/"); } @Test @@ -149,8 +144,7 @@ public class ExplodedArchiveTests { @Test public void getNonRecursiveManifest() throws Exception { - ExplodedArchive archive = new ExplodedArchive( - new File("src/test/resources/root")); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root")); assertThat(archive.getManifest()).isNotNull(); Map entries = getEntriesMap(archive); assertThat(entries.size()).isEqualTo(4); @@ -158,8 +152,7 @@ public class ExplodedArchiveTests { @Test public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception { - ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), - false); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); assertThat(archive.getManifest()).isNotNull(); Map entries = getEntriesMap(archive); assertThat(entries.size()).isEqualTo(3); @@ -167,23 +160,19 @@ public class ExplodedArchiveTests { @Test public void getResourceAsStream() throws Exception { - ExplodedArchive archive = new ExplodedArchive( - new File("src/test/resources/root")); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root")); assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); - assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")) - .isNotNull(); + assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")).isNotNull(); loader.close(); } @Test public void getResourceAsStreamNonRecursive() throws Exception { - ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), - false); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); - assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")) - .isNotNull(); + assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")).isNotNull(); loader.close(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index 464cf55ca83..b7a3f83991c 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -71,8 +71,7 @@ public class JarFileArchiveTests { @Test public void getManifest() throws Exception { - assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")) - .isEqualTo("j1"); + assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test @@ -91,8 +90,7 @@ public class JarFileArchiveTests { public void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString()) - .isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/"); + assertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/"); } @Test @@ -118,12 +116,10 @@ public class JarFileArchiveTests { @Test public void unpackedLocationsFromSameArchiveShareSameParent() throws Exception { setup(true); - File nested = new File(this.archive - .getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl() - .toURI()); - File anotherNested = new File(this.archive - .getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar")) - .getUrl().toURI()); + File nested = new File( + this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl().toURI()); + File anotherNested = new File( + this.archive.getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar")).getUrl().toURI()); assertThat(nested.getParent()).isEqualTo(anotherNested.getParent()); } @@ -153,10 +149,9 @@ public class JarFileArchiveTests { output.close(); JarFileArchive jarFileArchive = new JarFileArchive(file); assertThatIllegalStateException() - .isThrownBy(() -> jarFileArchive.getNestedArchive( - getEntriesMap(jarFileArchive).get("nested/zip64.jar"))) - .withMessageContaining( - "Failed to get nested archive for entry nested/zip64.jar"); + .isThrownBy( + () -> jarFileArchive.getNestedArchive(getEntriesMap(jarFileArchive).get("nested/zip64.jar"))) + .withMessageContaining("Failed to get nested archive for entry nested/zip64.jar"); } private byte[] writeZip64Jar() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index b0122135929..2e964069276 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,17 +82,15 @@ public class RandomAccessDataFileTests { @Test public void fileNotNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RandomAccessDataFile(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(null)) .withMessageContaining("File must not be null"); } @Test public void fileExists() { File file = new File("/does/not/exist"); - assertThatIllegalArgumentException() - .isThrownBy(() -> new RandomAccessDataFile(file)).withMessageContaining( - String.format("File %s must exist", file.getAbsolutePath())); + assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(file)) + .withMessageContaining(String.format("File %s must exist", file.getAbsolutePath())); } @Test @@ -103,31 +101,24 @@ public class RandomAccessDataFileTests { @Test public void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception { - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> this.file.read(257, 0)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.read(257, 0)); } @Test - public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() - throws Exception { + public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 10); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> subsection.read(11, 0)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> subsection.read(11, 0)); } @Test - public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() - throws Exception { - assertThatExceptionOfType(EOFException.class) - .isThrownBy(() -> this.file.read(256, 1)); + public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception { + assertThatExceptionOfType(EOFException.class).isThrownBy(() -> this.file.read(256, 1)); } @Test - public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() - throws Exception { + public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 10); - assertThatExceptionOfType(EOFException.class) - .isThrownBy(() -> subsection.read(10, 1)); + assertThatExceptionOfType(EOFException.class).isThrownBy(() -> subsection.read(10, 1)); } @Test @@ -145,8 +136,7 @@ public class RandomAccessDataFileTests { @Test public void inputStreamReadNullBytesWithOffset() throws Exception { - assertThatNullPointerException() - .isThrownBy(() -> this.inputStream.read(null, 0, 1)) + assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null, 0, 1)) .withMessage("Bytes must not be null"); } @@ -215,14 +205,12 @@ public class RandomAccessDataFileTests { @Test public void subsectionNegativeOffset() { - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> this.file.getSubsection(-1, 1)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(-1, 1)); } @Test public void subsectionNegativeLength() { - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> this.file.getSubsection(0, -1)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(0, -1)); } @Test @@ -234,15 +222,13 @@ public class RandomAccessDataFileTests { @Test public void subsectionTooBig() { this.file.getSubsection(0, 256); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> this.file.getSubsection(0, 257)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(0, 257)); } @Test public void subsectionTooBigWithOffset() { this.file.getSubsection(1, 255); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> this.file.getSubsection(1, 256)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(1, 256)); } @Test @@ -294,8 +280,8 @@ public class RandomAccessDataFileTests { List> results = new ArrayList<>(); for (int i = 0; i < 100; i++) { results.add(executorService.submit(() -> { - InputStream subsectionInputStream = RandomAccessDataFileTests.this.file - .getSubsection(0, 256).getInputStream(); + InputStream subsectionInputStream = RandomAccessDataFileTests.this.file.getSubsection(0, 256) + .getInputStream(); byte[] b = new byte[256]; subsectionInputStream.read(b); return Arrays.equals(b, BYTES); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java index da3d8c52f23..94be92bed87 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,8 +89,7 @@ public class AsciiBytesTests { assertThat(abcd.substring(2).toString()).isEqualTo("CD"); assertThat(abcd.substring(3).toString()).isEqualTo("D"); assertThat(abcd.substring(4).toString()).isEqualTo(""); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> abcd.substring(5)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> abcd.substring(5)); } @Test @@ -100,16 +99,14 @@ public class AsciiBytesTests { assertThat(abcd.substring(1, 3).toString()).isEqualTo("BC"); assertThat(abcd.substring(3, 4).toString()).isEqualTo("D"); assertThat(abcd.substring(3, 3).toString()).isEqualTo(""); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> abcd.substring(3, 5)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> abcd.substring(3, 5)); } @Test public void hashCodeAndEquals() { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); AsciiBytes bc = new AsciiBytes(new byte[] { 66, 67 }); - AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }) - .substring(1, 3); + AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }).substring(1, 3); AsciiBytes bc_string = new AsciiBytes("BC"); assertThat(bc.hashCode()).isEqualTo(bc.hashCode()); assertThat(bc.hashCode()).isEqualTo(bc_substring.hashCode()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java index 7f7c635fdf0..0e9d1a5308d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ public class CentralDirectoryParserTests { parser.addVisitor(visitor); parser.parse(this.jarData, false); List invocations = visitor.getInvocations(); - assertThat(invocations).startsWith("visitStart").endsWith("visitEnd") - .contains("visitFileHeader"); + assertThat(invocations).startsWith("visitStart").endsWith("visitEnd").contains("visitFileHeader"); } @Test @@ -91,13 +90,11 @@ public class CentralDirectoryParserTests { private List headers = new ArrayList<>(); @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { } @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, - int dataOffset) { + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { this.headers.add(fileHeader.clone()); } @@ -116,14 +113,12 @@ public class CentralDirectoryParserTests { private final List invocations = new ArrayList<>(); @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { this.invocations.add("visitStart"); } @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, - int dataOffset) { + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { this.invocations.add("visitFileHeader"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java index 4afc487f76f..c2239778d8d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java @@ -42,8 +42,7 @@ public class HandlerTests { private final Handler handler = new Handler(); @Test - public void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { String spec = "/entry.txt"; URL context = createUrl("file:example.jar!/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -51,8 +50,7 @@ public class HandlerTests { } @Test - public void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { String spec = "/entry.txt"; URL context = createUrl("file:example.jar!/dir/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -60,8 +58,7 @@ public class HandlerTests { } @Test - public void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -69,23 +66,19 @@ public class HandlerTests { } @Test - public void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/dir/"); this.handler.parseURL(context, spec, 0, spec.length()); - assertThat(context.toExternalForm()) - .isEqualTo("jar:file:example.jar!/dir/entry.txt"); + assertThat(context.toExternalForm()).isEqualTo("jar:file:example.jar!/dir/entry.txt"); } @Test - public void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/dir/file"); this.handler.parseURL(context, spec, 0, spec.length()); - assertThat(context.toExternalForm()) - .isEqualTo("jar:file:example.jar!/dir/entry.txt"); + assertThat(context.toExternalForm()).isEqualTo("jar:file:example.jar!/dir/entry.txt"); } @Test @@ -94,110 +87,89 @@ public class HandlerTests { String spec = "jar:file:/other.jar!/nested!/entry.txt"; URL context = createUrl("file:example.jar!/dir/file"); this.handler.parseURL(context, spec, 0, spec.length()); - assertThat(context.toExternalForm()) - .isEqualTo("jar:jar:file:/other.jar!/nested!/entry.txt"); + assertThat(context.toExternalForm()).isEqualTo("jar:jar:file:/other.jar!/nested!/entry.txt"); } @Test - public void sameFileReturnsFalseForUrlsWithDifferentProtocols() - throws MalformedURLException { - assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/content.txt"), - new URL("file:/foo.jar"))).isFalse(); + public void sameFileReturnsFalseForUrlsWithDifferentProtocols() throws MalformedURLException { + assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/content.txt"), new URL("file:/foo.jar"))).isFalse(); } @Test - public void sameFileReturnsFalseForDifferentFileInSameJar() - throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), + public void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException { + assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), new URL("jar:file:/foo.jar!/content.txt"))).isFalse(); } @Test - public void sameFileReturnsFalseForSameFileInDifferentJars() - throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), + public void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException { + assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), new URL("jar:file:/second.jar!/content.txt"))).isFalse(); } @Test public void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), + assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))).isTrue(); } @Test public void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), + assertThat(this.handler.sameFile(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))).isTrue(); } @Test public void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { - assertThat(this.handler - .hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) - .isEqualTo(this.handler.hashCode( - new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); + assertThat(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) + .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); } @Test public void urlWithSpecReferencingParentDirectory() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual( - "file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "../folderB/b.xsd"); } @Test - public void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() - throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual( - "file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", + public void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() throws MalformedURLException { + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "../../../../../../folderB/b.xsd"); } @Test public void urlWithSpecReferencingCurrentDirectory() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual( - "file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "./folderB/./b.xsd"); } @Test public void urlWithRef() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", - "!/foo.txt#alpha"); + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt#alpha"); } @Test public void urlWithQuery() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", - "!/foo.txt?alpha"); + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt?alpha"); } @Test public void fallbackToJdksJarUrlStreamHandler() throws Exception { File testJar = this.temporaryFolder.newFile("test.jar"); TestJarCreator.createTestJar(testJar); - URLConnection connection = new URL(null, - "jar:file:" + testJar.getAbsolutePath() + "!/nested.jar!/", this.handler) - .openConnection(); + URLConnection connection = new URL(null, "jar:file:" + testJar.getAbsolutePath() + "!/nested.jar!/", + this.handler).openConnection(); assertThat(connection).isInstanceOf(JarURLConnection.class); - URLConnection jdkConnection = new URL(null, - "jar:file:file:" + testJar.getAbsolutePath() + "!/nested.jar!/", + URLConnection jdkConnection = new URL(null, "jar:file:file:" + testJar.getAbsolutePath() + "!/nested.jar!/", this.handler).openConnection(); assertThat(jdkConnection).isNotInstanceOf(JarURLConnection.class); } - private void assertStandardAndCustomHandlerUrlsAreEqual(String context, String spec) - throws MalformedURLException { + private void assertStandardAndCustomHandlerUrlsAreEqual(String context, String spec) throws MalformedURLException { URL standardUrl = new URL(new URL("jar:" + context), spec); - URL customHandlerUrl = new URL(new URL("jar", null, -1, context, this.handler), - spec); + URL customHandlerUrl = new URL(new URL("jar", null, -1, context, this.handler), spec); assertThat(customHandlerUrl.toString()).isEqualTo(standardUrl.toString()); assertThat(customHandlerUrl.getFile()).isEqualTo(standardUrl.getFile()); assertThat(customHandlerUrl.getPath()).isEqualTo(standardUrl.getPath()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index 02be510381b..1b0c4194f9d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,8 +110,7 @@ public class JarFileTests { @Test public void getManifest() throws Exception { - assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")) - .isEqualTo("j1"); + assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test @@ -141,8 +140,7 @@ public class JarFileTests { @Test public void getSpecialResourceViaClassLoader() throws Exception { - URLClassLoader urlClassLoader = new URLClassLoader( - new URL[] { this.jarFile.getUrl() }); + URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { this.jarFile.getUrl() }); assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull(); urlClassLoader.close(); } @@ -156,8 +154,7 @@ public class JarFileTests { @Test public void getInputStream() throws Exception { - InputStream inputStream = this.jarFile - .getInputStream(this.jarFile.getEntry("1.dat")); + InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("1.dat")); assertThat(inputStream.available()).isEqualTo(1); assertThat(inputStream.read()).isEqualTo(1); assertThat(inputStream.available()).isEqualTo(0); @@ -186,8 +183,7 @@ public class JarFileTests { @Test public void close() throws Exception { - RandomAccessDataFile randomAccessDataFile = spy( - new RandomAccessDataFile(this.rootJarFile)); + RandomAccessDataFile randomAccessDataFile = spy(new RandomAccessDataFile(this.rootJarFile)); JarFile jarFile = new JarFile(randomAccessDataFile); jarFile.close(); verify(randomAccessDataFile).close(); @@ -203,19 +199,16 @@ public class JarFileTests { assertThat(jarURLConnection.getContentLength()).isGreaterThan(1); assertThat(jarURLConnection.getContent()).isSameAs(this.jarFile); assertThat(jarURLConnection.getContentType()).isEqualTo("x-java/jar"); - assertThat(jarURLConnection.getJarFileURL().toURI()) - .isEqualTo(this.rootJarFile.toURI()); + assertThat(jarURLConnection.getJarFileURL().toURI()).isEqualTo(this.rootJarFile.toURI()); } @Test public void createEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "1.dat"); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat"); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); assertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile); - assertThat(jarURLConnection.getJarEntry()) - .isSameAs(this.jarFile.getJarEntry("1.dat")); + assertThat(jarURLConnection.getJarEntry()).isSameAs(this.jarFile.getJarEntry("1.dat")); assertThat(jarURLConnection.getContentLength()).isEqualTo(1); assertThat(jarURLConnection.getContent()).isInstanceOf(InputStream.class); assertThat(jarURLConnection.getContentType()).isEqualTo("content/unknown"); @@ -228,8 +221,7 @@ public class JarFileTests { @Test public void getMissingEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); assertThatExceptionOfType(FileNotFoundException.class) .isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry); } @@ -252,8 +244,7 @@ public class JarFileTests { @Test public void getNestedJarFile() throws Exception { - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); Enumeration entries = nestedJarFile.entries(); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/"); @@ -263,18 +254,15 @@ public class JarFileTests { assertThat(entries.nextElement().getName()).isEqualTo("\u00E4.dat"); assertThat(entries.hasMoreElements()).isFalse(); - InputStream inputStream = nestedJarFile - .getInputStream(nestedJarFile.getEntry("3.dat")); + InputStream inputStream = nestedJarFile.getInputStream(nestedJarFile.getEntry("3.dat")); assertThat(inputStream.read()).isEqualTo(3); assertThat(inputStream.read()).isEqualTo(-1); URL url = nestedJarFile.getUrl(); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/"); JarURLConnection conn = (JarURLConnection) url.openConnection(); assertThat(conn.getJarFile()).isSameAs(nestedJarFile); - assertThat(conn.getJarFileURL().toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); + assertThat(conn.getJarFileURL().toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); assertThat(conn.getInputStream()).isNotNull(); JarInputStream jarInputStream = new JarInputStream(conn.getInputStream()); assertThat(jarInputStream.getNextJarEntry().getName()).isEqualTo("3.dat"); @@ -289,31 +277,26 @@ public class JarFileTests { @Test public void getNestedJarDirectory() throws Exception { - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("d/")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("d/")); Enumeration entries = nestedJarFile.entries(); assertThat(entries.nextElement().getName()).isEqualTo("9.dat"); assertThat(entries.hasMoreElements()).isFalse(); - InputStream inputStream = nestedJarFile - .getInputStream(nestedJarFile.getEntry("9.dat")); + InputStream inputStream = nestedJarFile.getInputStream(nestedJarFile.getEntry("9.dat")); assertThat(inputStream.read()).isEqualTo(9); assertThat(inputStream.read()).isEqualTo(-1); URL url = nestedJarFile.getUrl(); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/d!/"); - assertThat(((JarURLConnection) url.openConnection()).getJarFile()) - .isSameAs(nestedJarFile); + assertThat(((JarURLConnection) url.openConnection()).getJarFile()).isSameAs(nestedJarFile); } @Test public void getNestedJarEntryUrl() throws Exception { - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL url = nestedJarFile.getJarEntry("3.dat").getUrl(); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"); InputStream inputStream = url.openStream(); assertThat(inputStream).isNotNull(); assertThat(inputStream.read()).isEqualTo(3); @@ -330,8 +313,7 @@ public class JarFileTests { assertThat(inputStream.read()).isEqualTo(3); JarURLConnection connection = (JarURLConnection) url.openConnection(); assertThat(connection.getURL().toString()).isEqualTo(spec); - assertThat(connection.getJarFileURL().toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); + assertThat(connection.getJarFileURL().toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); assertThat(connection.getEntryName()).isEqualTo("3.dat"); } @@ -342,8 +324,7 @@ public class JarFileTests { @Test public void createNonNestedUrlFromPathString() throws Exception { - nonNestedJarFileFromString( - "jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat"); + nonNestedJarFileFromString("jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat"); } private void nonNestedJarFileFromString(String spec) throws Exception { @@ -355,15 +336,13 @@ public class JarFileTests { assertThat(inputStream.read()).isEqualTo(2); JarURLConnection connection = (JarURLConnection) url.openConnection(); assertThat(connection.getURL().toString()).isEqualTo(spec); - assertThat(connection.getJarFileURL().toURI()) - .isEqualTo(this.rootJarFile.toURI()); + assertThat(connection.getJarFileURL().toURI()).isEqualTo(this.rootJarFile.toURI()); assertThat(connection.getEntryName()).isEqualTo("2.dat"); } @Test public void getDirectoryInputStream() throws Exception { - InputStream inputStream = this.jarFile - .getInputStream(this.jarFile.getEntry("d/")); + InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d/")); assertThat(inputStream).isNotNull(); assertThat(inputStream.read()).isEqualTo(-1); } @@ -378,8 +357,8 @@ public class JarFileTests { @Test public void sensibleToString() throws Exception { assertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath()); - assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")) - .toString()).isEqualTo(this.rootJarFile.getPath() + "!/nested.jar"); + assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")).toString()) + .isEqualTo(this.rootJarFile.getPath() + "!/nested.jar"); } @Test @@ -426,12 +405,10 @@ public class JarFileTests { @Test public void cannotLoadMissingJar() throws Exception { // relates to gh-1070 - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL nestedUrl = nestedJarFile.getUrl(); URL url = new URL(nestedUrl, nestedJarFile.getUrl() + "missing.jar!/3.dat"); - assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(url.openConnection()::getInputStream); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(url.openConnection()::getInputStream); } @Test @@ -487,14 +464,12 @@ public class JarFileTests { JarURLConnection.setUseFastExceptions(true); try { JarFile.registerUrlProtocolHandler(); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL context = nested.getUrl(); - new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat") - .openConnection().getInputStream().close(); + new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat").openConnection() + .getInputStream().close(); assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( - new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") - .openConnection()::getInputStream); + new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat").openConnection()::getInputStream); } finally { JarURLConnection.setUseFastExceptions(false); @@ -503,8 +478,7 @@ public class JarFileTests { @Test public void multiReleaseEntry() throws Exception { - JarFile multiRelease = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("multi-release.jar")); + JarFile multiRelease = this.jarFile.getNestedJarFile(this.jarFile.getEntry("multi-release.jar")); ZipEntry entry = multiRelease.getEntry("multi-release.dat"); assertThat(entry.getName()).isEqualTo("multi-release.dat"); InputStream inputStream = multiRelease.getInputStream(entry); @@ -515,8 +489,7 @@ public class JarFileTests { private int getJavaVersion() { try { Object runtimeVersion = Runtime.class.getMethod("version").invoke(null); - return (int) runtimeVersion.getClass().getMethod("major") - .invoke(runtimeVersion); + return (int) runtimeVersion.getClass().getMethod("major").invoke(runtimeVersion); } catch (Throwable ex) { return 8; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java index 14d8a985e70..f254aaf82ef 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,15 +58,13 @@ public class JarURLConnectionTests { @Test public void connectionToRootUsingAbsoluteUrl() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/"); - assertThat(JarURLConnection.get(url, this.jarFile).getContent()) - .isSameAs(this.jarFile); + assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile); } @Test public void connectionToRootUsingRelativeUrl() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/"); - assertThat(JarURLConnection.get(url, this.jarFile).getContent()) - .isSameAs(this.jarFile); + assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile); } @Test @@ -84,8 +82,7 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() - throws Exception { + public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception { URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 })); @@ -106,32 +103,26 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() - throws Exception { + public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() - throws Exception { + public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() - throws Exception { - URL url = new URL(new URL("jar", null, -1, - "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception { + URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), + "/3.dat"); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @@ -145,33 +136,30 @@ public class JarURLConnectionTests { @Test public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception { - URL url = new URL( - "jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat"); + URL url = new URL("jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() - throws Exception { + public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThatExceptionOfType(FileNotFoundException.class) .isThrownBy(JarURLConnection.get(url, nested)::getInputStream); } @Test public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception { - URL url = new URL(new URL("jar", null, -1, - "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); + URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), + "/3.dat"); assertThat(url.openConnection().getContentLength()).isEqualTo(1); } @Test public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception { - URL url = new URL(new URL("jar", null, -1, - "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); + URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), + "/3.dat"); assertThat(url.openConnection().getContentLengthLong()).isEqualTo(1); } @@ -179,33 +167,28 @@ public class JarURLConnectionTests { public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat"); JarURLConnection connection = JarURLConnection.get(url, this.jarFile); - assertThat(connection.getLastModified()) - .isEqualTo(connection.getJarEntry().getTime()); + assertThat(connection.getLastModified()).isEqualTo(connection.getJarEntry().getTime()); } @Test public void jarEntryBasicName() { - assertThat(new JarEntryName(new StringSequence("a/b/C.class")).toString()) - .isEqualTo("a/b/C.class"); + assertThat(new JarEntryName(new StringSequence("a/b/C.class")).toString()).isEqualTo("a/b/C.class"); } @Test public void jarEntryNameWithSingleByteEncodedCharacters() { - assertThat(new JarEntryName(new StringSequence("%61/%62/%43.class")).toString()) - .isEqualTo("a/b/C.class"); + assertThat(new JarEntryName(new StringSequence("%61/%62/%43.class")).toString()).isEqualTo("a/b/C.class"); } @Test public void jarEntryNameWithDoubleByteEncodedCharacters() { - assertThat(new JarEntryName(new StringSequence("%c3%a1/b/C.class")).toString()) - .isEqualTo("\u00e1/b/C.class"); + assertThat(new JarEntryName(new StringSequence("%c3%a1/b/C.class")).toString()).isEqualTo("\u00e1/b/C.class"); } @Test public void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() { - assertThat( - new JarEntryName(new StringSequence("%c3%a1/b/\u00c7.class")).toString()) - .isEqualTo("\u00e1/b/\u00c7.class"); + assertThat(new JarEntryName(new StringSequence("%c3%a1/b/\u00c7.class")).toString()) + .isEqualTo("\u00e1/b/\u00c7.class"); } private String getAbsolutePath() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java index 8d4642ef724..821899d590b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,22 +60,18 @@ public class StringSequenceTests { @Test public void subSequenceWithJustStartShouldReturnSubSequence() { - assertThat(new StringSequence("smiles").subSequence(1).toString()) - .isEqualTo("miles"); + assertThat(new StringSequence("smiles").subSequence(1).toString()).isEqualTo("miles"); } @Test public void subSequenceShouldReturnSubSequence() { - assertThat(new StringSequence("hamburger").subSequence(4, 8).toString()) - .isEqualTo("urge"); - assertThat(new StringSequence("smiles").subSequence(1, 5).toString()) - .isEqualTo("mile"); + assertThat(new StringSequence("hamburger").subSequence(4, 8).toString()).isEqualTo("urge"); + assertThat(new StringSequence("smiles").subSequence(1, 5).toString()).isEqualTo("mile"); } @Test public void subSequenceWhenCalledMultipleTimesShouldReturnSubSequence() { - assertThat(new StringSequence("hamburger").subSequence(4, 8).subSequence(1, 3) - .toString()).isEqualTo("rg"); + assertThat(new StringSequence("hamburger").subSequence(4, 8).subSequence(1, 3).toString()).isEqualTo("rg"); } @Test @@ -83,8 +79,7 @@ public class StringSequenceTests { StringSequence sequence = new StringSequence("abcde").subSequence(1, 4); assertThat(sequence.toString()).isEqualTo("bcd"); assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d"); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> sequence.subSequence(3, 4)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> sequence.subSequence(3, 4)); } @Test @@ -92,8 +87,7 @@ public class StringSequenceTests { StringSequence sequence = new StringSequence("abcde").subSequence(1, 4); assertThat(sequence.toString()).isEqualTo("bcd"); assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d"); - assertThatExceptionOfType(IndexOutOfBoundsException.class) - .isThrownBy(() -> sequence.subSequence(4, 3)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> sequence.subSequence(4, 3)); } @Test @@ -148,10 +142,8 @@ public class StringSequenceTests { @Test public void hashCodeShouldBeSameAsString() { - assertThat(new StringSequence("hamburger").hashCode()) - .isEqualTo("hamburger".hashCode()); - assertThat(new StringSequence("hamburger").subSequence(4, 8).hashCode()) - .isEqualTo("urge".hashCode()); + assertThat(new StringSequence("hamburger").hashCode()).isEqualTo("hamburger".hashCode()); + assertThat(new StringSequence("hamburger").subSequence(4, 8).hashCode()).isEqualTo("urge".hashCode()); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java index 32adbf30ad6..6733a24d149 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,20 +46,17 @@ public class SystemPropertyUtilsTests { @Test public void testDefaultValue() { - assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")) - .isEqualTo("foo"); + assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")).isEqualTo("foo"); } @Test public void testNestedPlaceholder() { - assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")) - .isEqualTo("foo"); + assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")).isEqualTo("foo"); } @Test public void testEnvVar() { - assertThat(SystemPropertyUtils.getProperty("lang")) - .isEqualTo(System.getenv("LANG")); + assertThat(SystemPropertyUtils.getProperty("lang")).isEqualTo(System.getenv("LANG")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java index adf691e406a..9d1eb2df141 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,8 +75,8 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { this.excludeGroupIds = excludeGroupIds; } - protected Set filterDependencies(Set dependencies, - FilterArtifacts filters) throws MojoExecutionException { + protected Set filterDependencies(Set dependencies, FilterArtifacts filters) + throws MojoExecutionException { try { Set filtered = new LinkedHashSet<>(dependencies); filtered.retainAll(filters.filter(dependencies)); @@ -97,8 +97,7 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { for (ArtifactsFilter additionalFilter : additionalFilters) { filters.addFilter(additionalFilter); } - filters.addFilter( - new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); + filters.addFilter(new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); if (this.includes != null && !this.includes.isEmpty()) { filters.addFilter(new IncludeFilter(this.includes)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java index d850bf2b7fe..c739e391247 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java @@ -220,8 +220,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { */ @Deprecated protected boolean enableForkByDefault() { - return hasAgent() || hasJvmArgs() || hasEnvVariables() - || hasWorkingDirectorySet(); + return hasAgent() || hasJvmArgs() || hasEnvVariables() || hasWorkingDirectorySet(); } private boolean hasAgent() { @@ -231,24 +230,20 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { private boolean hasJvmArgs() { return (this.jvmArguments != null && !this.jvmArguments.isEmpty()) - || (this.systemPropertyVariables != null - && !this.systemPropertyVariables.isEmpty()); + || (this.systemPropertyVariables != null && !this.systemPropertyVariables.isEmpty()); } private boolean hasEnvVariables() { - return (this.environmentVariables != null - && !this.environmentVariables.isEmpty()); + return (this.environmentVariables != null && !this.environmentVariables.isEmpty()); } private boolean hasWorkingDirectorySet() { return this.workingDirectory != null; } - private void run(String startClassName) - throws MojoExecutionException, MojoFailureException { + private void run(String startClassName) throws MojoExecutionException, MojoFailureException { boolean fork = isFork(); - this.project.getProperties().setProperty("_spring.boot.fork.enabled", - Boolean.toString(fork)); + this.project.getProperties().setProperty("_spring.boot.fork.enabled", Boolean.toString(fork)); if (fork) { doRunWithForkedJvm(startClassName); } @@ -273,24 +268,20 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { + String.join(" ", runArguments.asArray()) + "]"); } if (hasWorkingDirectorySet()) { - getLog().warn( - "Fork mode disabled, ignoring working directory configuration"); + getLog().warn("Fork mode disabled, ignoring working directory configuration"); } } } - private void doRunWithForkedJvm(String startClassName) - throws MojoExecutionException, MojoFailureException { + private void doRunWithForkedJvm(String startClassName) throws MojoExecutionException, MojoFailureException { List args = new ArrayList<>(); addAgents(args); addJvmArgs(args); addClasspath(args); args.add(startClassName); addArgs(args); - runWithForkedJvm( - (this.workingDirectory != null) ? this.workingDirectory - : this.project.getBasedir(), - args, determineEnvironmentVariables()); + runWithForkedJvm((this.workingDirectory != null) ? this.workingDirectory : this.project.getBasedir(), args, + determineEnvironmentVariables()); } /** @@ -302,8 +293,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { * @throws MojoFailureException in case of MOJO failures */ protected abstract void runWithForkedJvm(File workingDirectory, List args, - Map environmentVariables) - throws MojoExecutionException, MojoFailureException; + Map environmentVariables) throws MojoExecutionException, MojoFailureException; /** * Run with the current VM, using the specified arguments. @@ -433,8 +423,8 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { } } if (mainClass == null) { - throw new MojoExecutionException("Unable to find a suitable main class, " - + "please add a 'mainClass' property"); + throw new MojoExecutionException( + "Unable to find a suitable main class, " + "please add a 'mainClass' property"); } return mainClass; } @@ -466,8 +456,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { for (Resource resource : this.project.getResources()) { File directory = new File(resource.getDirectory()); urls.add(directory.toURI().toURL()); - FileUtils.removeDuplicatesFromOutputDirectory(this.classesDirectory, - directory); + FileUtils.removeDuplicatesFromOutputDirectory(this.classesDirectory, directory); } } } @@ -476,12 +465,9 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { urls.add(this.classesDirectory.toURI().toURL()); } - private void addDependencies(List urls) - throws MalformedURLException, MojoExecutionException { - FilterArtifacts filters = (this.useTestClasspath ? getFilters() - : getFilters(new TestArtifactFilter())); - Set artifacts = filterDependencies(this.project.getArtifacts(), - filters); + private void addDependencies(List urls) throws MalformedURLException, MojoExecutionException { + FilterArtifacts filters = (this.useTestClasspath ? getFilters() : getFilters(new TestArtifactFilter())); + Set artifacts = filterDependencies(this.project.getArtifacts(), filters); for (Artifact artifact : artifacts) { if (artifact.getFile() != null) { urls.add(artifact.getFile().toURI().toURL()); @@ -491,8 +477,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { private void logArguments(String message, String[] args) { if (getLog().isDebugEnabled()) { - getLog().debug( - Arrays.stream(args).collect(Collectors.joining(" ", message, ""))); + getLog().debug(Arrays.stream(args).collect(Collectors.joining(" ", message, ""))); } } @@ -536,9 +521,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { synchronized (this.monitor) { if (this.exception != null) { throw new MojoExecutionException( - "An exception occurred while running. " - + this.exception.getMessage(), - this.exception); + "An exception occurred while running. " + this.exception.getMessage(), this.exception); } } } @@ -573,9 +556,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { } catch (NoSuchMethodException ex) { Exception wrappedEx = new Exception( - "The specified mainClass doesn't contain a " - + "main method with appropriate signature.", - ex); + "The specified mainClass doesn't contain a " + "main method with appropriate signature.", ex); thread.getThreadGroup().uncaughtException(thread, wrappedEx); } catch (Exception ex) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java index e6fca75eb7e..15571fef648 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,7 @@ public class ArtifactsLibraries implements Libraries { private final Log log; - public ArtifactsLibraries(Set artifacts, Collection unpacks, - Log log) { + public ArtifactsLibraries(Set artifacts, Collection unpacks, Log log) { this.artifacts = artifacts; this.unpacks = unpacks; this.log = log; @@ -78,8 +77,7 @@ public class ArtifactsLibraries implements Libraries { name = artifact.getGroupId() + "-" + name; this.log.debug("Renamed to: " + name); } - callback.library(new Library(name, artifact.getFile(), scope, - isUnpackRequired(artifact))); + callback.library(new Library(name, artifact.getFile(), scope, isUnpackRequired(artifact))); } } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java index 45c45b5ade6..45b15af5c8a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java @@ -41,8 +41,7 @@ import org.springframework.boot.loader.tools.BuildPropertiesWriter.ProjectDetail * @author Stephane Nicoll * @since 1.4.0 */ -@Mojo(name = "build-info", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, - threadSafe = true) +@Mojo(name = "build-info", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true) public class BuildInfoMojo extends AbstractMojo { @Component @@ -57,8 +56,7 @@ public class BuildInfoMojo extends AbstractMojo { /** * The location of the generated build-info.properties. */ - @Parameter( - defaultValue = "${project.build.outputDirectory}/META-INF/build-info.properties") + @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/build-info.properties") private File outputFile; /** @@ -71,16 +69,13 @@ public class BuildInfoMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { try { - new BuildPropertiesWriter(this.outputFile) - .writeBuildProperties(new ProjectDetails(this.project.getGroupId(), - this.project.getArtifactId(), this.project.getVersion(), - this.project.getName(), Instant.now(), - this.additionalProperties)); + new BuildPropertiesWriter(this.outputFile).writeBuildProperties(new ProjectDetails( + this.project.getGroupId(), this.project.getArtifactId(), this.project.getVersion(), + this.project.getName(), Instant.now(), this.additionalProperties)); this.buildContext.refresh(this.outputFile); } catch (NullAdditionalPropertyValueException ex) { - throw new MojoFailureException( - "Failed to generate build-info.properties. " + ex.getMessage(), ex); + throw new MojoFailureException("Failed to generate build-info.properties. " + ex.getMessage(), ex); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java index 9c09e94e8b4..ff4e8c73835 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,8 @@ public abstract class DependencyFilter extends AbstractArtifactsFilter { if (!dependency.getArtifactId().equals(artifact.getArtifactId())) { return false; } - return (dependency.getClassifier() == null || artifact.getClassifier() != null - && dependency.getClassifier().equals(artifact.getClassifier())); + return (dependency.getClassifier() == null + || artifact.getClassifier() != null && dependency.getClassifier().equals(artifact.getClassifier())); } protected final List getFilters() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java index 347f0a53d6d..fed0f401f63 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,8 @@ public class PropertiesMergingResourceTransformer implements ResourceTransformer } @Override - public void processResource(String resource, InputStream inputStream, - List relocators) throws IOException { + public void processResource(String resource, InputStream inputStream, List relocators) + throws IOException { Properties properties = new Properties(); properties.load(inputStream); inputStream.close(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java index f08f374262c..c1f62ac6b1e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java @@ -60,8 +60,7 @@ import org.springframework.boot.loader.tools.Repackager.MainClassTimeoutWarningL * @author Stephane Nicoll * @author Björn Lindström */ -@Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, - threadSafe = true, +@Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) public class RepackageMojo extends AbstractDependencyFilterMojo { @@ -220,10 +219,8 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { Artifact source = getSourceArtifact(); File target = getTargetFile(); Repackager repackager = getRepackager(source.getFile()); - Set artifacts = filterDependencies(this.project.getArtifacts(), - getFilters(getAdditionalFilters())); - Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack, - getLog()); + Set artifacts = filterDependencies(this.project.getArtifacts(), getFilters(getAdditionalFilters())); + Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack, getLog()); try { LaunchScript launchScript = getLaunchScript(); repackager.repackage(target, libraries, launchScript); @@ -248,8 +245,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { private Artifact getArtifact(String classifier) { if (classifier != null) { for (Artifact attachedArtifact : this.project.getAttachedArtifacts()) { - if (classifier.equals(attachedArtifact.getClassifier()) - && attachedArtifact.getFile() != null + if (classifier.equals(attachedArtifact.getClassifier()) && attachedArtifact.getFile() != null && attachedArtifact.getFile().isFile()) { return attachedArtifact; } @@ -266,14 +262,13 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { if (!this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } - return new File(this.outputDirectory, this.finalName + classifier + "." - + this.project.getArtifact().getArtifactHandler().getExtension()); + return new File(this.outputDirectory, + this.finalName + classifier + "." + this.project.getArtifact().getArtifactHandler().getExtension()); } private Repackager getRepackager(File source) { Repackager repackager = new Repackager(source, this.layoutFactory); - repackager.addMainClassTimeoutWarningListener( - new LoggingMainClassTimeoutWarningListener()); + repackager.addMainClassTimeoutWarningListener(new LoggingMainClassTimeoutWarningListener()); repackager.setMainClass(this.mainClass); if (this.layout != null) { getLog().info("Layout: " + this.layout); @@ -299,8 +294,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { private LaunchScript getLaunchScript() throws IOException { if (this.executable || this.embeddedLaunchScript != null) { - return new DefaultLaunchScript(this.embeddedLaunchScript, - buildLaunchScriptProperties()); + return new DefaultLaunchScript(this.embeddedLaunchScript, buildLaunchScriptProperties()); } return null; } @@ -311,21 +305,17 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { properties.putAll(this.embeddedLaunchScriptProperties); } putIfMissing(properties, "initInfoProvides", this.project.getArtifactId()); - putIfMissing(properties, "initInfoShortDescription", this.project.getName(), - this.project.getArtifactId()); - putIfMissing(properties, "initInfoDescription", - removeLineBreaks(this.project.getDescription()), this.project.getName(), - this.project.getArtifactId()); + putIfMissing(properties, "initInfoShortDescription", this.project.getName(), this.project.getArtifactId()); + putIfMissing(properties, "initInfoDescription", removeLineBreaks(this.project.getDescription()), + this.project.getName(), this.project.getArtifactId()); return properties; } private String removeLineBreaks(String description) { - return (description != null) - ? WHITE_SPACE_PATTERN.matcher(description).replaceAll(" ") : null; + return (description != null) ? WHITE_SPACE_PATTERN.matcher(description).replaceAll(" ") : null; } - private void putIfMissing(Properties properties, String key, - String... valueCandidates) { + private void putIfMissing(Properties properties, String key, String... valueCandidates) { if (!properties.containsKey(key)) { for (String candidate : valueCandidates) { if (candidate != null && !candidate.isEmpty()) { @@ -341,35 +331,30 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { attachArtifact(source, target); } else if (source.getFile().equals(target) && original.exists()) { - String artifactId = (this.classifier != null) - ? "artifact with classifier " + this.classifier : "main artifact"; - getLog().info(String.format("Updating %s %s to %s", artifactId, - source.getFile(), original)); + String artifactId = (this.classifier != null) ? "artifact with classifier " + this.classifier + : "main artifact"; + getLog().info(String.format("Updating %s %s to %s", artifactId, source.getFile(), original)); source.setFile(original); } else if (this.classifier != null) { - getLog().info("Creating repackaged archive " + target + " with classifier " - + this.classifier); + getLog().info("Creating repackaged archive " + target + " with classifier " + this.classifier); } } private void attachArtifact(Artifact source, File target) { if (this.classifier != null && !source.getFile().equals(target)) { - getLog().info("Attaching repackaged archive " + target + " with classifier " - + this.classifier); - this.projectHelper.attachArtifact(this.project, this.project.getPackaging(), - this.classifier, target); + getLog().info("Attaching repackaged archive " + target + " with classifier " + this.classifier); + this.projectHelper.attachArtifact(this.project, this.project.getPackaging(), this.classifier, target); } else { - String artifactId = (this.classifier != null) - ? "artifact with classifier " + this.classifier : "main artifact"; + String artifactId = (this.classifier != null) ? "artifact with classifier " + this.classifier + : "main artifact"; getLog().info("Replacing " + artifactId + " with repackaged archive"); source.setFile(target); } } - private class LoggingMainClassTimeoutWarningListener - implements MainClassTimeoutWarningListener { + private class LoggingMainClassTimeoutWarningListener implements MainClassTimeoutWarningListener { @Override public void handleTimeoutWarning(long duration, String mainMethod) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java index 86bf12d8f10..9801c424fc3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ class RunArguments { return CommandLineUtils.translateCommandline(arguments); } catch (Exception ex) { - throw new IllegalArgumentException( - "Failed to parse arguments [" + arguments + "]", ex); + throw new IllegalArgumentException("Failed to parse arguments [" + arguments + "]", ex); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java index 29420c733ba..31d2388e2d5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java @@ -86,23 +86,20 @@ public class RunMojo extends AbstractRunMojo { } @Override - protected void runWithForkedJvm(File workingDirectory, List args, - Map environmentVariables) throws MojoExecutionException { + protected void runWithForkedJvm(File workingDirectory, List args, Map environmentVariables) + throws MojoExecutionException { int exitCode = forkJvm(workingDirectory, args, environmentVariables); if (exitCode == 0 || exitCode == EXIT_CODE_SIGINT) { return; } - throw new MojoExecutionException( - "Application finished with exit code: " + exitCode); + throw new MojoExecutionException("Application finished with exit code: " + exitCode); } - private int forkJvm(File workingDirectory, List args, - Map environmentVariables) throws MojoExecutionException { + private int forkJvm(File workingDirectory, List args, Map environmentVariables) + throws MojoExecutionException { try { - RunProcess runProcess = new RunProcess(workingDirectory, - new JavaExecutable().toString()); - Runtime.getRuntime() - .addShutdownHook(new Thread(new RunProcessKiller(runProcess))); + RunProcess runProcess = new RunProcess(workingDirectory, new JavaExecutable().toString()); + Runtime.getRuntime().addShutdownHook(new Thread(new RunProcessKiller(runProcess))); return runProcess.run(true, args, environmentVariables); } catch (Exception ex) { @@ -111,11 +108,9 @@ public class RunMojo extends AbstractRunMojo { } @Override - protected void runWithMavenJvm(String startClassName, String... arguments) - throws MojoExecutionException { + protected void runWithMavenJvm(String startClassName, String... arguments) throws MojoExecutionException { IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(startClassName); - Thread launchThread = new Thread(threadGroup, - new LaunchRunner(startClassName, arguments), "main"); + Thread launchThread = new Thread(threadGroup, new LaunchRunner(startClassName, arguments), "main"); launchThread.setContextClassLoader(new URLClassLoader(getClassPathUrls())); launchThread.start(); join(threadGroup); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java index d5a0205eb17..6076779f924 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,12 +66,10 @@ class SpringApplicationAdminClient { return false; // Instance not available yet } catch (AttributeNotFoundException ex) { - throw new IllegalStateException("Unexpected: attribute 'Ready' not available", - ex); + throw new IllegalStateException("Unexpected: attribute 'Ready' not available", ex); } catch (ReflectionException ex) { - throw new MojoExecutionException("Failed to retrieve Ready attribute", - ex.getCause()); + throw new MojoExecutionException("Failed to retrieve Ready attribute", ex.getCause()); } catch (MBeanException | IOException ex) { throw new MojoExecutionException(ex.getMessage(), ex); @@ -84,8 +82,7 @@ class SpringApplicationAdminClient { * @throws IOException if an I/O error occurs * @throws InstanceNotFoundException if the lifecycle mbean cannot be found */ - public void stop() - throws MojoExecutionException, IOException, InstanceNotFoundException { + public void stop() throws MojoExecutionException, IOException, InstanceNotFoundException { try { this.connection.invoke(this.objectName, "shutdown", null, null); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java index 80f69089e01..d39d80d0960 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java @@ -50,8 +50,7 @@ import org.springframework.boot.loader.tools.RunProcess; * @since 1.3.0 * @see StopMojo */ -@Mojo(name = "start", requiresProject = true, - defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, +@Mojo(name = "start", requiresProject = true, defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.TEST) public class StartMojo extends AbstractRunMojo { @@ -90,8 +89,7 @@ public class StartMojo extends AbstractRunMojo { private final Object lock = new Object(); @Override - protected void runWithForkedJvm(File workingDirectory, List args, - Map environmentVariables) + protected void runWithForkedJvm(File workingDirectory, List args, Map environmentVariables) throws MojoExecutionException, MojoFailureException { RunProcess runProcess = runProcess(workingDirectory, args, environmentVariables); try { @@ -103,11 +101,10 @@ public class StartMojo extends AbstractRunMojo { } } - private RunProcess runProcess(File workingDirectory, List args, - Map environmentVariables) throws MojoExecutionException { + private RunProcess runProcess(File workingDirectory, List args, Map environmentVariables) + throws MojoExecutionException { try { - RunProcess runProcess = new RunProcess(workingDirectory, - new JavaExecutable().toString()); + RunProcess runProcess = new RunProcess(workingDirectory, new JavaExecutable().toString()); runProcess.run(false, args, environmentVariables); return runProcess; } @@ -121,8 +118,7 @@ public class StartMojo extends AbstractRunMojo { RunArguments applicationArguments = super.resolveApplicationArguments(); applicationArguments.getArgs().addLast(ENABLE_MBEAN_PROPERTY); if (isFork()) { - applicationArguments.getArgs() - .addLast(JMX_NAME_PROPERTY_PREFIX + this.jmxName); + applicationArguments.getArgs().addLast(JMX_NAME_PROPERTY_PREFIX + this.jmxName); } return applicationArguments; } @@ -143,18 +139,16 @@ public class StartMojo extends AbstractRunMojo { } @Override - protected void runWithMavenJvm(String startClassName, String... arguments) - throws MojoExecutionException { + protected void runWithMavenJvm(String startClassName, String... arguments) throws MojoExecutionException { IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(startClassName); - Thread launchThread = new Thread(threadGroup, - new LaunchRunner(startClassName, arguments), startClassName + ".main()"); + Thread launchThread = new Thread(threadGroup, new LaunchRunner(startClassName, arguments), + startClassName + ".main()"); launchThread.setContextClassLoader(new URLClassLoader(getClassPathUrls())); launchThread.start(); waitForSpringApplication(this.wait, this.maxAttempts); } - private void waitForSpringApplication(long wait, int maxAttempts) - throws MojoExecutionException { + private void waitForSpringApplication(long wait, int maxAttempts) throws MojoExecutionException { SpringApplicationAdminClient client = new SpringApplicationAdminClient( ManagementFactory.getPlatformMBeanServer(), this.jmxName); getLog().debug("Waiting for spring application to start..."); @@ -162,8 +156,7 @@ public class StartMojo extends AbstractRunMojo { if (client.isReady()) { return; } - String message = "Spring application is not ready yet, waiting " + wait - + "ms (attempt " + (i + 1) + ")"; + String message = "Spring application is not ready yet, waiting " + wait + "ms (attempt " + (i + 1) + ")"; getLog().debug(message); synchronized (this.lock) { try { @@ -171,18 +164,15 @@ public class StartMojo extends AbstractRunMojo { } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while waiting for Spring Boot app to start."); + throw new IllegalStateException("Interrupted while waiting for Spring Boot app to start."); } } } throw new MojoExecutionException( - "Spring application did not start before the configured timeout (" - + (wait * maxAttempts) + "ms"); + "Spring application did not start before the configured timeout (" + (wait * maxAttempts) + "ms"); } - private void waitForSpringApplication() - throws MojoFailureException, MojoExecutionException { + private void waitForSpringApplication() throws MojoFailureException, MojoExecutionException { try { if (isFork()) { waitForForkedSpringApplication(); @@ -192,26 +182,20 @@ public class StartMojo extends AbstractRunMojo { } } catch (IOException ex) { - throw new MojoFailureException("Could not contact Spring Boot application", - ex); + throw new MojoFailureException("Could not contact Spring Boot application", ex); } catch (Exception ex) { - throw new MojoExecutionException( - "Could not figure out if the application has started", ex); + throw new MojoExecutionException("Could not figure out if the application has started", ex); } } - private void waitForForkedSpringApplication() - throws IOException, MojoFailureException, MojoExecutionException { + private void waitForForkedSpringApplication() throws IOException, MojoFailureException, MojoExecutionException { try { getLog().debug("Connecting to local MBeanServer at port " + this.jmxPort); - try (JMXConnector connector = execute(this.wait, this.maxAttempts, - new CreateJmxConnector(this.jmxPort))) { + try (JMXConnector connector = execute(this.wait, this.maxAttempts, new CreateJmxConnector(this.jmxPort))) { if (connector == null) { - throw new MojoExecutionException( - "JMX MBean server was not reachable before the configured " - + "timeout (" + (this.wait * this.maxAttempts) - + "ms"); + throw new MojoExecutionException("JMX MBean server was not reachable before the configured " + + "timeout (" + (this.wait * this.maxAttempts) + "ms"); } getLog().debug("Connected to local MBeanServer at port " + this.jmxPort); MBeanServerConnection connection = connector.getMBeanServerConnection(); @@ -222,21 +206,18 @@ public class StartMojo extends AbstractRunMojo { throw ex; } catch (Exception ex) { - throw new MojoExecutionException( - "Failed to connect to MBean server at port " + this.jmxPort, ex); + throw new MojoExecutionException("Failed to connect to MBean server at port " + this.jmxPort, ex); } } private void doWaitForSpringApplication(MBeanServerConnection connection) throws IOException, MojoExecutionException, MojoFailureException { - final SpringApplicationAdminClient client = new SpringApplicationAdminClient( - connection, this.jmxName); + final SpringApplicationAdminClient client = new SpringApplicationAdminClient(connection, this.jmxName); try { execute(this.wait, this.maxAttempts, () -> (client.isReady() ? true : null)); } catch (ReflectionException ex) { - throw new MojoExecutionException("Unable to retrieve 'ready' attribute", - ex.getCause()); + throw new MojoExecutionException("Unable to retrieve 'ready' attribute", ex.getCause()); } catch (Exception ex) { throw new MojoFailureException("Could not invoke shutdown operation", ex); @@ -253,16 +234,14 @@ public class StartMojo extends AbstractRunMojo { * @return the result * @throws Exception in case of execution errors */ - public T execute(long wait, int maxAttempts, Callable callback) - throws Exception { + public T execute(long wait, int maxAttempts, Callable callback) throws Exception { getLog().debug("Waiting for spring application to start..."); for (int i = 0; i < maxAttempts; i++) { T result = callback.call(); if (result != null) { return result; } - String message = "Spring application is not ready yet, waiting " + wait - + "ms (attempt " + (i + 1) + ")"; + String message = "Spring application is not ready yet, waiting " + wait + "ms (attempt " + (i + 1) + ")"; getLog().debug(message); synchronized (this.lock) { try { @@ -270,14 +249,12 @@ public class StartMojo extends AbstractRunMojo { } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while waiting for Spring Boot app to start."); + throw new IllegalStateException("Interrupted while waiting for Spring Boot app to start."); } } } throw new MojoExecutionException( - "Spring application did not start before the configured " + "timeout (" - + (wait * maxAttempts) + "ms"); + "Spring application did not start before the configured " + "timeout (" + (wait * maxAttempts) + "ms"); } private class CreateJmxConnector implements Callable { @@ -295,8 +272,7 @@ public class StartMojo extends AbstractRunMojo { } catch (IOException ex) { if (hasCauseWithType(ex, ConnectException.class)) { - String message = "MBean server at port " + this.port - + " is not up yet..."; + String message = "MBean server at port " + this.port + " is not up yet..."; getLog().debug(message); return null; } @@ -305,8 +281,7 @@ public class StartMojo extends AbstractRunMojo { } private boolean hasCauseWithType(Throwable t, Class type) { - return type.isAssignableFrom(t.getClass()) - || t.getCause() != null && hasCauseWithType(t.getCause(), type); + return type.isAssignableFrom(t.getClass()) || t.getCause() != null && hasCauseWithType(t.getCause(), type); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java index 05714b09749..ff8567937ac 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java @@ -38,8 +38,7 @@ import org.apache.maven.project.MavenProject; * @author Stephane Nicoll * @since 1.3.0 */ -@Mojo(name = "stop", requiresProject = true, - defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST) +@Mojo(name = "stop", requiresProject = true, defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST) public class StopMojo extends AbstractMojo { /** @@ -104,15 +103,12 @@ public class StopMojo extends AbstractMojo { if (this.fork != null) { return this.fork; } - String property = this.project.getProperties() - .getProperty("_spring.boot.fork.enabled"); + String property = this.project.getProperties().getProperty("_spring.boot.fork.enabled"); return Boolean.valueOf(property); } - private void stopForkedProcess() - throws IOException, MojoFailureException, MojoExecutionException { - try (JMXConnector connector = SpringApplicationAdminClient - .connect(this.jmxPort)) { + private void stopForkedProcess() throws IOException, MojoFailureException, MojoExecutionException { + try (JMXConnector connector = SpringApplicationAdminClient.connect(this.jmxPort)) { MBeanServerConnection connection = connector.getMBeanServerConnection(); doStop(connection); } @@ -122,16 +118,13 @@ public class StopMojo extends AbstractMojo { doStop(ManagementFactory.getPlatformMBeanServer()); } - private void doStop(MBeanServerConnection connection) - throws IOException, MojoExecutionException { + private void doStop(MBeanServerConnection connection) throws IOException, MojoExecutionException { try { new SpringApplicationAdminClient(connection, this.jmxName).stop(); } catch (InstanceNotFoundException ex) { - throw new MojoExecutionException( - "Spring application lifecycle JMX bean not found (fork is " - + this.fork + "). Could not stop application gracefully", - ex); + throw new MojoExecutionException("Spring application lifecycle JMX bean not found (fork is " + this.fork + + "). Could not stop application gracefully", ex); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java index df5b90a0e85..1cfec166e81 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,8 +99,7 @@ public class ArtifactsLibrariesTests { Dependency unpack = new Dependency(); unpack.setGroupId("gid"); unpack.setArtifactId("aid"); - this.libs = new ArtifactsLibraries(this.artifacts, Collections.singleton(unpack), - mock(Log.class)); + this.libs = new ArtifactsLibraries(this.artifacts, Collections.singleton(unpack), mock(Log.class)); this.libs.doWithLibraries(this.callback); verify(this.callback).library(this.libraryCaptor.capture()); assertThat(this.libraryCaptor.getValue().isUnpackRequired()).isTrue(); @@ -128,10 +127,8 @@ public class ArtifactsLibrariesTests { this.libs = new ArtifactsLibraries(this.artifacts, null, mock(Log.class)); this.libs.doWithLibraries(this.callback); verify(this.callback, times(2)).library(this.libraryCaptor.capture()); - assertThat(this.libraryCaptor.getAllValues().get(0).getName()) - .isEqualTo("g1-artifact-1.0.jar"); - assertThat(this.libraryCaptor.getAllValues().get(1).getName()) - .isEqualTo("g2-artifact-1.0.jar"); + assertThat(this.libraryCaptor.getAllValues().get(0).getName()).isEqualTo("g1-artifact-1.0.jar"); + assertThat(this.libraryCaptor.getAllValues().get(1).getName()).isEqualTo("g2-artifact-1.0.jar"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java index 0a7cd4ad31a..5d8091e3a0c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,34 +41,29 @@ public class DependencyFilterMojoTests { @Test public void filterDependencies() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.emptyList(), "com.foo"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo"); Artifact artifact = createArtifact("com.bar", "one"); - Set artifacts = mojo.filterDependencies( - createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), - artifact); + Set artifacts = mojo.filterDependencies(createArtifact("com.foo", "one"), + createArtifact("com.foo", "two"), artifact); assertThat(artifacts).hasSize(1); assertThat(artifacts.iterator().next()).isSameAs(artifact); } @Test public void filterGroupIdExactMatch() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.emptyList(), "com.foo"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo"); Artifact artifact = createArtifact("com.foo.bar", "one"); - Set artifacts = mojo.filterDependencies( - createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), - artifact); + Set artifacts = mojo.filterDependencies(createArtifact("com.foo", "one"), + createArtifact("com.foo", "two"), artifact); assertThat(artifacts).hasSize(1); assertThat(artifacts.iterator().next()).isSameAs(artifact); } @Test public void filterScopeKeepOrder() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.emptyList(), "", + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "", new ScopeFilter(null, Artifact.SCOPE_SYSTEM)); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.foo", "two", Artifact.SCOPE_SYSTEM); @@ -79,8 +74,7 @@ public class DependencyFilterMojoTests { @Test public void filterGroupIdKeepOrder() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.emptyList(), "com.foo"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo"); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.bar", "two"); Artifact three = createArtifact("com.bar", "three"); @@ -94,8 +88,7 @@ public class DependencyFilterMojoTests { Exclude exclude = new Exclude(); exclude.setGroupId("com.bar"); exclude.setArtifactId("two"); - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.singletonList(exclude), ""); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.singletonList(exclude), ""); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.bar", "two"); Artifact three = createArtifact("com.bar", "three"); @@ -108,8 +101,7 @@ public class DependencyFilterMojoTests { return createArtifact(groupId, artifactId, null); } - private static Artifact createArtifact(String groupId, String artifactId, - String scope) { + private static Artifact createArtifact(String groupId, String artifactId, String scope) { Artifact a = mock(Artifact.class); given(a.getGroupId()).willReturn(groupId); given(a.getArtifactId()).willReturn(artifactId); @@ -119,20 +111,18 @@ public class DependencyFilterMojoTests { return a; } - private static final class TestableDependencyFilterMojo - extends AbstractDependencyFilterMojo { + private static final class TestableDependencyFilterMojo extends AbstractDependencyFilterMojo { private final ArtifactsFilter[] additionalFilters; - private TestableDependencyFilterMojo(List excludes, - String excludeGroupIds, ArtifactsFilter... additionalFilters) { + private TestableDependencyFilterMojo(List excludes, String excludeGroupIds, + ArtifactsFilter... additionalFilters) { setExcludes(excludes); setExcludeGroupIds(excludeGroupIds); this.additionalFilters = additionalFilters; } - public Set filterDependencies(Artifact... artifacts) - throws MojoExecutionException { + public Set filterDependencies(Artifact... artifacts) throws MojoExecutionException { Set input = new LinkedHashSet<>(Arrays.asList(artifacts)); return filterDependencies(input, getFilters(this.additionalFilters)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java index 8a0d248dfa2..a8770c1f4f9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,15 +39,14 @@ public class EnvVariablesTests { @Test public void asArray() { - assertThat(new EnvVariables(getTestArgs()).asArray()).contains("key=My Value", - "key1= tt ", "key2= ", "key3="); + assertThat(new EnvVariables(getTestArgs()).asArray()).contains("key=My Value", "key1= tt ", "key2= ", + "key3="); } @Test public void asMap() { - assertThat(new EnvVariables(getTestArgs()).asMap()).containsExactly( - entry("key", "My Value"), entry("key1", " tt "), entry("key2", " "), - entry("key3", "")); + assertThat(new EnvVariables(getTestArgs()).asMap()).containsExactly(entry("key", "My Value"), + entry("key1", " tt "), entry("key2", " "), entry("key3", "")); } private Map getTestArgs() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java index 1f19097ca0d..995df1d0325 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,17 +40,14 @@ public class ExcludeFilterTests { @Test public void excludeSimple() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar"))); - Set result = filter - .filter(Collections.singleton(createArtifact("com.foo", "bar"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); + Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar"))); assertThat(result).isEmpty(); } @Test public void excludeGroupIdNoMatch() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -59,8 +56,7 @@ public class ExcludeFilterTests { @Test public void excludeArtifactIdNoMatch() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -69,17 +65,14 @@ public class ExcludeFilterTests { @Test public void excludeClassifier() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); - Set result = filter - .filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); + Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); assertThat(result).isEmpty(); } @Test public void excludeClassifierNoTargetClassifier() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -88,8 +81,7 @@ public class ExcludeFilterTests { @Test public void excludeClassifierNoMatch() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -98,9 +90,8 @@ public class ExcludeFilterTests { @Test public void excludeMulti() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter(Arrays.asList( - createExclude("com.foo", "bar"), createExclude("com.foo", "bar2"), - createExclude("org.acme", "app"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"), + createExclude("com.foo", "bar2"), createExclude("org.acme", "app"))); Set artifacts = new HashSet<>(); artifacts.add(createArtifact("com.foo", "bar")); artifacts.add(createArtifact("com.foo", "bar")); @@ -125,8 +116,7 @@ public class ExcludeFilterTests { return exclude; } - private Artifact createArtifact(String groupId, String artifactId, - String classifier) { + private Artifact createArtifact(String groupId, String artifactId, String classifier) { Artifact a = mock(Artifact.class); given(a.getGroupId()).willReturn(groupId); given(a.getArtifactId()).willReturn(artifactId); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java index c6713fe54bf..c07ecfce002 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public class IncludeFilterTests { @Test public void includeSimple() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -49,8 +48,7 @@ public class IncludeFilterTests { @Test public void includeGroupIdNoMatch() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -58,8 +56,7 @@ public class IncludeFilterTests { @Test public void includeArtifactIdNoMatch() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -67,8 +64,7 @@ public class IncludeFilterTests { @Test public void includeClassifier() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk5"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -77,8 +73,7 @@ public class IncludeFilterTests { @Test public void includeClassifierNoTargetClassifier() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -86,8 +81,7 @@ public class IncludeFilterTests { @Test public void includeClassifierNoMatch() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -95,9 +89,8 @@ public class IncludeFilterTests { @Test public void includeMulti() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter(Arrays.asList( - createInclude("com.foo", "bar"), createInclude("com.foo", "bar2"), - createInclude("org.acme", "app"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"), + createInclude("com.foo", "bar2"), createInclude("org.acme", "app"))); Set artifacts = new HashSet<>(); artifacts.add(createArtifact("com.foo", "bar")); artifacts.add(createArtifact("com.foo", "bar")); @@ -121,8 +114,7 @@ public class IncludeFilterTests { return include; } - private Artifact createArtifact(String groupId, String artifactId, - String classifier) { + private Artifact createArtifact(String groupId, String artifactId, String classifier) { Artifact a = mock(Artifact.class); given(a.getGroupId()).willReturn(groupId); given(a.getArtifactId()).willReturn(artifactId); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java index 95cd7f809b1..bb3ea1cb9ea 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,25 +36,21 @@ public class PropertiesMergingResourceTransformerTests { @Test public void testProcess() throws Exception { assertThat(this.transformer.hasTransformedResource()).isFalse(); - this.transformer.processResource("foo", - new ByteArrayInputStream("foo=bar".getBytes()), null); + this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); assertThat(this.transformer.hasTransformedResource()).isTrue(); } @Test public void testMerge() throws Exception { - this.transformer.processResource("foo", - new ByteArrayInputStream("foo=bar".getBytes()), null); - this.transformer.processResource("bar", - new ByteArrayInputStream("foo=spam".getBytes()), null); + this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); + this.transformer.processResource("bar", new ByteArrayInputStream("foo=spam".getBytes()), null); assertThat(this.transformer.getData().getProperty("foo")).isEqualTo("bar,spam"); } @Test public void testOutput() throws Exception { this.transformer.setResource("foo"); - this.transformer.processResource("foo", - new ByteArrayInputStream("foo=bar".getBytes()), null); + this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); ByteArrayOutputStream out = new ByteArrayOutputStream(); JarOutputStream os = new JarOutputStream(out); this.transformer.modifyOutputStream(os); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java index a1ce4e035fc..6a7843ddd04 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,12 +64,10 @@ public class RunArgumentsTests { @Test public void parseDebugFlags() { - String[] args = parseArgs( - "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); + String[] args = parseArgs("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); assertThat(args.length).isEqualTo(2); assertThat(args[0]).isEqualTo("-Xdebug"); - assertThat(args[1]).isEqualTo( - "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); + assertThat(args[1]).isEqualTo("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java index 047dbcec50c..075bd381178 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public class SystemPropertyFormatterTests { @Test public void parseKeyWithValue() { - assertThat(SystemPropertyFormatter.format("key1", "value1")) - .isEqualTo("-Dkey1=\"value1\""); + assertThat(SystemPropertyFormatter.format("key1", "value1")).isEqualTo("-Dkey1=\"value1\""); } @Test @@ -50,8 +49,7 @@ public class SystemPropertyFormatterTests { @Test public void parseKeyWithOnlySpaces() { - assertThat(SystemPropertyFormatter.format("key1", " ")) - .isEqualTo("-Dkey1=\" \""); + assertThat(SystemPropertyFormatter.format("key1", " ")).isEqualTo("-Dkey1=\" \""); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java index c8e3bad5d57..864f7e1e06b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java @@ -51,13 +51,12 @@ public final class Verify { new JarArchiveVerification(file, SAMPLE_APP).verify(); } - public static void verifyJar(File file, String main, String... scriptContents) - throws Exception { + public static void verifyJar(File file, String main, String... scriptContents) throws Exception { verifyJar(file, main, true, scriptContents); } - public static void verifyJar(File file, String main, boolean executable, - String... scriptContents) throws Exception { + public static void verifyJar(File file, String main, boolean executable, String... scriptContents) + throws Exception { new JarArchiveVerification(file, main).verify(executable, scriptContents); } @@ -73,8 +72,8 @@ public final class Verify { new ModuleArchiveVerification(file).verify(); } - public static Properties verifyBuildInfo(File file, String group, String artifact, - String name, String version) throws IOException { + public static Properties verifyBuildInfo(File file, String group, String artifact, String name, String version) + throws IOException { FileSystemResource resource = new FileSystemResource(file); Properties properties = PropertiesLoaderUtils.loadProperties(resource); assertThat(properties.get("build.group")).isEqualTo(group); @@ -112,21 +111,18 @@ public final class Verify { public void assertHasNoEntryNameStartingWith(String entry) { for (String name : this.content.keySet()) { if (name.startsWith(entry)) { - throw new IllegalStateException("Entry starting with " + entry - + " should not have been found"); + throw new IllegalStateException("Entry starting with " + entry + " should not have been found"); } } } public void assertHasNonUnpackEntry(String entryName) { - assertThat(hasNonUnpackEntry(entryName)) - .as("Entry starting with " + entryName + " was an UNPACK entry") + assertThat(hasNonUnpackEntry(entryName)).as("Entry starting with " + entryName + " was an UNPACK entry") .isTrue(); } public void assertHasUnpackEntry(String entryName) { - assertThat(hasUnpackEntry(entryName)) - .as("Entry starting with " + entryName + " was not an UNPACK entry") + assertThat(hasUnpackEntry(entryName)).as("Entry starting with " + entryName + " was not an UNPACK entry") .isTrue(); } @@ -140,11 +136,9 @@ public final class Verify { } private ZipEntry getEntryStartingWith(String entryName) { - return this.content.entrySet().stream() - .filter((entry) -> entry.getKey().startsWith(entryName)) + return this.content.entrySet().stream().filter((entry) -> entry.getKey().startsWith(entryName)) .map(Map.Entry::getValue).findFirst() - .orElseThrow(() -> new IllegalStateException( - "Unable to find entry starting with " + entryName)); + .orElseThrow(() -> new IllegalStateException("Unable to find entry starting with " + entryName)); } public boolean hasEntry(String entry) { @@ -177,14 +171,12 @@ public final class Verify { verify(true); } - public void verify(boolean executable, String... scriptContents) - throws Exception { + public void verify(boolean executable, String... scriptContents) throws Exception { assertThat(this.file).exists().isFile(); if (scriptContents.length > 0 && executable) { String contents = contentOf(this.file); - contents = contents.substring(0, contents - .indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); + contents = contents.substring(0, contents.indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); for (String content : scriptContents) { assertThat(contents).contains(content); } @@ -192,8 +184,7 @@ public final class Verify { if (!executable) { String contents = contentOf(this.file); - assertThat(contents).as("Is executable") - .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); + assertThat(contents).as("Is executable").startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); } try (ZipFile zipFile = new ZipFile(this.file)) { @@ -207,8 +198,7 @@ public final class Verify { } private void verifyManifest(ArchiveVerifier verifier) throws Exception { - Manifest manifest = new Manifest( - verifier.getEntryContent("META-INF/MANIFEST.MF")); + Manifest manifest = new Manifest(verifier.getEntryContent("META-INF/MANIFEST.MF")); verifyManifest(manifest); } @@ -231,22 +221,18 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("BOOT-INF/lib/spring-context"); verifier.assertHasEntryNameStartingWith("BOOT-INF/lib/spring-core"); verifier.assertHasEntryNameStartingWith("BOOT-INF/lib/jakarta.servlet-api-4"); - assertThat(verifier - .hasEntry("org/springframework/boot/loader/JarLauncher.class")) - .as("Unpacked launcher classes").isTrue(); - assertThat(verifier - .hasEntry("BOOT-INF/classes/org/test/SampleApplication.class")) - .as("Own classes").isTrue(); + assertThat(verifier.hasEntry("org/springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isTrue(); + assertThat(verifier.hasEntry("BOOT-INF/classes/org/test/SampleApplication.class")).as("Own classes") + .isTrue(); } @Override protected void verifyManifest(Manifest manifest) throws Exception { assertThat(manifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(manifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo(this.main); - assertThat(manifest.getMainAttributes().getValue("Not-Used")) - .isEqualTo("Foo"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")).isEqualTo(this.main); + assertThat(manifest.getMainAttributes().getValue("Not-Used")).isEqualTo("Foo"); } } @@ -262,14 +248,11 @@ public final class Verify { super.verifyZipEntries(verifier); verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-context"); verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-core"); - verifier.assertHasEntryNameStartingWith( - "WEB-INF/lib-provided/jakarta.servlet-api-4"); - assertThat(verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) - .as("Unpacked launcher classes").isTrue(); - assertThat(verifier - .hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")) - .as("Own classes").isTrue(); + verifier.assertHasEntryNameStartingWith("WEB-INF/lib-provided/jakarta.servlet-api-4"); + assertThat(verifier.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isTrue(); + assertThat(verifier.hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")).as("Own classes") + .isTrue(); assertThat(verifier.hasEntry("index.html")).as("Web content").isTrue(); } @@ -277,10 +260,8 @@ public final class Verify { protected void verifyManifest(Manifest manifest) throws Exception { assertThat(manifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.WarLauncher"); - assertThat(manifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("org.test.SampleApplication"); - assertThat(manifest.getMainAttributes().getValue("Not-Used")) - .isEqualTo("Foo"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")).isEqualTo("org.test.SampleApplication"); + assertThat(manifest.getMainAttributes().getValue("Not-Used")).isEqualTo("Foo"); } } @@ -295,10 +276,8 @@ public final class Verify { protected void verifyManifest(Manifest manifest) throws Exception { assertThat(manifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); - assertThat(manifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("org.test.SampleApplication"); - assertThat(manifest.getMainAttributes().getValue("Not-Used")) - .isEqualTo("Foo"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")).isEqualTo("org.test.SampleApplication"); + assertThat(manifest.getMainAttributes().getValue("Not-Used")).isEqualTo("Foo"); } } @@ -315,11 +294,9 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("lib/spring-context"); verifier.assertHasEntryNameStartingWith("lib/spring-core"); verifier.assertHasNoEntryNameStartingWith("lib/jakarta.servlet-api"); - assertThat(verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) - .as("Unpacked launcher classes").isFalse(); - assertThat(verifier.hasEntry("org/" + "test/SampleModule.class")) - .as("Own classes").isTrue(); + assertThat(verifier.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isFalse(); + assertThat(verifier.hasEntry("org/" + "test/SampleModule.class")).as("Own classes").isTrue(); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/BuildOutput.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/BuildOutput.java index 1fe19ef8204..040b8ea54ae 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/BuildOutput.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/BuildOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,17 +38,14 @@ public class BuildOutput { */ public File getTestClassesLocation() { try { - File location = new File(this.testClass.getProtectionDomain().getCodeSource() - .getLocation().toURI()); + File location = new File(this.testClass.getProtectionDomain().getCodeSource().getLocation().toURI()); if (location.getPath().endsWith(path("target", "test-classes"))) { return location; } - throw new IllegalStateException( - "Unexpected test classes location '" + location + "'"); + throw new IllegalStateException("Unexpected test classes location '" + location + "'"); } catch (URISyntaxException ex) { - throw new IllegalStateException("Invalid test class code source location", - ex); + throw new IllegalStateException("Invalid test class code source location", ex); } } @@ -62,8 +59,7 @@ public class BuildOutput { return testClassesLocation; } throw new IllegalStateException( - "Cannot determine test resources location from classes location '" - + testClassesLocation + "'"); + "Cannot determine test resources location from classes location '" + testClassesLocation + "'"); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java index 2a5834869a3..6602dda9a62 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,7 @@ public class TestCompiler { this(ToolProvider.getSystemJavaCompiler(), temporaryFolder); } - public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) - throws IOException { + public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) throws IOException { this.compiler = compiler; this.fileManager = compiler.getStandardFileManager(null, null, null); this.outputLocation = temporaryFolder.newFolder(); @@ -66,8 +65,7 @@ public class TestCompiler { } public TestCompilationTask getTask(Collection sourceFiles) { - Iterable javaFileObjects = this.fileManager - .getJavaFileObjectsFromFiles(sourceFiles); + Iterable javaFileObjects = this.fileManager.getJavaFileObjectsFromFiles(sourceFiles); return getTask(javaFileObjects); } @@ -76,10 +74,9 @@ public class TestCompiler { return getTask(javaFileObjects); } - private TestCompilationTask getTask( - Iterable javaFileObjects) { - return new TestCompilationTask(this.compiler.getTask(null, this.fileManager, null, - null, null, javaFileObjects)); + private TestCompilationTask getTask(Iterable javaFileObjects) { + return new TestCompilationTask( + this.compiler.getTask(null, this.fileManager, null, null, null, javaFileObjects)); } public File getOutputLocation() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java index 3a77e37fb75..8fa95a18ad1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,12 +52,11 @@ public abstract class AbstractConfigurationClassTests { public void allBeanMethodsArePublic() throws IOException { Set nonPublicBeanMethods = new HashSet<>(); for (AnnotationMetadata configurationClass : findConfigurationClasses()) { - Set beanMethods = configurationClass - .getAnnotatedMethods(Bean.class.getName()); + Set beanMethods = configurationClass.getAnnotatedMethods(Bean.class.getName()); for (MethodMetadata methodMetadata : beanMethods) { if (!isPublic(methodMetadata)) { - nonPublicBeanMethods.add(methodMetadata.getDeclaringClassName() + "." - + methodMetadata.getMethodName()); + nonPublicBeanMethods + .add(methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName()); } } } @@ -66,16 +65,13 @@ public abstract class AbstractConfigurationClassTests { private Set findConfigurationClasses() throws IOException { Set configurationClasses = new HashSet<>(); - Resource[] resources = this.resolver.getResources("classpath*:" - + getClass().getPackage().getName().replace('.', '/') + "/**/*.class"); + Resource[] resources = this.resolver + .getResources("classpath*:" + getClass().getPackage().getName().replace('.', '/') + "/**/*.class"); for (Resource resource : resources) { if (!isTestClass(resource)) { - MetadataReader metadataReader = new SimpleMetadataReaderFactory() - .getMetadataReader(resource); - AnnotationMetadata annotationMetadata = metadataReader - .getAnnotationMetadata(); - if (annotationMetadata.getAnnotationTypes() - .contains(Configuration.class.getName())) { + MetadataReader metadataReader = new SimpleMetadataReaderFactory().getMetadataReader(resource); + AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); + if (annotationMetadata.getAnnotationTypes().contains(Configuration.class.getName())) { configurationClasses.add(annotationMetadata); } } @@ -89,8 +85,7 @@ public abstract class AbstractConfigurationClassTests { } private boolean isPublic(MethodMetadata methodMetadata) { - int access = (Integer) new DirectFieldAccessor(methodMetadata) - .getPropertyValue("access"); + int access = (Integer) new DirectFieldAccessor(methodMetadata).getPropertyValue("access"); return (access & Opcodes.ACC_PUBLIC) != 0; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java index 17285b23939..afdbdcafedd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java @@ -70,8 +70,7 @@ import org.springframework.util.StringUtils; */ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { - private static final Pattern INTELLIJ_CLASSPATH_JAR_PATTERN = Pattern - .compile(".*classpath(\\d+)?\\.jar"); + private static final Pattern INTELLIJ_CLASSPATH_JAR_PATTERN = Pattern.compile(".*classpath(\\d+)?\\.jar"); public ModifiedClassPathRunner(Class testClass) throws InitializationError { super(testClass); @@ -91,15 +90,14 @@ 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 { ClassLoader classLoader = this.getClass().getClassLoader(); - return new ModifiedClassPathClassLoader( - processUrls(extractUrls(classLoader), testClass), classLoader.getParent(), - classLoader); + return new ModifiedClassPathClassLoader(processUrls(extractUrls(classLoader), testClass), + classLoader.getParent(), classLoader); } private URL[] extractUrls(ClassLoader classLoader) throws Exception { @@ -119,8 +117,8 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { if (classLoader instanceof URLClassLoader) { return Stream.of(((URLClassLoader) classLoader).getURLs()); } - return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath() - .split(File.pathSeparator)).map(this::toURL); + return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) + .map(this::toURL); } private URL toURL(String entry) { @@ -170,8 +168,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private String[] getClassPath(URL booterJar) throws Exception { Attributes attributes = getManifestMainAttributesFromUrl(booterJar); - return StringUtils.delimitedListToStringArray( - attributes.getValue(Attributes.Name.CLASS_PATH), " "); + return StringUtils.delimitedListToStringArray(attributes.getValue(Attributes.Name.CLASS_PATH), " "); } private Attributes getManifestMainAttributesFromUrl(URL url) throws Exception { @@ -181,13 +178,10 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private URL[] processUrls(URL[] urls, Class testClass) throws Exception { - MergedAnnotations annotations = MergedAnnotations.from(testClass, - SearchStrategy.EXHAUSTIVE); - ClassPathEntryFilter filter = new ClassPathEntryFilter( - annotations.get(ClassPathExclusions.class)); + MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE); + ClassPathEntryFilter filter = new ClassPathEntryFilter(annotations.get(ClassPathExclusions.class)); List processedUrls = new ArrayList<>(); - List additionalUrls = getAdditionalUrls( - annotations.get(ClassPathOverrides.class)); + List additionalUrls = getAdditionalUrls(annotations.get(ClassPathOverrides.class)); processedUrls.addAll(additionalUrls); for (URL url : urls) { if (!filter.isExcluded(url)) { @@ -197,8 +191,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { return processedUrls.toArray(new URL[0]); } - private List getAdditionalUrls(MergedAnnotation annotation) - throws Exception { + private List getAdditionalUrls(MergedAnnotation annotation) throws Exception { if (!annotation.isPresent()) { return Collections.emptyList(); } @@ -206,26 +199,19 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private List resolveCoordinates(String[] coordinates) throws Exception { - DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils - .newServiceLocator(); - serviceLocator.addService(RepositoryConnectorFactory.class, - BasicRepositoryConnectorFactory.class); + DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils.newServiceLocator(); + serviceLocator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); serviceLocator.addService(TransporterFactory.class, HttpTransporterFactory.class); - RepositorySystem repositorySystem = serviceLocator - .getService(RepositorySystem.class); + RepositorySystem repositorySystem = serviceLocator.getService(RepositorySystem.class); 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(new RemoteRepository.Builder("central", "default", - "https://repo.maven.apache.org/maven2").build())); + LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); + session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); + CollectRequest collectRequest = new CollectRequest(null, Arrays.asList( + new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2").build())); collectRequest.setDependencies(createDependencies(coordinates)); DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); - DependencyResult result = repositorySystem.resolveDependencies(session, - dependencyRequest); + DependencyResult result = repositorySystem.resolveDependencies(session, dependencyRequest); List resolvedArtifacts = new ArrayList<>(); for (ArtifactResult artifact : result.getArtifactResults()) { resolvedArtifacts.add(artifact.getArtifact().getFile().toURI().toURL()); @@ -250,13 +236,11 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final AntPathMatcher matcher = new AntPathMatcher(); - private ClassPathEntryFilter(MergedAnnotation annotation) - throws Exception { + private ClassPathEntryFilter(MergedAnnotation annotation) throws Exception { this.exclusions = new ArrayList<>(); this.exclusions.add("log4j-*.jar"); if (annotation.isPresent()) { - this.exclusions.addAll( - Arrays.asList(annotation.getStringArray(MergedAnnotation.VALUE))); + this.exclusions.addAll(Arrays.asList(annotation.getStringArray(MergedAnnotation.VALUE))); } } @@ -282,15 +266,13 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final ClassLoader classLoader; - ModifiedClassPathTestClass(ClassLoader classLoader, String testClassName) - throws ClassNotFoundException { + ModifiedClassPathTestClass(ClassLoader classLoader, String testClassName) throws ClassNotFoundException { super(classLoader.loadClass(testClassName)); this.classLoader = classLoader; } @Override - public List getAnnotatedMethods( - Class annotationClass) { + public List getAnnotatedMethods(Class annotationClass) { try { return getAnnotatedMethods(annotationClass.getName()); } @@ -300,28 +282,24 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } @SuppressWarnings("unchecked") - private List getAnnotatedMethods(String annotationClassName) - throws ClassNotFoundException { + private List getAnnotatedMethods(String annotationClassName) throws ClassNotFoundException { Class annotationClass = (Class) this.classLoader .loadClass(annotationClassName); List methods = super.getAnnotatedMethods(annotationClass); return wrapFrameworkMethods(methods); } - private List wrapFrameworkMethods( - List methods) { + private List wrapFrameworkMethods(List methods) { List wrapped = new ArrayList<>(methods.size()); for (FrameworkMethod frameworkMethod : methods) { - wrapped.add(new ModifiedClassPathFrameworkMethod( - frameworkMethod.getMethod())); + wrapped.add(new ModifiedClassPathFrameworkMethod(frameworkMethod.getMethod())); } return wrapped; } private T doWithModifiedClassPathThreadContextClassLoader( ModifiedClassPathTcclAction action) throws E { - ClassLoader originalClassLoader = Thread.currentThread() - .getContextClassLoader(); + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.classLoader); try { return action.perform(); @@ -352,11 +330,9 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } @Override - public Object invokeExplosively(Object target, Object... params) - throws Throwable { + public Object invokeExplosively(Object target, Object... params) throws Throwable { return doWithModifiedClassPathThreadContextClassLoader( - () -> ModifiedClassPathFrameworkMethod.super.invokeExplosively( - target, params)); + () -> ModifiedClassPathFrameworkMethod.super.invokeExplosively(target, params)); } } @@ -370,8 +346,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final ClassLoader junitLoader; - ModifiedClassPathClassLoader(URL[] urls, ClassLoader parent, - ClassLoader junitLoader) { + ModifiedClassPathClassLoader(URL[] urls, ClassLoader parent, ClassLoader junitLoader) { super(urls, parent); this.junitLoader = junitLoader; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java index 61ed4b75668..0c3924147e5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java @@ -45,12 +45,10 @@ class Container implements Startable { } @SuppressWarnings({ "unchecked", "resource" }) - > Container(String dockerImageName, int port, - Consumer customizer) { + > Container(String dockerImageName, int port, Consumer customizer) { this.port = port; this.containerFactory = () -> { - T container = (T) new GenericContainer<>(dockerImageName) - .withExposedPorts(port); + T container = (T) new GenericContainer<>(dockerImageName).withExposedPorts(port); if (customizer != null) { customizer.accept(container); } @@ -68,8 +66,7 @@ class Container implements Startable { @Override public void start() { - Assumptions.assumeTrue(isDockerRunning(), - "Could not find valid docker environment."); + Assumptions.assumeTrue(isDockerRunning(), "Could not find valid docker environment."); this.container = this.containerFactory.get(); this.container.start(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java index b94627bc425..b040fe0bb2c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java @@ -26,10 +26,8 @@ import java.time.Duration; public class ElasticsearchContainer extends Container { public ElasticsearchContainer() { - super("elasticsearch:6.7.2", 9200, - (container) -> container.withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(5).withEnv("discovery.type", "single-node") - .addExposedPorts(9200, 9300)); + super("elasticsearch:6.7.2", 9200, (container) -> container.withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(5).withEnv("discovery.type", "single-node").addExposedPorts(9200, 9300)); } public int getMappedTransportPort() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java index a7f9b9ffb3f..0d91d18e7ed 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java @@ -43,16 +43,14 @@ public class SkippableContainer> implements Starta public T getContainer() { if (this.container == null) { - throw new IllegalStateException( - "Container cannot be accessed prior to test invocation"); + throw new IllegalStateException("Container cannot be accessed prior to test invocation"); } return this.container; } @Override public void start() { - Assumptions.assumeTrue(isDockerRunning(), - "Could not find valid docker environment."); + Assumptions.assumeTrue(isDockerRunning(), "Could not find valid docker environment."); this.container = this.containerFactory.get(); this.container.start(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleFilter.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleFilter.java index fafd0865fa5..d454ec24497 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleFilter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ public class ExampleFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { response.getWriter().write("["); chain.doFilter(request, response); response.getWriter().write("]"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleServlet.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleServlet.java index b5a7353b833..5461c1fb05d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleServlet.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/ExampleServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class ExampleServlet extends GenericServlet { } @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String content = "Hello World"; if (this.echoRequestInfo) { content += " scheme=" + request.getScheme(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java index 4b1921a9e74..57913c0e837 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,36 +65,27 @@ public abstract class MockServletWebServer { private void initialize() { try { this.servletContext = mock(ServletContext.class); - given(this.servletContext.addServlet(anyString(), any(Servlet.class))) - .willAnswer((invocation) -> { - RegisteredServlet registeredServlet = new RegisteredServlet( - invocation.getArgument(1)); - MockServletWebServer.this.registeredServlets - .add(registeredServlet); - return registeredServlet.getRegistration(); - }); - given(this.servletContext.addFilter(anyString(), any(Filter.class))) - .willAnswer((invocation) -> { - RegisteredFilter registeredFilter = new RegisteredFilter( - invocation.getArgument(1)); - MockServletWebServer.this.registeredFilters.add(registeredFilter); - return registeredFilter.getRegistration(); - }); + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willAnswer((invocation) -> { + RegisteredServlet registeredServlet = new RegisteredServlet(invocation.getArgument(1)); + MockServletWebServer.this.registeredServlets.add(registeredServlet); + return registeredServlet.getRegistration(); + }); + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willAnswer((invocation) -> { + RegisteredFilter registeredFilter = new RegisteredFilter(invocation.getArgument(1)); + MockServletWebServer.this.registeredFilters.add(registeredFilter); + return registeredFilter.getRegistration(); + }); final Map initParameters = new HashMap<>(); - given(this.servletContext.setInitParameter(anyString(), anyString())) - .will((invocation) -> { - initParameters.put(invocation.getArgument(0), - invocation.getArgument(1)); - return null; - }); + given(this.servletContext.setInitParameter(anyString(), anyString())).will((invocation) -> { + initParameters.put(invocation.getArgument(0), invocation.getArgument(1)); + return null; + }); given(this.servletContext.getInitParameterNames()) .willReturn(Collections.enumeration(initParameters.keySet())); - given(this.servletContext.getInitParameter(anyString())).willAnswer( - (invocation) -> initParameters.get(invocation.getArgument(0))); - given(this.servletContext.getAttributeNames()) - .willReturn(Collections.emptyEnumeration()); - given(this.servletContext.getNamedDispatcher("default")) - .willReturn(mock(RequestDispatcher.class)); + given(this.servletContext.getInitParameter(anyString())) + .willAnswer((invocation) -> initParameters.get(invocation.getArgument(0))); + given(this.servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); + given(this.servletContext.getNamedDispatcher("default")).willReturn(mock(RequestDispatcher.class)); for (Initializer initializer : this.initializers) { initializer.onStartup(this.servletContext); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java index d3069eee25a..a96e4cfb268 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java @@ -32,8 +32,7 @@ import static org.hamcrest.Matchers.isA; @ClassPathExclusions("hibernate-validator-*.jar") public class ModifiedClassPathRunnerExclusionsTests { - private static final String EXCLUDED_RESOURCE = "META-INF/services/" - + "javax.validation.spi.ValidationProvider"; + private static final String EXCLUDED_RESOURCE = "META-INF/services/" + "javax.validation.spi.ValidationProvider"; @Test public void entriesAreFilteredFromTestClassClassLoader() { @@ -42,8 +41,7 @@ public class ModifiedClassPathRunnerExclusionsTests { @Test public void entriesAreFilteredFromThreadContextClassLoader() { - assertThat(Thread.currentThread().getContextClassLoader() - .getResource(EXCLUDED_RESOURCE)).isNull(); + assertThat(Thread.currentThread().getContextClassLoader().getResource(EXCLUDED_RESOURCE)).isNull(); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java index 7687c2fc973..557bfd1bfa6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,14 +35,14 @@ public class ModifiedClassPathRunnerOverridesTests { @Test public void classesAreLoadedFromOverride() { - assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource() - .getLocation().toString()).endsWith("spring-context-4.1.0.RELEASE.jar"); + assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) + .endsWith("spring-context-4.1.0.RELEASE.jar"); } @Test public void classesAreLoadedFromTransitiveDependencyOfOverride() { - assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation() - .toString()).endsWith("spring-core-4.1.0.RELEASE.jar"); + assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation().toString()) + .endsWith("spring-core-4.1.0.RELEASE.jar"); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java index 745d512807e..f6f7cdeff31 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java @@ -148,11 +148,9 @@ class BeanDefinitionLoader { } private int load(Class source) { - if (isGroovyPresent() - && GroovyBeanDefinitionSource.class.isAssignableFrom(source)) { + if (isGroovyPresent() && GroovyBeanDefinitionSource.class.isAssignableFrom(source)) { // Any GroovyLoaders added in beans{} DSL can contribute beans here - GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source, - GroovyBeanDefinitionSource.class); + GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source, GroovyBeanDefinitionSource.class); load(loader); } if (isComponent(source)) { @@ -172,8 +170,7 @@ class BeanDefinitionLoader { private int load(Resource source) { if (source.getFilename().endsWith(".groovy")) { if (this.groovyReader == null) { - throw new BeanDefinitionStoreException( - "Cannot load Groovy beans without Groovy on classpath"); + throw new BeanDefinitionStoreException("Cannot load Groovy beans without Groovy on classpath"); } return this.groovyReader.loadBeanDefinitions(source); } @@ -185,8 +182,7 @@ class BeanDefinitionLoader { } private int load(CharSequence source) { - String resolvedSource = this.xmlReader.getEnvironment() - .resolvePlaceholders(source.toString()); + String resolvedSource = this.xmlReader.getEnvironment().resolvePlaceholders(source.toString()); // Attempt as a Class try { return load(ClassUtils.forName(resolvedSource, null)); @@ -262,14 +258,11 @@ class BeanDefinitionLoader { } try { // Attempt to find a class in this package - ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( - getClass().getClassLoader()); - Resource[] resources = resolver.getResources( - ClassUtils.convertClassNameToResourcePath(source.toString()) - + "/*.class"); + ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); + Resource[] resources = resolver + .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); for (Resource resource : resources) { - String className = StringUtils - .stripFilenameExtension(resource.getFilename()); + String className = StringUtils.stripFilenameExtension(resource.getFilename()); load(Class.forName(source.toString() + "." + className)); break; } @@ -283,14 +276,13 @@ class BeanDefinitionLoader { private boolean isComponent(Class type) { // This has to be a bit of a guess. The only way to be sure that this type is // eligible is to make a bean definition out of it and try to instantiate it. - if (MergedAnnotations.from(type, SearchStrategy.EXHAUSTIVE) - .isPresent(Component.class)) { + if (MergedAnnotations.from(type, SearchStrategy.EXHAUSTIVE).isPresent(Component.class)) { return true; } // Nested anonymous classes are not eligible for registration, nor are groovy // closures - if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass() - || type.getConstructors() == null || type.getConstructors().length == 0) { + if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass() || type.getConstructors() == null + || type.getConstructors().length == 0) { return false; } return true; @@ -300,8 +292,7 @@ class BeanDefinitionLoader { * Simple {@link TypeFilter} used to ensure that specified {@link Class} sources are * not accidentally re-added during scanning. */ - private static class ClassExcludeFilter - extends AbstractTypeHierarchyTraversingFilter { + private static class ClassExcludeFilter extends AbstractTypeHierarchyTraversingFilter { private final Set classNames = new HashSet<>(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java index f1ffdd7294f..7fe7e5f7156 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import org.springframework.util.ReflectionUtils; * * @author Phillip Webb */ -class ClearCachesApplicationListener - implements ApplicationListener { +class ClearCachesApplicationListener implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent event) { @@ -41,8 +40,7 @@ class ClearCachesApplicationListener return; } try { - Method clearCacheMethod = classLoader.getClass() - .getDeclaredMethod("clearCache"); + Method clearCacheMethod = classLoader.getClass().getDeclaredMethod("clearCache"); clearCacheMethod.invoke(classLoader); } catch (Exception ex) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java index a5fb939a7db..1bd0eb8864b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,7 @@ final class EnvironmentConverter { return result; } - private StandardEnvironment createEnvironment( - Class type) { + private StandardEnvironment createEnvironment(Class type) { try { return type.newInstance(); } @@ -95,10 +94,8 @@ final class EnvironmentConverter { } } - private void copyPropertySources(ConfigurableEnvironment source, - StandardEnvironment target) { - removePropertySources(target.getPropertySources(), - isServletEnvironment(target.getClass(), this.classLoader)); + private void copyPropertySources(ConfigurableEnvironment source, StandardEnvironment target) { + removePropertySources(target.getPropertySources(), isServletEnvironment(target.getClass(), this.classLoader)); for (PropertySource propertySource : source.getPropertySources()) { if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) { target.getPropertySources().addLast(propertySource); @@ -106,11 +103,9 @@ final class EnvironmentConverter { } } - private boolean isServletEnvironment(Class conversionType, - ClassLoader classLoader) { + private boolean isServletEnvironment(Class conversionType, ClassLoader classLoader) { try { - Class webEnvironmentClass = ClassUtils - .forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, classLoader); + Class webEnvironmentClass = ClassUtils.forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, classLoader); return webEnvironmentClass.isAssignableFrom(conversionType); } catch (Throwable ex) { @@ -118,15 +113,13 @@ final class EnvironmentConverter { } } - private void removePropertySources(MutablePropertySources propertySources, - boolean isServletEnvironment) { + private void removePropertySources(MutablePropertySources propertySources, boolean isServletEnvironment) { Set names = new HashSet<>(); for (PropertySource propertySource : propertySources) { names.add(propertySource.getName()); } for (String name : names) { - if (!isServletEnvironment - || !SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(name)) { + if (!isServletEnvironment || !SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(name)) { propertySources.remove(name); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java index e61b1a0ac8b..7e7ccc1d12c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ class ExitCodeGenerators implements Iterable { addAll(exception, Arrays.asList(mappers)); } - public void addAll(Throwable exception, - Iterable mappers) { + public void addAll(Throwable exception, Iterable mappers) { Assert.notNull(exception, "Exception must not be null"); Assert.notNull(mappers, "Mappers must not be null"); for (ExitCodeExceptionMapper mapper : mappers) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java index c05186c71d3..6a4a8f4d8d1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,16 +76,15 @@ public class ImageBanner implements Banner { } @Override - public void printBanner(Environment environment, Class sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class sourceClass, PrintStream out) { String headless = System.getProperty("java.awt.headless"); try { System.setProperty("java.awt.headless", "true"); printBanner(environment, out); } catch (Throwable ex) { - logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() - + ": '" + ex.getMessage() + "')"); + logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() + ": '" + ex.getMessage() + + "')"); logger.debug("Image banner printing failure", ex); } finally { @@ -98,8 +97,7 @@ public class ImageBanner implements Banner { } } - private void printBanner(Environment environment, PrintStream out) - throws IOException { + private void printBanner(Environment environment, PrintStream out) throws IOException { int width = getProperty(environment, "width", Integer.class, 76); int height = getProperty(environment, "height", Integer.class, 0); int margin = getProperty(environment, "margin", Integer.class, 2); @@ -114,22 +112,19 @@ public class ImageBanner implements Banner { } } - private T getProperty(Environment environment, String name, Class targetType, - T defaultValue) { + private T getProperty(Environment environment, String name, Class targetType, T defaultValue) { return environment.getProperty(PROPERTY_PREFIX + name, targetType, defaultValue); } private Frame[] readFrames(int width, int height) throws IOException { try (InputStream inputStream = this.image.getInputStream()) { - try (ImageInputStream imageStream = ImageIO - .createImageInputStream(inputStream)) { + try (ImageInputStream imageStream = ImageIO.createImageInputStream(inputStream)) { return readFrames(width, height, imageStream); } } } - private Frame[] readFrames(int width, int height, ImageInputStream stream) - throws IOException { + private Frame[] readFrames(int width, int height, ImageInputStream stream) throws IOException { Iterator readers = ImageIO.getImageReaders(stream); Assert.state(readers.hasNext(), "Unable to read image banner source"); ImageReader reader = readers.next(); @@ -148,8 +143,8 @@ public class ImageBanner implements Banner { } } - private Frame readFrame(int width, int height, ImageReader reader, int imageIndex, - ImageReadParam readParam) throws IOException { + private Frame readFrame(int width, int height, ImageReader reader, int imageIndex, ImageReadParam readParam) + throws IOException { BufferedImage image = reader.read(imageIndex, readParam); BufferedImage resized = resizeImage(image, width, height); int delayTime = getDelayTime(reader, imageIndex); @@ -158,11 +153,9 @@ public class ImageBanner implements Banner { private int getDelayTime(ImageReader reader, int imageIndex) throws IOException { IIOMetadata metadata = reader.getImageMetadata(imageIndex); - IIOMetadataNode root = (IIOMetadataNode) metadata - .getAsTree(metadata.getNativeMetadataFormatName()); + IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(metadata.getNativeMetadataFormatName()); IIOMetadataNode extension = findNode(root, "GraphicControlExtension"); - String attribute = (extension != null) ? extension.getAttribute("delayTime") - : null; + String attribute = (extension != null) ? extension.getAttribute("delayTime") : null; return (attribute != null) ? Integer.parseInt(attribute) * 10 : 0; } @@ -186,8 +179,7 @@ public class ImageBanner implements Banner { double aspectRatio = (double) width / image.getWidth() * 0.5; height = (int) Math.ceil(image.getHeight() * aspectRatio); } - BufferedImage resized = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); + BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Image scaled = image.getScaledInstance(width, height, Image.SCALE_DEFAULT); resized.getGraphics().drawImage(scaled, 0, 0, null); return resized; @@ -198,8 +190,7 @@ public class ImageBanner implements Banner { out.print("\033[" + lines + "A\r"); } - private void printBanner(BufferedImage image, int margin, boolean invert, - PrintStream out) { + private void printBanner(BufferedImage image, int margin, boolean invert, PrintStream out) { AnsiElement background = invert ? AnsiBackground.BLACK : AnsiBackground.DEFAULT; out.print(AnsiOutput.encode(AnsiColor.DEFAULT)); out.print(AnsiOutput.encode(background)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java index 5bea70c5c0d..e66135986d1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java @@ -30,17 +30,14 @@ import org.springframework.core.Ordered; * @author Madhura Bhave * @since 2.2.0 */ -public final class LazyInitializationBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public final class LazyInitializationBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String name : beanFactory.getBeanDefinitionNames()) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name); if (beanDefinition instanceof AbstractBeanDefinition) { - Boolean lazyInit = ((AbstractBeanDefinition) beanDefinition) - .getLazyInit(); + Boolean lazyInit = ((AbstractBeanDefinition) beanDefinition).getLazyInit(); if (lazyInit != null && !lazyInit) { continue; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java index 17780e715f3..650003bc73b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,27 +58,24 @@ public class ResourceBanner implements Banner { } @Override - public void printBanner(Environment environment, Class sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class sourceClass, PrintStream out) { try { String banner = StreamUtils.copyToString(this.resource.getInputStream(), - environment.getProperty("spring.banner.charset", Charset.class, - StandardCharsets.UTF_8)); + environment.getProperty("spring.banner.charset", Charset.class, StandardCharsets.UTF_8)); - for (PropertyResolver resolver : getPropertyResolvers(environment, - sourceClass)) { + for (PropertyResolver resolver : getPropertyResolvers(environment, sourceClass)) { banner = resolver.resolvePlaceholders(banner); } out.println(banner); } catch (Exception ex) { - logger.warn("Banner not printable: " + this.resource + " (" + ex.getClass() - + ": '" + ex.getMessage() + "')", ex); + logger.warn( + "Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')", + ex); } } - protected List getPropertyResolvers(Environment environment, - Class sourceClass) { + protected List getPropertyResolvers(Environment environment, Class sourceClass) { List resolvers = new ArrayList<>(); resolvers.add(environment); resolvers.add(getVersionResolver(sourceClass)); @@ -89,8 +86,7 @@ public class ResourceBanner implements Banner { private PropertyResolver getVersionResolver(Class sourceClass) { MutablePropertySources propertySources = new MutablePropertySources(); - propertySources - .addLast(new MapPropertySource("version", getVersionsMap(sourceClass))); + propertySources.addLast(new MapPropertySource("version", getVersionsMap(sourceClass))); return new PropertySourcesPropertyResolver(propertySources); } @@ -101,8 +97,7 @@ public class ResourceBanner implements Banner { versions.put("application.version", getVersionString(appVersion, false)); versions.put("spring-boot.version", getVersionString(bootVersion, false)); versions.put("application.formatted-version", getVersionString(appVersion, true)); - versions.put("spring-boot.formatted-version", - getVersionString(bootVersion, true)); + versions.put("spring-boot.formatted-version", getVersionString(bootVersion, true)); return versions; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index 61d0f1178e4..017fa01837c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -268,8 +268,7 @@ public class SpringApplication { Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); - setInitializers((Collection) getSpringFactoriesInstances( - ApplicationContextInitializer.class)); + setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); } @@ -304,24 +303,19 @@ public class SpringApplication { SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { - ApplicationArguments applicationArguments = new DefaultApplicationArguments( - args); - ConfigurableEnvironment environment = prepareEnvironment(listeners, - applicationArguments); + ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); + ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); configureIgnoreBeanInfo(environment); Banner printedBanner = printBanner(environment); context = createApplicationContext(); - exceptionReporters = getSpringFactoriesInstances( - SpringBootExceptionReporter.class, + exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); - prepareContext(context, environment, listeners, applicationArguments, - printedBanner); + prepareContext(context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { - new StartupInfoLogger(this.mainApplicationClass) - .logStarted(getApplicationLog(), stopWatch); + new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } listeners.started(context); callRunners(context, applicationArguments); @@ -341,8 +335,7 @@ public class SpringApplication { return context; } - private ConfigurableEnvironment prepareEnvironment( - SpringApplicationRunListeners listeners, + private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { // Create and configure the environment ConfigurableEnvironment environment = getOrCreateEnvironment(); @@ -350,8 +343,8 @@ public class SpringApplication { listeners.environmentPrepared(environment); bindToSpringApplication(environment); if (!this.isCustomEnvironment) { - environment = new EnvironmentConverter(getClassLoader()) - .convertEnvironmentIfNecessary(environment, deduceEnvironmentClass()); + environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment, + deduceEnvironmentClass()); } ConfigurationPropertySources.attach(environment); return environment; @@ -368,9 +361,8 @@ public class SpringApplication { } } - private void prepareContext(ConfigurableApplicationContext context, - ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, - ApplicationArguments applicationArguments, Banner printedBanner) { + private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, + SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); postProcessApplicationContext(context); applyInitializers(context); @@ -390,8 +382,7 @@ public class SpringApplication { .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } if (this.lazyInitialization) { - context.addBeanFactoryPostProcessor( - new LazyInitializationBeanFactoryPostProcessor()); + context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } // Load the sources Set sources = getAllSources(); @@ -413,49 +404,43 @@ public class SpringApplication { } private void configureHeadlessProperty() { - System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty( - SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); + System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, + System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); } private SpringApplicationRunListeners getRunListeners(String[] args) { Class[] types = new Class[] { SpringApplication.class, String[].class }; - return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances( - SpringApplicationRunListener.class, types, this, args)); + return new SpringApplicationRunListeners(logger, + getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args)); } private Collection getSpringFactoriesInstances(Class type) { return getSpringFactoriesInstances(type, new Class[] {}); } - private Collection getSpringFactoriesInstances(Class type, - Class[] parameterTypes, Object... args) { + private Collection getSpringFactoriesInstances(Class type, Class[] parameterTypes, Object... args) { ClassLoader classLoader = getClassLoader(); // Use names and ensure unique to protect against duplicates - Set names = new LinkedHashSet<>( - SpringFactoriesLoader.loadFactoryNames(type, classLoader)); - List instances = createSpringFactoriesInstances(type, parameterTypes, - classLoader, args, names); + Set names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); + List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; } @SuppressWarnings("unchecked") - private List createSpringFactoriesInstances(Class type, - Class[] parameterTypes, ClassLoader classLoader, Object[] args, - Set names) { + private List createSpringFactoriesInstances(Class type, Class[] parameterTypes, + ClassLoader classLoader, Object[] args, Set names) { List instances = new ArrayList<>(names.size()); for (String name : names) { try { Class instanceClass = ClassUtils.forName(name, classLoader); Assert.isAssignable(type, instanceClass); - Constructor constructor = instanceClass - .getDeclaredConstructor(parameterTypes); + Constructor constructor = instanceClass.getDeclaredConstructor(parameterTypes); T instance = (T) BeanUtils.instantiateClass(constructor, args); instances.add(instance); } catch (Throwable ex) { - throw new IllegalArgumentException( - "Cannot instantiate " + type + " : " + name, ex); + throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex); } } return instances; @@ -486,13 +471,10 @@ public class SpringApplication { * @see #configureProfiles(ConfigurableEnvironment, String[]) * @see #configurePropertySources(ConfigurableEnvironment, String[]) */ - protected void configureEnvironment(ConfigurableEnvironment environment, - String[] args) { + protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { if (this.addConversionService) { - ConversionService conversionService = ApplicationConversionService - .getSharedInstance(); - environment.setConversionService( - (ConfigurableConversionService) conversionService); + ConversionService conversionService = ApplicationConversionService.getSharedInstance(); + environment.setConversionService((ConfigurableConversionService) conversionService); } configurePropertySources(environment, args); configureProfiles(environment, args); @@ -505,20 +487,18 @@ public class SpringApplication { * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ - protected void configurePropertySources(ConfigurableEnvironment environment, - String[] args) { + protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { - sources.addLast( - new MapPropertySource("defaultProperties", this.defaultProperties)); + sources.addLast(new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); - composite.addPropertySource(new SimpleCommandLinePropertySource( - "springApplicationCommandLineArgs", args)); + composite.addPropertySource( + new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } @@ -546,12 +526,9 @@ public class SpringApplication { } private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) { - if (System.getProperty( - CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) { - Boolean ignore = environment.getProperty("spring.beaninfo.ignore", - Boolean.class, Boolean.TRUE); - System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, - ignore.toString()); + if (System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) { + Boolean ignore = environment.getProperty("spring.beaninfo.ignore", Boolean.class, Boolean.TRUE); + System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, ignore.toString()); } } @@ -572,10 +549,9 @@ public class SpringApplication { if (this.bannerMode == Banner.Mode.OFF) { return null; } - ResourceLoader resourceLoader = (this.resourceLoader != null) - ? this.resourceLoader : new DefaultResourceLoader(getClassLoader()); - SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter( - resourceLoader, this.banner); + ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader + : new DefaultResourceLoader(getClassLoader()); + SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner); if (this.bannerMode == Mode.LOG) { return bannerPrinter.print(environment, this.mainApplicationClass, logger); } @@ -606,8 +582,7 @@ public class SpringApplication { } catch (ClassNotFoundException ex) { throw new IllegalStateException( - "Unable create a default ApplicationContext, " - + "please specify an ApplicationContextClass", + "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass", ex); } } @@ -621,23 +596,19 @@ public class SpringApplication { */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { - context.getBeanFactory().registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, + context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { - ((GenericApplicationContext) context) - .setResourceLoader(this.resourceLoader); + ((GenericApplicationContext) context).setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { - ((DefaultResourceLoader) context) - .setClassLoader(this.resourceLoader.getClassLoader()); + ((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader()); } } if (this.addConversionService) { - context.getBeanFactory().setConversionService( - ApplicationConversionService.getSharedInstance()); + context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()); } } @@ -650,8 +621,8 @@ public class SpringApplication { @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { - Class requiredType = GenericTypeResolver.resolveTypeArgument( - initializer.getClass(), ApplicationContextInitializer.class); + Class requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), + ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } @@ -664,8 +635,7 @@ public class SpringApplication { */ protected void logStartupInfo(boolean isRoot) { if (isRoot) { - new StartupInfoLogger(this.mainApplicationClass) - .logStarting(getApplicationLog()); + new StartupInfoLogger(this.mainApplicationClass).logStarting(getApplicationLog()); } } @@ -707,11 +677,9 @@ public class SpringApplication { */ protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { - logger.debug( - "Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); + logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } - BeanDefinitionLoader loader = createBeanDefinitionLoader( - getBeanDefinitionRegistry(context), sources); + BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources); if (this.beanNameGenerator != null) { loader.setBeanNameGenerator(this.beanNameGenerator); } @@ -756,8 +724,7 @@ public class SpringApplication { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { - return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) - .getBeanFactory(); + return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } @@ -768,8 +735,7 @@ public class SpringApplication { * @param sources the sources to load * @return the {@link BeanDefinitionLoader} that will be used to load beans */ - protected BeanDefinitionLoader createBeanDefinitionLoader( - BeanDefinitionRegistry registry, Object[] sources) { + protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); } @@ -787,8 +753,7 @@ public class SpringApplication { * @param context the application context * @param args the application arguments */ - protected void afterRefresh(ConfigurableApplicationContext context, - ApplicationArguments args) { + protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { } private void callRunners(ApplicationContext context, ApplicationArguments args) { @@ -824,10 +789,8 @@ public class SpringApplication { } } - private void handleRunFailure(ConfigurableApplicationContext context, - Throwable exception, - Collection exceptionReporters, - SpringApplicationRunListeners listeners) { + private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception, + Collection exceptionReporters, SpringApplicationRunListeners listeners) { try { try { handleExitCode(context, exception); @@ -848,8 +811,7 @@ public class SpringApplication { ReflectionUtils.rethrowRuntimeException(exception); } - private void reportFailure(Collection exceptionReporters, - Throwable failure) { + private void reportFailure(Collection exceptionReporters, Throwable failure) { try { for (SpringBootExceptionReporter reporter : exceptionReporters) { if (reporter.reportException(failure)) { @@ -879,8 +841,7 @@ public class SpringApplication { } } - private void handleExitCode(ConfigurableApplicationContext context, - Throwable exception) { + private void handleExitCode(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromException(context, exception); if (exitCode != 0) { if (context != null) { @@ -893,8 +854,7 @@ public class SpringApplication { } } - private int getExitCodeFromException(ConfigurableApplicationContext context, - Throwable exception) { + private int getExitCodeFromException(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromMappedException(context, exception); if (exitCode == 0) { exitCode = getExitCodeFromExitCodeGeneratorException(exception); @@ -902,14 +862,12 @@ public class SpringApplication { return exitCode; } - private int getExitCodeFromMappedException(ConfigurableApplicationContext context, - Throwable exception) { + private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) { if (context == null || !context.isActive()) { return 0; } ExitCodeGenerators generators = new ExitCodeGenerators(); - Collection beans = context - .getBeansOfType(ExitCodeExceptionMapper.class).values(); + Collection beans = context.getBeansOfType(ExitCodeExceptionMapper.class).values(); generators.addAll(exception, beans); return generators.getExitCode(); } @@ -932,8 +890,7 @@ public class SpringApplication { } private boolean isMainThread(Thread currentThread) { - return ("main".equals(currentThread.getName()) - || "restartedMain".equals(currentThread.getName())) + return ("main".equals(currentThread.getName()) || "restartedMain".equals(currentThread.getName())) && "main".equals(currentThread.getThreadGroup().getName()); } @@ -1188,11 +1145,9 @@ public class SpringApplication { * applications. * @param applicationContextClass the context class to set */ - public void setApplicationContextClass( - Class applicationContextClass) { + public void setApplicationContextClass(Class applicationContextClass) { this.applicationContextClass = applicationContextClass; - this.webApplicationType = WebApplicationType - .deduceFromApplicationContext(applicationContextClass); + this.webApplicationType = WebApplicationType.deduceFromApplicationContext(applicationContextClass); } /** @@ -1200,8 +1155,7 @@ public class SpringApplication { * {@link ApplicationContext}. * @param initializers the initializers to set */ - public void setInitializers( - Collection> initializers) { + public void setInitializers(Collection> initializers) { this.initializers = new ArrayList<>(initializers); } @@ -1258,8 +1212,7 @@ public class SpringApplication { * @param args the application arguments (usually passed from a Java main method) * @return the running {@link ApplicationContext} */ - public static ConfigurableApplicationContext run(Class primarySource, - String... args) { + public static ConfigurableApplicationContext run(Class primarySource, String... args) { return run(new Class[] { primarySource }, args); } @@ -1270,8 +1223,7 @@ public class SpringApplication { * @param args the application arguments (usually passed from a Java main method) * @return the running {@link ApplicationContext} */ - public static ConfigurableApplicationContext run(Class[] primarySources, - String[] args) { + public static ConfigurableApplicationContext run(Class[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); } @@ -1302,15 +1254,13 @@ public class SpringApplication { * @param exitCodeGenerators exist code generators * @return the outcome (0 if successful) */ - public static int exit(ApplicationContext context, - ExitCodeGenerator... exitCodeGenerators) { + public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); - Collection beans = context - .getBeansOfType(ExitCodeGenerator.class).values(); + Collection beans = context.getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java index fd6b625e7ad..28a271c53dd 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,8 +86,7 @@ class SpringApplicationBannerPrinter { } private Banner getTextBanner(Environment environment) { - String location = environment.getProperty(BANNER_LOCATION_PROPERTY, - DEFAULT_BANNER_LOCATION); + String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION); Resource resource = this.resourceLoader.getResource(location); if (resource.exists()) { return new ResourceBanner(resource); @@ -110,8 +109,8 @@ class SpringApplicationBannerPrinter { return null; } - private String createStringFromBanner(Banner banner, Environment environment, - Class mainApplicationClass) throws UnsupportedEncodingException { + private String createStringFromBanner(Banner banner, Environment environment, Class mainApplicationClass) + throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); banner.printBanner(environment, mainApplicationClass, new PrintStream(baos)); String charset = environment.getProperty("spring.banner.charset", "UTF-8"); @@ -136,8 +135,7 @@ class SpringApplicationBannerPrinter { } @Override - public void printBanner(Environment environment, Class sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class sourceClass, PrintStream out) { for (Banner banner : this.banners) { banner.printBanner(environment, sourceClass, out); } @@ -161,8 +159,7 @@ class SpringApplicationBannerPrinter { } @Override - public void printBanner(Environment environment, Class sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class sourceClass, PrintStream out) { sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass; this.banner.printBanner(environment, sourceClass, out); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java index 123dde4f2ec..2018fbe72cb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ class SpringApplicationRunListeners { private final List listeners; - SpringApplicationRunListeners(Log log, - Collection listeners) { + SpringApplicationRunListeners(Log log, Collection listeners) { this.log = log; this.listeners = new ArrayList<>(listeners); } @@ -85,8 +84,8 @@ class SpringApplicationRunListeners { } } - private void callFailedListener(SpringApplicationRunListener listener, - ConfigurableApplicationContext context, Throwable exception) { + private void callFailedListener(SpringApplicationRunListener listener, ConfigurableApplicationContext context, + Throwable exception) { try { listener.failed(context, exception); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java index 08bcfec8115..967eca784fe 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,12 +30,9 @@ import org.springframework.core.env.Environment; */ class SpringBootBanner implements Banner { - private static final String[] BANNER = { "", - " . ____ _ __ _ _", - " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\", - "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\", - " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )", - " ' |____| .__|_| |_|_| |_\\__, | / / / /", + private static final String[] BANNER = { "", " . ____ _ __ _ _", + " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\", "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\", + " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )", " ' |____| .__|_| |_|_| |_\\__, | / / / /", " =========|_|==============|___/=/_/_/_/" }; private static final String SPRING_BOOT = " :: Spring Boot :: "; @@ -43,21 +40,19 @@ class SpringBootBanner implements Banner { private static final int STRAP_LINE_SIZE = 42; @Override - public void printBanner(Environment environment, Class sourceClass, - PrintStream printStream) { + public void printBanner(Environment environment, Class sourceClass, PrintStream printStream) { for (String line : BANNER) { printStream.println(line); } String version = SpringBootVersion.getVersion(); version = (version != null) ? " (v" + version + ")" : ""; StringBuilder padding = new StringBuilder(); - while (padding.length() < STRAP_LINE_SIZE - - (version.length() + SPRING_BOOT.length())) { + while (padding.length() < STRAP_LINE_SIZE - (version.length() + SPRING_BOOT.length())) { padding.append(" "); } - printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT, - AnsiColor.DEFAULT, padding.toString(), AnsiStyle.FAINT, version)); + printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT, AnsiColor.DEFAULT, padding.toString(), + AnsiStyle.FAINT, version)); printStream.println(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java index 8264b568e38..ae168e6ca0a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,8 +117,7 @@ class SpringBootExceptionHandler implements UncaughtExceptionHandler { /** * Thread local used to attach and track handlers. */ - private static class LoggedExceptionHandlerThreadLocal - extends ThreadLocal { + private static class LoggedExceptionHandlerThreadLocal extends ThreadLocal { @Override protected SpringBootExceptionHandler initialValue() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootVersion.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootVersion.java index 8a950ca69a6..dc5904d8458 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootVersion.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringBootVersion.java @@ -58,13 +58,11 @@ public final class SpringBootVersion { } private static String determineSpringBootVersion() { - String implementationVersion = SpringBootVersion.class.getPackage() - .getImplementationVersion(); + String implementationVersion = SpringBootVersion.class.getPackage().getImplementationVersion(); if (implementationVersion != null) { return implementationVersion; } - CodeSource codeSource = SpringBootVersion.class.getProtectionDomain() - .getCodeSource(); + CodeSource codeSource = SpringBootVersion.class.getProtectionDomain().getCodeSource(); if (codeSource == null) { return null; } @@ -72,8 +70,7 @@ public final class SpringBootVersion { try { URLConnection connection = codeSourceLocation.openConnection(); if (connection instanceof JarURLConnection) { - return getImplementationVersion( - ((JarURLConnection) connection).getJarFile()); + return getImplementationVersion(((JarURLConnection) connection).getJarFile()); } try (JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) { return getImplementationVersion(jarFile); @@ -85,8 +82,7 @@ public final class SpringBootVersion { } private static String getImplementationVersion(JarFile jarFile) throws IOException { - return jarFile.getManifest().getMainAttributes() - .getValue(Attributes.Name.IMPLEMENTATION_VERSION); + return jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java index 84aa83bc59e..3c613737134 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java @@ -100,8 +100,7 @@ class StartupInfoLogger { } private void appendApplicationName(StringBuilder message) { - String name = (this.sourceClass != null) - ? ClassUtils.getShortName(this.sourceClass) : "application"; + String name = (this.sourceClass != null) ? ClassUtils.getShortName(this.sourceClass) : "application"; message.append(name); } @@ -149,8 +148,7 @@ class StartupInfoLogger { append(message, prefix, call, ""); } - private void append(StringBuilder message, String prefix, Callable call, - String defaultValue) { + private void append(StringBuilder message, String prefix, Callable call, String defaultValue) { Object result = callIfPossible(call); String value = (result != null) ? result.toString() : null; if (!StringUtils.hasLength(value)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java index 4bde270044f..8fd8fd175ac 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,11 +48,9 @@ public enum WebApplicationType { private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext" }; - private static final String WEBMVC_INDICATOR_CLASS = "org.springframework." - + "web.servlet.DispatcherServlet"; + private static final String WEBMVC_INDICATOR_CLASS = "org.springframework." + "web.servlet.DispatcherServlet"; - private static final String WEBFLUX_INDICATOR_CLASS = "org." - + "springframework.web.reactive.DispatcherHandler"; + private static final String WEBFLUX_INDICATOR_CLASS = "org." + "springframework.web.reactive.DispatcherHandler"; private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer"; @@ -61,8 +59,7 @@ public enum WebApplicationType { private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext"; static WebApplicationType deduceFromClasspath() { - if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) - && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null) + if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null) && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) { return WebApplicationType.REACTIVE; } @@ -74,8 +71,7 @@ public enum WebApplicationType { return WebApplicationType.SERVLET; } - static WebApplicationType deduceFromApplicationContext( - Class applicationContextClass) { + static WebApplicationType deduceFromApplicationContext(Class applicationContextClass) { if (isAssignable(SERVLET_APPLICATION_CONTEXT_CLASS, applicationContextClass)) { return WebApplicationType.SERVLET; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java index 7c0f9898b9e..cbef17201ee 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java @@ -50,8 +50,8 @@ import org.springframework.util.Assert; * @author Andy Wilkinson * @since 1.3.0 */ -public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContextAware, - GenericApplicationListener, EnvironmentAware, InitializingBean, DisposableBean { +public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContextAware, GenericApplicationListener, + EnvironmentAware, InitializingBean, DisposableBean { private static final Log logger = LogFactory.getLog(SpringApplicationAdmin.class); @@ -65,14 +65,12 @@ public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContext private boolean embeddedWebApplication = false; - public SpringApplicationAdminMXBeanRegistrar(String name) - throws MalformedObjectNameException { + public SpringApplicationAdminMXBeanRegistrar(String name) throws MalformedObjectNameException { this.objectName = new ObjectName(name); } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Assert.state(applicationContext instanceof ConfigurableApplicationContext, "ApplicationContext does not implement ConfigurableApplicationContext"); this.applicationContext = (ConfigurableApplicationContext) applicationContext; @@ -130,8 +128,7 @@ public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContext MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.registerMBean(new SpringApplicationAdmin(), this.objectName); if (logger.isDebugEnabled()) { - logger.debug("Application Admin MBean registered with name '" - + this.objectName + "'"); + logger.debug("Application Admin MBean registered with name '" + this.objectName + "'"); } } @@ -154,8 +151,7 @@ public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContext @Override public String getProperty(String key) { - return SpringApplicationAdminMXBeanRegistrar.this.environment - .getProperty(key); + return SpringApplicationAdminMXBeanRegistrar.this.environment.getProperty(key); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java index d43b74a75ae..e9d5689558c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,8 +84,7 @@ public final class AnsiColors { */ private static final class LabColor { - private static final ColorSpace XYZ_COLOR_SPACE = ColorSpace - .getInstance(ColorSpace.CS_CIEXYZ); + private static final ColorSpace XYZ_COLOR_SPACE = ColorSpace.getInstance(ColorSpace.CS_CIEXYZ); private final double l; @@ -117,8 +116,7 @@ public final class AnsiColors { } private double f(double t) { - return (t > (216.0 / 24389.0)) ? Math.cbrt(t) - : (1.0 / 3.0) * Math.pow(29.0 / 6.0, 2) * t + (4.0 / 29.0); + return (t > (216.0 / 24389.0)) ? Math.cbrt(t) : (1.0 / 3.0) * Math.pow(29.0 / 6.0, 2) * t + (4.0 / 29.0); } // See https://en.wikipedia.org/wiki/Color_difference#CIE94 @@ -127,12 +125,9 @@ public final class AnsiColors { double deltaC = c1 - Math.sqrt(other.a * other.a + other.b * other.b); double deltaA = this.a - other.a; double deltaB = this.b - other.b; - double deltaH = Math.sqrt( - Math.max(0.0, deltaA * deltaA + deltaB * deltaB - deltaC * deltaC)); - return Math.sqrt(Math.max(0.0, - Math.pow((this.l - other.l) / (1.0), 2) - + Math.pow(deltaC / (1 + 0.045 * c1), 2) - + Math.pow(deltaH / (1 + 0.015 * c1), 2.0))); + double deltaH = Math.sqrt(Math.max(0.0, deltaA * deltaA + deltaB * deltaB - deltaC * deltaC)); + return Math.sqrt(Math.max(0.0, Math.pow((this.l - other.l) / (1.0), 2) + + Math.pow(deltaC / (1 + 0.045 * c1), 2) + Math.pow(deltaH / (1 + 0.015 * c1), 2.0))); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java index ef0882eb3fa..9f314880186 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java @@ -36,8 +36,7 @@ public abstract class AnsiOutput { private static Boolean ansiCapable; - private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name") - .toLowerCase(Locale.ENGLISH); + private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); private static final String ENCODE_START = "\033["; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java index 11355621b6c..a95bb119e64 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.core.Ordered; * * @author Dave Syer */ -public class ParentContextApplicationContextInitializer implements - ApplicationContextInitializer, Ordered { +public class ParentContextApplicationContextInitializer + implements ApplicationContextInitializer, Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; @@ -59,8 +59,7 @@ public class ParentContextApplicationContextInitializer implements } } - private static class EventPublisher - implements ApplicationListener, Ordered { + private static class EventPublisher implements ApplicationListener, Ordered { private static final EventPublisher INSTANCE = new EventPublisher(); @@ -72,10 +71,8 @@ public class ParentContextApplicationContextInitializer implements @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext context = event.getApplicationContext(); - if (context instanceof ConfigurableApplicationContext - && context == event.getSource()) { - context.publishEvent(new ParentContextAvailableEvent( - (ConfigurableApplicationContext) context)); + if (context instanceof ConfigurableApplicationContext && context == event.getSource()) { + context.publishEvent(new ParentContextAvailableEvent((ConfigurableApplicationContext) context)); } } @@ -87,8 +84,7 @@ public class ParentContextApplicationContextInitializer implements @SuppressWarnings("serial") public static class ParentContextAvailableEvent extends ApplicationEvent { - public ParentContextAvailableEvent( - ConfigurableApplicationContext applicationContext) { + public ParentContextAvailableEvent(ConfigurableApplicationContext applicationContext) { super(applicationContext); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java index 5328bcfb558..b7a2ee94f7c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.util.ObjectUtils; * @author Eric Bottard */ public class ParentContextCloserApplicationListener - implements ApplicationListener, - ApplicationContextAware, Ordered { + implements ApplicationListener, ApplicationContextAware, Ordered { private int order = Ordered.LOWEST_PRECEDENCE - 10; @@ -60,10 +59,8 @@ public class ParentContextCloserApplicationListener } private void maybeInstallListenerInParent(ConfigurableApplicationContext child) { - if (child == this.context - && child.getParent() instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext parent = (ConfigurableApplicationContext) child - .getParent(); + if (child == this.context && child.getParent() instanceof ConfigurableApplicationContext) { + ConfigurableApplicationContext parent = (ConfigurableApplicationContext) child.getParent(); parent.addApplicationListener(createContextCloserListener(child)); } } @@ -74,16 +71,14 @@ public class ParentContextCloserApplicationListener * @param child the child context * @return the {@link ContextCloserListener} to use */ - protected ContextCloserListener createContextCloserListener( - ConfigurableApplicationContext child) { + protected ContextCloserListener createContextCloserListener(ConfigurableApplicationContext child) { return new ContextCloserListener(child); } /** * {@link ApplicationListener} to close the context. */ - protected static class ContextCloserListener - implements ApplicationListener { + protected static class ContextCloserListener implements ApplicationListener { private WeakReference childContext; @@ -94,9 +89,7 @@ public class ParentContextCloserApplicationListener @Override public void onApplicationEvent(ContextClosedEvent event) { ConfigurableApplicationContext context = this.childContext.get(); - if ((context != null) - && (event.getApplicationContext() == context.getParent()) - && context.isActive()) { + if ((context != null) && (event.getApplicationContext() == context.getParent()) && context.isActive()) { context.close(); } } @@ -111,8 +104,7 @@ public class ParentContextCloserApplicationListener } if (obj instanceof ContextCloserListener) { ContextCloserListener other = (ContextCloserListener) obj; - return ObjectUtils.nullSafeEquals(this.childContext.get(), - other.childContext.get()); + return ObjectUtils.nullSafeEquals(this.childContext.get(), other.childContext.get()); } return super.equals(obj); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java index 843dee5c511..8bf76bcc4b9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java @@ -148,8 +148,7 @@ public class SpringApplicationBuilder { if (!this.registerShutdownHookApplied) { this.application.setRegisterShutdownHook(false); } - initializers(new ParentContextApplicationContextInitializer( - this.parent.run(args))); + initializers(new ParentContextApplicationContextInitializer(this.parent.run(args))); } } @@ -210,9 +209,8 @@ public class SpringApplicationBuilder { */ public SpringApplicationBuilder parent(Class... sources) { if (this.parent == null) { - this.parent = new SpringApplicationBuilder(sources) - .web(WebApplicationType.NONE).properties(this.defaultProperties) - .environment(this.environment); + this.parent = new SpringApplicationBuilder(sources).web(WebApplicationType.NONE) + .properties(this.defaultProperties).environment(this.environment); } else { this.parent.sources(sources); @@ -274,8 +272,7 @@ public class SpringApplicationBuilder { * @param cls the context class to use * @return the current builder */ - public SpringApplicationBuilder contextClass( - Class cls) { + public SpringApplicationBuilder contextClass(Class cls) { this.application.setApplicationContextClass(cls); return this; } @@ -366,8 +363,7 @@ public class SpringApplicationBuilder { * @param addCommandLineProperties the flag to set. Default true. * @return the current builder */ - public SpringApplicationBuilder addCommandLineProperties( - boolean addCommandLineProperties) { + public SpringApplicationBuilder addCommandLineProperties(boolean addCommandLineProperties) { this.application.setAddCommandLineProperties(addCommandLineProperties); return this; } @@ -379,8 +375,7 @@ public class SpringApplicationBuilder { * @return the current builder * @since 2.1.0 */ - public SpringApplicationBuilder setAddConversionService( - boolean addConversionService) { + public SpringApplicationBuilder setAddConversionService(boolean addConversionService) { this.application.setAddConversionService(addConversionService); return this; } @@ -470,16 +465,13 @@ public class SpringApplicationBuilder { */ public SpringApplicationBuilder profiles(String... profiles) { this.additionalProfiles.addAll(Arrays.asList(profiles)); - this.application.setAdditionalProfiles( - StringUtils.toStringArray(this.additionalProfiles)); + this.application.setAdditionalProfiles(StringUtils.toStringArray(this.additionalProfiles)); return this; } - private SpringApplicationBuilder additionalProfiles( - Collection additionalProfiles) { + private SpringApplicationBuilder additionalProfiles(Collection additionalProfiles) { this.additionalProfiles = new LinkedHashSet<>(additionalProfiles); - this.application.setAdditionalProfiles( - StringUtils.toStringArray(this.additionalProfiles)); + this.application.setAdditionalProfiles(StringUtils.toStringArray(this.additionalProfiles)); return this; } @@ -489,8 +481,7 @@ public class SpringApplicationBuilder { * @param beanNameGenerator the generator to set. * @return the current builder */ - public SpringApplicationBuilder beanNameGenerator( - BeanNameGenerator beanNameGenerator) { + public SpringApplicationBuilder beanNameGenerator(BeanNameGenerator beanNameGenerator) { this.application.setBeanNameGenerator(beanNameGenerator); return this; } @@ -523,8 +514,7 @@ public class SpringApplicationBuilder { * @param initializers some initializers to add * @return the current builder */ - public SpringApplicationBuilder initializers( - ApplicationContextInitializer... initializers) { + public SpringApplicationBuilder initializers(ApplicationContextInitializer... initializers) { this.application.addInitializers(initializers); return this; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java index 93595fb6d16..8d337b46f09 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,11 +88,9 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Andy Wilkinson */ -public class CloudFoundryVcapEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { +public class CloudFoundryVcapEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { - private static final Log logger = LogFactory - .getLog(CloudFoundryVcapEnvironmentPostProcessor.class); + private static final Log logger = LogFactory.getLog(CloudFoundryVcapEnvironmentPostProcessor.class); private static final String VCAP_APPLICATION = "VCAP_APPLICATION"; @@ -111,26 +109,19 @@ public class CloudFoundryVcapEnvironmentPostProcessor } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) { Properties properties = new Properties(); JsonParser jsonParser = JsonParserFactory.getJsonParser(); - addWithPrefix(properties, - getPropertiesFromApplication(environment, jsonParser), - "vcap.application."); - addWithPrefix(properties, getPropertiesFromServices(environment, jsonParser), - "vcap.services."); + addWithPrefix(properties, getPropertiesFromApplication(environment, jsonParser), "vcap.application."); + addWithPrefix(properties, getPropertiesFromServices(environment, jsonParser), "vcap.services."); MutablePropertySources propertySources = environment.getPropertySources(); - if (propertySources.contains( - CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { - propertySources.addAfter( - CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, + if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { + propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, new PropertiesPropertySource("vcap", properties)); } else { - propertySources - .addFirst(new PropertiesPropertySource("vcap", properties)); + propertySources.addFirst(new PropertiesPropertySource("vcap", properties)); } } } @@ -142,8 +133,7 @@ public class CloudFoundryVcapEnvironmentPostProcessor } } - private Properties getPropertiesFromApplication(Environment environment, - JsonParser parser) { + private Properties getPropertiesFromApplication(Environment environment, JsonParser parser) { Properties properties = new Properties(); try { String property = environment.getProperty(VCAP_APPLICATION, "{}"); @@ -156,8 +146,7 @@ public class CloudFoundryVcapEnvironmentPostProcessor return properties; } - private Properties getPropertiesFromServices(Environment environment, - JsonParser parser) { + private Properties getPropertiesFromServices(Environment environment, JsonParser parser) { Properties properties = new Properties(); try { String property = environment.getProperty(VCAP_SERVICES, "{}"); @@ -170,15 +159,13 @@ public class CloudFoundryVcapEnvironmentPostProcessor return properties; } - private void extractPropertiesFromApplication(Properties properties, - Map map) { + private void extractPropertiesFromApplication(Properties properties, Map map) { if (map != null) { flatten(properties, map, ""); } } - private void extractPropertiesFromServices(Properties properties, - Map map) { + private void extractPropertiesFromServices(Properties properties, Map map) { if (map != null) { for (Object services : map.values()) { @SuppressWarnings("unchecked") @@ -207,8 +194,7 @@ public class CloudFoundryVcapEnvironmentPostProcessor else if (value instanceof Collection) { // Need a compound key Collection collection = (Collection) value; - properties.put(name, - StringUtils.collectionToCommaDelimitedString(collection)); + properties.put(name, StringUtils.collectionToCommaDelimitedString(collection)); int count = 0; for (Object item : collection) { String itemKey = "[" + (count++) + "]"; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java index c778c46cb2e..2db1b48e561 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java @@ -39,8 +39,7 @@ public enum CloudPlatform { @Override public boolean isActive(Environment environment) { - return environment.containsProperty("VCAP_APPLICATION") - || environment.containsProperty("VCAP_SERVICES"); + return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES"); } }, @@ -100,8 +99,7 @@ public enum CloudPlatform { if (propertyName.endsWith(SERVICE_HOST_SUFFIX)) { String serviceName = propertyName.substring(0, propertyName.length() - SERVICE_HOST_SUFFIX.length()); - if (environmentPropertySource - .getProperty(serviceName + SERVICE_PORT_SUFFIX) != null) { + if (environmentPropertySource.getProperty(serviceName + SERVICE_PORT_SUFFIX) != null) { return true; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java index f5f796d0363..29dea9e8856 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,7 @@ import org.springframework.util.Assert; * @author Madhura Bhave * @since 2.0.0 */ -public class ApplicationPidFileWriter - implements ApplicationListener, Ordered { +public class ApplicationPidFileWriter implements ApplicationListener, Ordered { private static final Log logger = LogFactory.getLog(ApplicationPidFileWriter.class); @@ -128,16 +127,14 @@ public class ApplicationPidFileWriter * {@link Environment}. * @param triggerEventType the trigger event type */ - public void setTriggerEventType( - Class triggerEventType) { + public void setTriggerEventType(Class triggerEventType) { Assert.notNull(triggerEventType, "Trigger event type must not be null"); this.triggerEventType = triggerEventType; } @Override public void onApplicationEvent(SpringApplicationEvent event) { - if (this.triggerEventType.isInstance(event) - && created.compareAndSet(false, true)) { + if (this.triggerEventType.isInstance(event) && created.compareAndSet(false, true)) { try { writePidFile(event); } @@ -229,12 +226,10 @@ public class ApplicationPidFileWriter return ((ApplicationEnvironmentPreparedEvent) event).getEnvironment(); } if (event instanceof ApplicationPreparedEvent) { - return ((ApplicationPreparedEvent) event).getApplicationContext() - .getEnvironment(); + return ((ApplicationPreparedEvent) event).getApplicationContext().getEnvironment(); } if (event instanceof ApplicationReadyEvent) { - return ((ApplicationReadyEvent) event).getApplicationContext() - .getEnvironment(); + return ((ApplicationReadyEvent) event).getApplicationContext().getEnvironment(); } return null; } @@ -249,8 +244,7 @@ public class ApplicationPidFileWriter private final String[] properties; SystemProperty(String name) { - this.properties = new String[] { name.toUpperCase(Locale.ENGLISH), - name.toLowerCase(Locale.ENGLISH) }; + this.properties = new String[] { name.toUpperCase(Locale.ENGLISH), name.toLowerCase(Locale.ENGLISH) }; } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java index e3ba8d013e8..eae415310c4 100755 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,13 +52,11 @@ import org.springframework.util.StringUtils; public class ConfigurationWarningsApplicationContextInitializer implements ApplicationContextInitializer { - private static final Log logger = LogFactory - .getLog(ConfigurationWarningsApplicationContextInitializer.class); + private static final Log logger = LogFactory.getLog(ConfigurationWarningsApplicationContextInitializer.class); @Override public void initialize(ConfigurableApplicationContext context) { - context.addBeanFactoryPostProcessor( - new ConfigurationWarningsPostProcessor(getChecks())); + context.addBeanFactoryPostProcessor(new ConfigurationWarningsPostProcessor(getChecks())); } /** @@ -87,13 +85,11 @@ public class ConfigurationWarningsApplicationContextInitializer } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { for (Check check : this.checks) { String message = check.getWarning(registry); if (StringUtils.hasLength(message)) { @@ -147,31 +143,26 @@ public class ConfigurationWarningsApplicationContextInitializer if (problematicPackages.isEmpty()) { return null; } - return "Your ApplicationContext is unlikely to " - + "start due to a @ComponentScan of " - + StringUtils.collectionToDelimitedString(problematicPackages, ", ") - + "."; + return "Your ApplicationContext is unlikely to " + "start due to a @ComponentScan of " + + StringUtils.collectionToDelimitedString(problematicPackages, ", ") + "."; } - protected Set getComponentScanningPackages( - BeanDefinitionRegistry registry) { + protected Set getComponentScanningPackages(BeanDefinitionRegistry registry) { Set packages = new LinkedHashSet<>(); String[] names = registry.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = registry.getBeanDefinition(name); if (definition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; - addComponentScanningPackages(packages, - annotatedDefinition.getMetadata()); + addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); } } return packages; } - private void addComponentScanningPackages(Set packages, - AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata - .getAnnotationAttributes(ComponentScan.class.getName(), true)); + private void addComponentScanningPackages(Set packages, AnnotationMetadata metadata) { + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); if (attributes != null) { addPackages(packages, attributes.getStringArray("value")); addPackages(packages, attributes.getStringArray("basePackages")); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java index a186eebf592..5db9e45a258 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Andy Wilkinson */ -public class ContextIdApplicationContextInitializer implements - ApplicationContextInitializer, Ordered { +public class ContextIdApplicationContextInitializer + implements ApplicationContextInitializer, Ordered { private int order = Ordered.LOWEST_PRECEDENCE - 10; @@ -52,8 +52,7 @@ public class ContextIdApplicationContextInitializer implements public void initialize(ConfigurableApplicationContext applicationContext) { ContextId contextId = getContextId(applicationContext); applicationContext.setId(contextId.getId()); - applicationContext.getBeanFactory().registerSingleton(ContextId.class.getName(), - contextId); + applicationContext.getBeanFactory().registerSingleton(ContextId.class.getName(), contextId); } private ContextId getContextId(ConfigurableApplicationContext applicationContext) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java index 3432a43f123..7bece66dfb6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ import org.springframework.core.env.ConfigurableEnvironment; public class FileEncodingApplicationListener implements ApplicationListener, Ordered { - private static final Log logger = LogFactory - .getLog(FileEncodingApplicationListener.class); + private static final Log logger = LogFactory.getLog(FileEncodingApplicationListener.class); @Override public int getOrder() { @@ -64,18 +63,14 @@ public class FileEncodingApplicationListener String encoding = System.getProperty("file.encoding"); String desired = environment.getProperty("spring.mandatory-file-encoding"); if (encoding != null && !desired.equalsIgnoreCase(encoding)) { - logger.error("System property 'file.encoding' is currently '" + encoding - + "'. It should be '" + desired + logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired + "' (as defined in 'spring.mandatoryFileEncoding')."); logger.error("Environment variable LANG is '" + System.getenv("LANG") - + "'. You could use a locale setting that matches encoding='" - + desired + "'."); + + "'. You could use a locale setting that matches encoding='" + desired + "'."); logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL") - + "'. You could use a locale setting that matches encoding='" - + desired + "'."); - throw new IllegalStateException( - "The Java Virtual Machine has not been configured to use the " - + "desired default character encoding (" + desired + ")."); + + "'. You could use a locale setting that matches encoding='" + desired + "'."); + throw new IllegalStateException("The Java Virtual Machine has not been configured to use the " + + "desired default character encoding (" + desired + ")."); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java index 302aa3261de..4e538be6467 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,10 +57,9 @@ public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware { } @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - if (this.beanFactory instanceof ListableBeanFactory - && getClass() == TypeExcludeFilter.class) { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + if (this.beanFactory instanceof ListableBeanFactory && getClass() == TypeExcludeFilter.class) { Collection delegates = ((ListableBeanFactory) this.beanFactory) .getBeansOfType(TypeExcludeFilter.class).values(); for (TypeExcludeFilter delegate : delegates) { @@ -74,14 +73,12 @@ public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware { @Override public boolean equals(Object obj) { - throw new IllegalStateException( - "TypeExcludeFilter " + getClass() + " has not implemented equals"); + throw new IllegalStateException("TypeExcludeFilter " + getClass() + " has not implemented equals"); } @Override public int hashCode() { - throw new IllegalStateException( - "TypeExcludeFilter " + getClass() + " has not implemented hashCode"); + throw new IllegalStateException("TypeExcludeFilter " + getClass() + " has not implemented hashCode"); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java index e874568b5a1..59056d2e8e1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -119,8 +119,7 @@ public abstract class Configurations { List ordered = new ArrayList<>(configurations); ordered.sort(COMPARATOR); List collated = collate(ordered); - LinkedHashSet> classes = collated.stream() - .flatMap(Configurations::streamClasses) + LinkedHashSet> classes = collated.stream().flatMap(Configurations::streamClasses) .collect(Collectors.toCollection(LinkedHashSet::new)); return ClassUtils.toClassArray(classes); } @@ -129,8 +128,7 @@ public abstract class Configurations { return configurations.getClasses().stream(); } - private static List collate( - List orderedConfigurations) { + private static List collate(List orderedConfigurations) { LinkedList collated = new LinkedList<>(); for (Configurations item : orderedConfigurations) { if (collated.isEmpty() || collated.getLast().getClass() != item.getClass()) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java index 8ee87f26b1b..5796920ed04 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,11 +39,9 @@ public class AnsiOutputApplicationListener @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); - Binder.get(environment) - .bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class) + Binder.get(environment).bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class) .ifBound(AnsiOutput::setEnabled); - AnsiOutput.setConsoleAvailable(environment - .getProperty("spring.output.ansi.console-available", Boolean.class)); + AnsiOutput.setConsoleAvailable(environment.getProperty("spring.output.ansi.console-available", Boolean.class)); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java index a50b7f41033..669d2330b12 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java @@ -102,8 +102,7 @@ import org.springframework.util.StringUtils; * @author Eddú Meléndez * @author Madhura Bhave */ -public class ConfigFileApplicationListener - implements EnvironmentPostProcessor, SmartApplicationListener, Ordered { +public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered { private static final String DEFAULT_PROPERTIES = "defaultProperties"; @@ -116,8 +115,7 @@ public class ConfigFileApplicationListener private static final Bindable STRING_ARRAY = Bindable.of(String[].class); - private static final Bindable> STRING_LIST = Bindable - .listOf(String.class); + private static final Bindable> STRING_LIST = Bindable.listOf(String.class); /** * The "active profiles" property name. @@ -166,33 +164,28 @@ public class ConfigFileApplicationListener @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { - onApplicationEnvironmentPreparedEvent( - (ApplicationEnvironmentPreparedEvent) event); + onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); } if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent(event); } } - private void onApplicationEnvironmentPreparedEvent( - ApplicationEnvironmentPreparedEvent event) { + private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { List postProcessors = loadPostProcessors(); postProcessors.add(this); AnnotationAwareOrderComparator.sort(postProcessors); for (EnvironmentPostProcessor postProcessor : postProcessors) { - postProcessor.postProcessEnvironment(event.getEnvironment(), - event.getSpringApplication()); + postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication()); } } List loadPostProcessors() { - return SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, - getClass().getClassLoader()); + return SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, getClass().getClassLoader()); } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { addPropertySources(environment, application.getResourceLoader()); } @@ -207,8 +200,7 @@ public class ConfigFileApplicationListener * @param resourceLoader the resource loader * @see #addPostProcessors(ConfigurableApplicationContext) */ - protected void addPropertySources(ConfigurableEnvironment environment, - ResourceLoader resourceLoader) { + protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { RandomValuePropertySource.addToEnvironment(environment); new Loader(environment, resourceLoader).load(); } @@ -218,8 +210,7 @@ public class ConfigFileApplicationListener * @param context the context to configure */ protected void addPostProcessors(ConfigurableApplicationContext context) { - context.addBeanFactoryPostProcessor( - new PropertySourceOrderingPostProcessor(context)); + context.addBeanFactoryPostProcessor(new PropertySourceOrderingPostProcessor(context)); } public void setOrder(int order) { @@ -259,8 +250,7 @@ public class ConfigFileApplicationListener * {@link BeanFactoryPostProcessor} to re-order our property sources below any * {@code @PropertySource} items added by the {@link ConfigurationClassPostProcessor}. */ - private class PropertySourceOrderingPostProcessor - implements BeanFactoryPostProcessor, Ordered { + private class PropertySourceOrderingPostProcessor implements BeanFactoryPostProcessor, Ordered { private ConfigurableApplicationContext context; @@ -274,14 +264,12 @@ public class ConfigFileApplicationListener } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { reorderSources(this.context.getEnvironment()); } private void reorderSources(ConfigurableEnvironment environment) { - PropertySource defaultProperties = environment.getPropertySources() - .remove(DEFAULT_PROPERTIES); + PropertySource defaultProperties = environment.getPropertySources().remove(DEFAULT_PROPERTIES); if (defaultProperties != null) { environment.getPropertySources().addLast(defaultProperties); } @@ -316,12 +304,10 @@ public class ConfigFileApplicationListener Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { this.environment = environment; - this.placeholdersResolver = new PropertySourcesPlaceholdersResolver( - this.environment); - this.resourceLoader = (resourceLoader != null) ? resourceLoader - : new DefaultResourceLoader(); - this.propertySourceLoaders = SpringFactoriesLoader.loadFactories( - PropertySourceLoader.class, getClass().getClassLoader()); + this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment); + this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(); + this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, + getClass().getClassLoader()); } public void load() { @@ -329,8 +315,8 @@ public class ConfigFileApplicationListener this.processedProfiles = new LinkedList<>(); this.activatedProfiles = false; this.loaded = new LinkedHashMap<>(); - MapPropertySource defaultProperties = (MapPropertySource) this.environment - .getPropertySources().get(DEFAULT_PROPERTIES); + MapPropertySource defaultProperties = (MapPropertySource) this.environment.getPropertySources() + .get(DEFAULT_PROPERTIES); replaceDefaultPropertySourceIfNecessary(defaultProperties); initializeProfiles(); while (!this.profiles.isEmpty()) { @@ -338,22 +324,18 @@ public class ConfigFileApplicationListener if (profile != null && !profile.isDefaultProfile()) { addProfileToEnvironment(profile.getName()); } - load(profile, this::getPositiveProfileFilter, - addToLoaded(MutablePropertySources::addLast, false)); + load(profile, this::getPositiveProfileFilter, addToLoaded(MutablePropertySources::addLast, false)); this.processedProfiles.add(profile); } - load(null, this::getNegativeProfileFilter, - addToLoaded(MutablePropertySources::addFirst, true)); + load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true)); addLoadedPropertySources(); resetEnvironment(defaultProperties); } - private void replaceDefaultPropertySourceIfNecessary( - MapPropertySource defaultProperties) { + private void replaceDefaultPropertySourceIfNecessary(MapPropertySource defaultProperties) { if (defaultProperties != null) { this.environment.getPropertySources().replace(DEFAULT_PROPERTIES, - new FilteredDefaultPropertySource(DEFAULT_PROPERTIES, - defaultProperties.getSource())); + new FilteredDefaultPropertySource(DEFAULT_PROPERTIES, defaultProperties.getSource())); } } @@ -366,12 +348,9 @@ public class ConfigFileApplicationListener // The default profile for these purposes is represented as null. We add it // first so that it is processed first and has lowest priority. this.profiles.add(null); - Set activatedViaProperty = getProfilesFromProperty( - ACTIVE_PROFILES_PROPERTY); - Set includedViaProperty = getProfilesFromProperty( - INCLUDE_PROFILES_PROPERTY); - List otherActiveProfiles = getOtherActiveProfiles( - activatedViaProperty, includedViaProperty); + Set activatedViaProperty = getProfilesFromProperty(ACTIVE_PROFILES_PROPERTY); + Set includedViaProperty = getProfilesFromProperty(INCLUDE_PROFILES_PROPERTY); + List otherActiveProfiles = getOtherActiveProfiles(activatedViaProperty, includedViaProperty); this.profiles.addAll(otherActiveProfiles); // Any pre-existing active profiles set via property sources (e.g. // System properties) take precedence over those added in config files. @@ -396,9 +375,8 @@ public class ConfigFileApplicationListener private List getOtherActiveProfiles(Set activatedViaProperty, Set includedViaProperty) { - return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new) - .filter((profile) -> !activatedViaProperty.contains(profile) - && !includedViaProperty.contains(profile)) + return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new).filter( + (profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile)) .collect(Collectors.toList()); } @@ -408,23 +386,20 @@ public class ConfigFileApplicationListener } if (this.activatedProfiles) { if (this.logger.isDebugEnabled()) { - this.logger.debug("Profiles already activated, '" + profiles - + "' will not be applied"); + this.logger.debug("Profiles already activated, '" + profiles + "' will not be applied"); } return; } this.profiles.addAll(profiles); if (this.logger.isDebugEnabled()) { - this.logger.debug("Activated activeProfiles " - + StringUtils.collectionToCommaDelimitedString(profiles)); + this.logger.debug("Activated activeProfiles " + StringUtils.collectionToCommaDelimitedString(profiles)); } this.activatedProfiles = true; removeUnprocessedDefaultProfiles(); } private void removeUnprocessedDefaultProfiles() { - this.profiles.removeIf( - (profile) -> (profile != null && profile.isDefaultProfile())); + this.profiles.removeIf((profile) -> (profile != null && profile.isDefaultProfile())); } private DocumentFilter getPositiveProfileFilter(Profile profile) { @@ -432,21 +407,17 @@ public class ConfigFileApplicationListener if (profile == null) { return ObjectUtils.isEmpty(document.getProfiles()); } - return ObjectUtils.containsElement(document.getProfiles(), - profile.getName()) - && this.environment - .acceptsProfiles(Profiles.of(document.getProfiles())); + return ObjectUtils.containsElement(document.getProfiles(), profile.getName()) + && this.environment.acceptsProfiles(Profiles.of(document.getProfiles())); }; } private DocumentFilter getNegativeProfileFilter(Profile profile) { - return (Document document) -> (profile == null - && !ObjectUtils.isEmpty(document.getProfiles()) && this.environment - .acceptsProfiles(Profiles.of(document.getProfiles()))); + return (Document document) -> (profile == null && !ObjectUtils.isEmpty(document.getProfiles()) + && this.environment.acceptsProfiles(Profiles.of(document.getProfiles()))); } - private DocumentConsumer addToLoaded( - BiConsumer> addMethod, + private DocumentConsumer addToLoaded(BiConsumer> addMethod, boolean checkForExisting) { return (profile, document) -> { if (checkForExisting) { @@ -462,23 +433,20 @@ public class ConfigFileApplicationListener }; } - private void load(Profile profile, DocumentFilterFactory filterFactory, - DocumentConsumer consumer) { + private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) { getSearchLocations().forEach((location) -> { boolean isFolder = location.endsWith("/"); Set names = isFolder ? getSearchNames() : NO_SEARCH_NAMES; - names.forEach( - (name) -> load(location, name, profile, filterFactory, consumer)); + names.forEach((name) -> load(location, name, profile, filterFactory, consumer)); }); } - private void load(String location, String name, Profile profile, - DocumentFilterFactory filterFactory, DocumentConsumer consumer) { + private void load(String location, String name, Profile profile, DocumentFilterFactory filterFactory, + DocumentConsumer consumer) { if (!StringUtils.hasText(name)) { for (PropertySourceLoader loader : this.propertySourceLoaders) { if (canLoadFileExtension(loader, location)) { - load(loader, location, profile, - filterFactory.getDocumentFilter(profile), consumer); + load(loader, location, profile, filterFactory.getDocumentFilter(profile), consumer); return; } } @@ -487,8 +455,8 @@ public class ConfigFileApplicationListener for (PropertySourceLoader loader : this.propertySourceLoaders) { for (String fileExtension : loader.getFileExtensions()) { if (processed.add(fileExtension)) { - loadForFileExtension(loader, location + name, "." + fileExtension, - profile, filterFactory, consumer); + loadForFileExtension(loader, location + name, "." + fileExtension, profile, filterFactory, + consumer); } } } @@ -496,13 +464,11 @@ public class ConfigFileApplicationListener private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, - fileExtension)); + .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); } - private void loadForFileExtension(PropertySourceLoader loader, String prefix, - String fileExtension, Profile profile, - DocumentFilterFactory filterFactory, DocumentConsumer consumer) { + private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension, + Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) { DocumentFilter defaultFilter = filterFactory.getDocumentFilter(null); DocumentFilter profileFilter = filterFactory.getDocumentFilter(profile); if (profile != null) { @@ -513,8 +479,7 @@ public class ConfigFileApplicationListener // Try profile specific sections in files we've already processed for (Profile processedProfile : this.processedProfiles) { if (processedProfile != null) { - String previouslyLoaded = prefix + "-" + processedProfile - + fileExtension; + String previouslyLoaded = prefix + "-" + processedProfile + fileExtension; load(loader, previouslyLoaded, profile, profileFilter, consumer); } } @@ -523,24 +488,22 @@ public class ConfigFileApplicationListener load(loader, prefix + fileExtension, profile, profileFilter, consumer); } - private void load(PropertySourceLoader loader, String location, Profile profile, - DocumentFilter filter, DocumentConsumer consumer) { + private void load(PropertySourceLoader loader, String location, Profile profile, DocumentFilter filter, + DocumentConsumer consumer) { try { Resource resource = this.resourceLoader.getResource(location); if (resource == null || !resource.exists()) { if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription( - "Skipped missing config ", location, resource, profile); + StringBuilder description = getDescription("Skipped missing config ", location, resource, + profile); this.logger.trace(description); } return; } - if (!StringUtils.hasText( - StringUtils.getFilenameExtension(resource.getFilename()))) { + if (!StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename()))) { if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription( - "Skipped empty config extension ", location, resource, - profile); + StringBuilder description = getDescription("Skipped empty config extension ", location, + resource, profile); this.logger.trace(description); } return; @@ -549,8 +512,8 @@ public class ConfigFileApplicationListener List documents = loadDocuments(loader, name, resource); if (CollectionUtils.isEmpty(documents)) { if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription( - "Skipped unloaded config ", location, resource, profile); + StringBuilder description = getDescription("Skipped unloaded config ", location, resource, + profile); this.logger.trace(description); } return; @@ -567,15 +530,14 @@ public class ConfigFileApplicationListener if (!loaded.isEmpty()) { loaded.forEach((document) -> consumer.accept(profile, document)); if (this.logger.isDebugEnabled()) { - StringBuilder description = getDescription("Loaded config file ", - location, resource, profile); + StringBuilder description = getDescription("Loaded config file ", location, resource, profile); this.logger.debug(description); } } } catch (Exception ex) { - throw new IllegalStateException("Failed to load property " - + "source from location '" + location + "'", ex); + throw new IllegalStateException("Failed to load property " + "source from location '" + location + "'", + ex); } } @@ -587,8 +549,8 @@ public class ConfigFileApplicationListener this.profiles.addAll(existingProfiles); } - private List loadDocuments(PropertySourceLoader loader, String name, - Resource resource) throws IOException { + private List loadDocuments(PropertySourceLoader loader, String name, Resource resource) + throws IOException { DocumentsCacheKey cacheKey = new DocumentsCacheKey(loader, resource); List documents = this.loadDocumentsCache.get(cacheKey); if (documents == null) { @@ -604,18 +566,14 @@ public class ConfigFileApplicationListener return Collections.emptyList(); } return loaded.stream().map((propertySource) -> { - Binder binder = new Binder( - ConfigurationPropertySources.from(propertySource), + Binder binder = new Binder(ConfigurationPropertySources.from(propertySource), this.placeholdersResolver); - return new Document(propertySource, - binder.bind("spring.profiles", STRING_ARRAY).orElse(null), - getProfiles(binder, ACTIVE_PROFILES_PROPERTY), - getProfiles(binder, INCLUDE_PROFILES_PROPERTY)); + return new Document(propertySource, binder.bind("spring.profiles", STRING_ARRAY).orElse(null), + getProfiles(binder, ACTIVE_PROFILES_PROPERTY), getProfiles(binder, INCLUDE_PROFILES_PROPERTY)); }).collect(Collectors.toList()); } - private StringBuilder getDescription(String prefix, String location, - Resource resource, Profile profile) { + private StringBuilder getDescription(String prefix, String location, Resource resource, Profile profile) { StringBuilder result = new StringBuilder(prefix); try { if (resource != null) { @@ -638,8 +596,7 @@ public class ConfigFileApplicationListener } private Set getProfiles(Binder binder, String name) { - return binder.bind(name, STRING_ARRAY).map(this::asProfileSet) - .orElse(Collections.emptySet()); + return binder.bind(name, STRING_ARRAY).map(this::asProfileSet).orElse(Collections.emptySet()); } private Set asProfileSet(String[] profileNames) { @@ -663,19 +620,16 @@ public class ConfigFileApplicationListener if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) { return getSearchLocations(CONFIG_LOCATION_PROPERTY); } - Set locations = getSearchLocations( - CONFIG_ADDITIONAL_LOCATION_PROPERTY); + Set locations = getSearchLocations(CONFIG_ADDITIONAL_LOCATION_PROPERTY); locations.addAll( - asResolvedSet(ConfigFileApplicationListener.this.searchLocations, - DEFAULT_SEARCH_LOCATIONS)); + asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS)); return locations; } private Set getSearchLocations(String propertyName) { Set locations = new LinkedHashSet<>(); if (this.environment.containsProperty(propertyName)) { - for (String path : asResolvedSet( - this.environment.getProperty(propertyName), null)) { + for (String path : asResolvedSet(this.environment.getProperty(propertyName), null)) { if (!path.contains("$")) { path = StringUtils.cleanPath(path); if (!ResourceUtils.isUrl(path)) { @@ -697,9 +651,8 @@ public class ConfigFileApplicationListener } private Set asResolvedSet(String value, String fallback) { - List list = Arrays.asList(StringUtils.trimArrayElements( - StringUtils.commaDelimitedListToStringArray((value != null) - ? this.environment.resolvePlaceholders(value) : fallback))); + List list = Arrays.asList(StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray( + (value != null) ? this.environment.resolvePlaceholders(value) : fallback))); Collections.reverse(list); return new LinkedHashSet<>(list); } @@ -720,8 +673,8 @@ public class ConfigFileApplicationListener } } - private void addLoadedPropertySource(MutablePropertySources destination, - String lastAdded, PropertySource source) { + private void addLoadedPropertySource(MutablePropertySources destination, String lastAdded, + PropertySource source) { if (lastAdded == null) { if (destination.contains(DEFAULT_PROPERTIES)) { destination.addBefore(DEFAULT_PROPERTIES, source); @@ -738,28 +691,23 @@ public class ConfigFileApplicationListener private void resetEnvironment(MapPropertySource defaultProperties) { List activeProfiles = new ArrayList<>(); handleDefaultPropertySource(defaultProperties, activeProfiles); - activeProfiles.addAll(this.processedProfiles.stream() - .filter((profile) -> profile != null && !profile.isDefaultProfile()) - .map(Profile::getName).collect(Collectors.toList())); + activeProfiles.addAll( + this.processedProfiles.stream().filter((profile) -> profile != null && !profile.isDefaultProfile()) + .map(Profile::getName).collect(Collectors.toList())); this.environment.setActiveProfiles(activeProfiles.toArray(new String[0])); } - private void handleDefaultPropertySource(MapPropertySource defaultProperties, - List activeProfiles) { + private void handleDefaultPropertySource(MapPropertySource defaultProperties, List activeProfiles) { if (defaultProperties != null) { - Binder binder = new Binder( - ConfigurationPropertySources.from(defaultProperties), + Binder binder = new Binder(ConfigurationPropertySources.from(defaultProperties), new PropertySourcesPlaceholdersResolver(this.environment)); - List includes = getDefaultProfiles(binder, - "spring.profiles.include"); + List includes = getDefaultProfiles(binder, "spring.profiles.include"); activeProfiles.addAll(includes); if (!this.activatedProfiles) { - List active = getDefaultProfiles(binder, - "spring.profiles.active"); + List active = getDefaultProfiles(binder, "spring.profiles.active"); activeProfiles.addAll(active); } - this.environment.getPropertySources().replace(DEFAULT_PROPERTIES, - defaultProperties); + this.environment.getPropertySources().replace(DEFAULT_PROPERTIES, defaultProperties); } } @@ -771,8 +719,8 @@ public class ConfigFileApplicationListener private static class FilteredDefaultPropertySource extends MapPropertySource { - private static final List FILTERED_PROPERTY = Arrays - .asList("spring.profiles.active", "spring.profiles.include"); + private static final List FILTERED_PROPERTY = Arrays.asList("spring.profiles.active", + "spring.profiles.include"); FilteredDefaultPropertySource(String name, Map source) { super(name, source); @@ -796,8 +744,8 @@ public class ConfigFileApplicationListener @Override public String[] getPropertyNames() { - return Arrays.stream(super.getPropertyNames()) - .filter((name) -> !isFilteredProperty(name)).toArray(String[]::new); + return Arrays.stream(super.getPropertyNames()).filter((name) -> !isFilteredProperty(name)) + .toArray(String[]::new); } protected boolean isFilteredProperty(String name) { @@ -879,8 +827,7 @@ public class ConfigFileApplicationListener return false; } DocumentsCacheKey other = (DocumentsCacheKey) obj; - return this.loader.equals(other.loader) - && this.resource.equals(other.resource); + return this.loader.equals(other.loader) && this.resource.equals(other.resource); } @Override @@ -903,8 +850,8 @@ public class ConfigFileApplicationListener private final Set includeProfiles; - Document(PropertySource propertySource, String[] profiles, - Set activeProfiles, Set includeProfiles) { + Document(PropertySource propertySource, String[] profiles, Set activeProfiles, + Set includeProfiles) { this.propertySource = propertySource; this.profiles = profiles; this.activeProfiles = activeProfiles; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java index 96726cb9211..e93f28344af 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Phillip Webb */ -public class DelegatingApplicationContextInitializer implements - ApplicationContextInitializer, Ordered { +public class DelegatingApplicationContextInitializer + implements ApplicationContextInitializer, Ordered { // NOTE: Similar to org.springframework.web.context.ContextLoader @@ -69,19 +69,16 @@ public class DelegatingApplicationContextInitializer implements private Class getInitializerClass(String className) throws LinkageError { try { - Class initializerClass = ClassUtils.forName(className, - ClassUtils.getDefaultClassLoader()); + Class initializerClass = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); Assert.isAssignable(ApplicationContextInitializer.class, initializerClass); return initializerClass; } catch (ClassNotFoundException ex) { - throw new ApplicationContextException( - "Failed to load context initializer class [" + className + "]", ex); + throw new ApplicationContextException("Failed to load context initializer class [" + className + "]", ex); } } - private void applyInitializerClasses(ConfigurableApplicationContext context, - List> initializerClasses) { + private void applyInitializerClasses(ConfigurableApplicationContext context, List> initializerClasses) { Class contextClass = context.getClass(); List> initializers = new ArrayList<>(); for (Class initializerClass : initializerClasses) { @@ -90,20 +87,15 @@ public class DelegatingApplicationContextInitializer implements applyInitializers(context, initializers); } - private ApplicationContextInitializer instantiateInitializer(Class contextClass, - Class initializerClass) { - Class requireContextClass = GenericTypeResolver.resolveTypeArgument( - initializerClass, ApplicationContextInitializer.class); + private ApplicationContextInitializer instantiateInitializer(Class contextClass, Class initializerClass) { + Class requireContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass, + ApplicationContextInitializer.class); Assert.isAssignable(requireContextClass, contextClass, String.format( - "Could not add context initializer [%s]" - + " as its generic parameter [%s] is not assignable " - + "from the type of application context used by this " - + "context loader [%s]: ", - initializerClass.getName(), requireContextClass.getName(), - contextClass.getName())); - return (ApplicationContextInitializer) BeanUtils - .instantiateClass(initializerClass); + "Could not add context initializer [%s]" + " as its generic parameter [%s] is not assignable " + + "from the type of application context used by this " + "context loader [%s]: ", + initializerClass.getName(), requireContextClass.getName(), contextClass.getName())); + return (ApplicationContextInitializer) BeanUtils.instantiateClass(initializerClass); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java index f1b03a65c2e..0ef73b46559 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Phillip Webb */ -public class DelegatingApplicationListener - implements ApplicationListener, Ordered { +public class DelegatingApplicationListener implements ApplicationListener, Ordered { // NOTE: Similar to org.springframework.web.context.ContextLoader @@ -70,8 +69,7 @@ public class DelegatingApplicationListener } @SuppressWarnings("unchecked") - private List> getListeners( - ConfigurableEnvironment environment) { + private List> getListeners(ConfigurableEnvironment environment) { if (environment == null) { return Collections.emptyList(); } @@ -80,16 +78,13 @@ public class DelegatingApplicationListener if (StringUtils.hasLength(classNames)) { for (String className : StringUtils.commaDelimitedListToSet(classNames)) { try { - Class clazz = ClassUtils.forName(className, - ClassUtils.getDefaultClassLoader()); - Assert.isAssignable(ApplicationListener.class, clazz, "class [" - + className + "] must implement ApplicationListener"); - listeners.add((ApplicationListener) BeanUtils - .instantiateClass(clazz)); + Class clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); + Assert.isAssignable(ApplicationListener.class, clazz, + "class [" + className + "] must implement ApplicationListener"); + listeners.add((ApplicationListener) BeanUtils.instantiateClass(clazz)); } catch (Exception ex) { - throw new ApplicationContextException( - "Failed to load context listener class [" + className + "]", + throw new ApplicationContextException("Failed to load context listener class [" + className + "]", ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationContextInitializedEvent.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationContextInitializedEvent.java index 3a51debab5c..3fc5d5eefe5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationContextInitializedEvent.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationContextInitializedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class ApplicationContextInitializedEvent extends SpringApplicationEvent { * @param args the arguments the application is running with * @param context the context that has been initialized */ - public ApplicationContextInitializedEvent(SpringApplication application, - String[] args, ConfigurableApplicationContext context) { + public ApplicationContextInitializedEvent(SpringApplication application, String[] args, + ConfigurableApplicationContext context) { super(application, args); this.context = context; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java index 73bdc7fc951..5981ec7e2d8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,8 @@ public class ApplicationEnvironmentPreparedEvent extends SpringApplicationEvent * @param args the arguments the application is running with * @param environment the environment that was just created */ - public ApplicationEnvironmentPreparedEvent(SpringApplication application, - String[] args, ConfigurableEnvironment environment) { + public ApplicationEnvironmentPreparedEvent(SpringApplication application, String[] args, + ConfigurableEnvironment environment) { super(application, args); this.environment = environment; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java index edfec4a5f7c..0607536abeb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class ApplicationFailedEvent extends SpringApplicationEvent { * @param context the context that was being created (maybe null) * @param exception the exception that caused the error */ - public ApplicationFailedEvent(SpringApplication application, String[] args, - ConfigurableApplicationContext context, Throwable exception) { + public ApplicationFailedEvent(SpringApplication application, String[] args, ConfigurableApplicationContext context, + Throwable exception) { super(application, args); this.context = context; this.exception = exception; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java index 9647f8200db..b66d20ab3ba 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ public class ApplicationReadyEvent extends SpringApplicationEvent { * @param args the arguments the application is running with * @param context the context that was being created */ - public ApplicationReadyEvent(SpringApplication application, String[] args, - ConfigurableApplicationContext context) { + public ApplicationReadyEvent(SpringApplication application, String[] args, ConfigurableApplicationContext context) { super(application, args); this.context = context; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java index bdcda013656..2b5c731cea0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,20 +66,19 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, @Override public void starting() { - this.initialMulticaster.multicastEvent( - new ApplicationStartingEvent(this.application, this.args)); + this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args)); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { - this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent( - this.application, this.args, environment)); + this.initialMulticaster + .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment)); } @Override public void contextPrepared(ConfigurableApplicationContext context) { - this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent( - this.application, this.args, context)); + this.initialMulticaster + .multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context)); } @Override @@ -90,26 +89,22 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, } context.addApplicationListener(listener); } - this.initialMulticaster.multicastEvent( - new ApplicationPreparedEvent(this.application, this.args, context)); + this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context)); } @Override public void started(ConfigurableApplicationContext context) { - context.publishEvent( - new ApplicationStartedEvent(this.application, this.args, context)); + context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context)); } @Override public void running(ConfigurableApplicationContext context) { - context.publishEvent( - new ApplicationReadyEvent(this.application, this.args, context)); + context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context)); } @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { - ApplicationFailedEvent event = new ApplicationFailedEvent(this.application, - this.args, context, exception); + ApplicationFailedEvent event = new ApplicationFailedEvent(this.application, this.args, context, exception); if (context != null && context.isActive()) { // Listeners have been registered to the application context so we should // use it at this point if we can diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/ClasspathLoggingApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/ClasspathLoggingApplicationListener.java index 19c387b1e1d..eac5ecf5bf6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/ClasspathLoggingApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/ClasspathLoggingApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,11 @@ import org.springframework.core.ResolvableType; * @author Andy Wilkinson * @since 2.0.0 */ -public final class ClasspathLoggingApplicationListener - implements GenericApplicationListener { +public final class ClasspathLoggingApplicationListener implements GenericApplicationListener { private static final int ORDER = LoggingApplicationListener.DEFAULT_ORDER + 1; - private static final Log logger = LogFactory - .getLog(ClasspathLoggingApplicationListener.class); + private static final Log logger = LogFactory.getLog(ClasspathLoggingApplicationListener.class); @Override public void onApplicationEvent(ApplicationEvent event) { @@ -53,8 +51,7 @@ public final class ClasspathLoggingApplicationListener logger.debug("Application started with classpath: " + getClasspath()); } else if (event instanceof ApplicationFailedEvent) { - logger.debug( - "Application failed to start with classpath: " + getClasspath()); + logger.debug("Application failed to start with classpath: " + getClasspath()); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java index 0160cbe642c..95024227697 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java @@ -89,17 +89,14 @@ import org.springframework.util.StringUtils; */ public class LoggingApplicationListener implements GenericApplicationListener { - private static final ConfigurationPropertyName LOGGING_LEVEL = ConfigurationPropertyName - .of("logging.level"); + private static final ConfigurationPropertyName LOGGING_LEVEL = ConfigurationPropertyName.of("logging.level"); - private static final ConfigurationPropertyName LOGGING_GROUP = ConfigurationPropertyName - .of("logging.group"); + private static final ConfigurationPropertyName LOGGING_GROUP = ConfigurationPropertyName.of("logging.group"); - private static final Bindable> STRING_STRING_MAP = Bindable - .mapOf(String.class, String.class); + private static final Bindable> STRING_STRING_MAP = Bindable.mapOf(String.class, String.class); - private static final Bindable> STRING_STRINGS_MAP = Bindable - .mapOf(String.class, String[].class); + private static final Bindable> STRING_STRINGS_MAP = Bindable.mapOf(String.class, + String[].class); /** * The default order for the LoggingApplicationListener. @@ -131,8 +128,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { loggers.add("web", "org.springframework.http"); loggers.add("web", "org.springframework.web"); loggers.add("web", "org.springframework.boot.actuate.endpoint.web"); - loggers.add("web", - "org.springframework.boot.web.servlet.ServletContextInitializerBeans"); + loggers.add("web", "org.springframework.boot.web.servlet.ServletContextInitializerBeans"); loggers.add("sql", "org.springframework.jdbc.core"); loggers.add("sql", "org.hibernate.SQL"); loggers.add("sql", "org.jooq.tools.LoggerListener"); @@ -154,11 +150,10 @@ public class LoggingApplicationListener implements GenericApplicationListener { } private static final Class[] EVENT_TYPES = { ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, - ContextClosedEvent.class, ApplicationFailedEvent.class }; + ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, ContextClosedEvent.class, + ApplicationFailedEvent.class }; - private static final Class[] SOURCE_TYPES = { SpringApplication.class, - ApplicationContext.class }; + private static final Class[] SOURCE_TYPES = { SpringApplication.class, ApplicationContext.class }; private static final AtomicBoolean shutdownHookRegistered = new AtomicBoolean(false); @@ -199,14 +194,13 @@ public class LoggingApplicationListener implements GenericApplicationListener { onApplicationStartingEvent((ApplicationStartingEvent) event); } else if (event instanceof ApplicationEnvironmentPreparedEvent) { - onApplicationEnvironmentPreparedEvent( - (ApplicationEnvironmentPreparedEvent) event); + onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); } else if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } - else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event) - .getApplicationContext().getParent() == null) { + else if (event instanceof ContextClosedEvent + && ((ContextClosedEvent) event).getApplicationContext().getParent() == null) { onContextClosedEvent(); } else if (event instanceof ApplicationFailedEvent) { @@ -215,23 +209,19 @@ public class LoggingApplicationListener implements GenericApplicationListener { } private void onApplicationStartingEvent(ApplicationStartingEvent event) { - this.loggingSystem = LoggingSystem - .get(event.getSpringApplication().getClassLoader()); + this.loggingSystem = LoggingSystem.get(event.getSpringApplication().getClassLoader()); this.loggingSystem.beforeInitialize(); } - private void onApplicationEnvironmentPreparedEvent( - ApplicationEnvironmentPreparedEvent event) { + private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { if (this.loggingSystem == null) { - this.loggingSystem = LoggingSystem - .get(event.getSpringApplication().getClassLoader()); + this.loggingSystem = LoggingSystem.get(event.getSpringApplication().getClassLoader()); } initialize(event.getEnvironment(), event.getSpringApplication().getClassLoader()); } private void onApplicationPreparedEvent(ApplicationPreparedEvent event) { - ConfigurableListableBeanFactory beanFactory = event.getApplicationContext() - .getBeanFactory(); + ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory(); if (!beanFactory.containsBean(LOGGING_SYSTEM_BEAN_NAME)) { beanFactory.registerSingleton(LOGGING_SYSTEM_BEAN_NAME, this.loggingSystem); } @@ -255,8 +245,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { * @param environment the environment * @param classLoader the classloader */ - protected void initialize(ConfigurableEnvironment environment, - ClassLoader classLoader) { + protected void initialize(ConfigurableEnvironment environment, ClassLoader classLoader) { new LoggingSystemProperties(environment).apply(); LogFile logFile = LogFile.get(environment); if (logFile != null) { @@ -284,10 +273,8 @@ public class LoggingApplicationListener implements GenericApplicationListener { return (value != null && !value.equals("false")); } - private void initializeSystem(ConfigurableEnvironment environment, - LoggingSystem system, LogFile logFile) { - LoggingInitializationContext initializationContext = new LoggingInitializationContext( - environment); + private void initializeSystem(ConfigurableEnvironment environment, LoggingSystem system, LogFile logFile) { + LoggingInitializationContext initializationContext = new LoggingInitializationContext(environment); String logConfig = environment.getProperty(CONFIG_PROPERTY); if (ignoreLogConfig(logConfig)) { system.initialize(initializationContext, null, logFile); @@ -299,8 +286,8 @@ public class LoggingApplicationListener implements GenericApplicationListener { } catch (Exception ex) { // NOTE: We can't use the logger here to report the problem - System.err.println("Logging system failed to initialize " - + "using configuration from '" + logConfig + "'"); + System.err.println( + "Logging system failed to initialize " + "using configuration from '" + logConfig + "'"); ex.printStackTrace(System.err); throw new IllegalStateException(ex); } @@ -311,8 +298,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { return !StringUtils.hasLength(logConfig) || logConfig.startsWith("-D"); } - private void initializeFinalLoggingLevels(ConfigurableEnvironment environment, - LoggingSystem system) { + private void initializeFinalLoggingLevels(ConfigurableEnvironment environment, LoggingSystem system) { if (this.springBootLogging != null) { initializeLogLevel(system, this.springBootLogging); } @@ -340,8 +326,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { Binder binder = Binder.get(environment); Map groups = getGroups(); binder.bind(LOGGING_GROUP, STRING_STRINGS_MAP.withExistingValue(groups)); - Map levels = binder.bind(LOGGING_LEVEL, STRING_STRING_MAP) - .orElseGet(Collections::emptyMap); + Map levels = binder.bind(LOGGING_LEVEL, STRING_STRING_MAP).orElseGet(Collections::emptyMap); levels.forEach((name, level) -> { String[] groupedNames = groups.get(name); if (ObjectUtils.isEmpty(groupedNames)) { @@ -355,8 +340,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { private Map getGroups() { Map groups = new LinkedHashMap<>(); - DEFAULT_GROUP_LOGGERS.forEach( - (name, loggers) -> groups.put(name, StringUtils.toStringArray(loggers))); + DEFAULT_GROUP_LOGGERS.forEach((name, loggers) -> groups.put(name, StringUtils.toStringArray(loggers))); return groups; } @@ -384,14 +368,11 @@ public class LoggingApplicationListener implements GenericApplicationListener { return LogLevel.valueOf(trimmedLevel.toUpperCase(Locale.ENGLISH)); } - private void registerShutdownHookIfNecessary(Environment environment, - LoggingSystem loggingSystem) { - boolean registerShutdownHook = environment - .getProperty(REGISTER_SHUTDOWN_HOOK_PROPERTY, Boolean.class, false); + private void registerShutdownHookIfNecessary(Environment environment, LoggingSystem loggingSystem) { + boolean registerShutdownHook = environment.getProperty(REGISTER_SHUTDOWN_HOOK_PROPERTY, Boolean.class, false); if (registerShutdownHook) { Runnable shutdownHandler = loggingSystem.getShutdownHandler(); - if (shutdownHandler != null - && shutdownHookRegistered.compareAndSet(false, true)) { + if (shutdownHandler != null && shutdownHookRegistered.compareAndSet(false, true)) { registerShutdownHook(new Thread(shutdownHandler)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata.java index f17b259cd39..25710ccdabd 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata.java @@ -42,16 +42,13 @@ public class ConfigurationBeanFactoryMetadata implements ApplicationContextAware /** * The bean name that this class is registered with. */ - public static final String BEAN_NAME = ConfigurationBeanFactoryMetadata.class - .getName(); + public static final String BEAN_NAME = ConfigurationBeanFactoryMetadata.class.getName(); private ConfigurableApplicationContext applicationContext; - public Map getBeansWithFactoryAnnotation( - Class type) { + public Map getBeansWithFactoryAnnotation(Class type) { Map result = new HashMap<>(); - for (String name : this.applicationContext.getBeanFactory() - .getBeanDefinitionNames()) { + for (String name : this.applicationContext.getBeanFactory().getBeanDefinitionNames()) { if (findFactoryAnnotation(name, type) != null) { result.put(name, this.applicationContext.getBean(name)); } @@ -59,15 +56,13 @@ public class ConfigurationBeanFactoryMetadata implements ApplicationContextAware return result; } - public A findFactoryAnnotation(String beanName, - Class type) { + public A findFactoryAnnotation(String beanName, Class type) { Method method = findFactoryMethod(beanName); return (method != null) ? AnnotationUtils.findAnnotation(method, type) : null; } public Method findFactoryMethod(String beanName) { - ConfigurableListableBeanFactory beanFactory = this.applicationContext - .getBeanFactory(); + ConfigurableListableBeanFactory beanFactory = this.applicationContext.getBeanFactory(); if (beanFactory.containsBeanDefinition(beanName)) { BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName); if (beanDefinition instanceof RootBeanDefinition) { @@ -78,8 +73,7 @@ public class ConfigurationBeanFactoryMetadata implements ApplicationContextAware } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (ConfigurableApplicationContext) applicationContext; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinition.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinition.java index 1c6e47cc4e3..2509e2be6f2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinition.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinition.java @@ -35,40 +35,35 @@ import org.springframework.validation.annotation.Validated; */ final class ConfigurationPropertiesBeanDefinition extends GenericBeanDefinition { - static ConfigurationPropertiesBeanDefinition from( - ConfigurableListableBeanFactory beanFactory, String beanName, Class type) { + static ConfigurationPropertiesBeanDefinition from(ConfigurableListableBeanFactory beanFactory, String beanName, + Class type) { ConfigurationPropertiesBeanDefinition beanDefinition = new ConfigurationPropertiesBeanDefinition(); beanDefinition.setBeanClass(type); beanDefinition.setInstanceSupplier(createBean(beanFactory, beanName, type)); return beanDefinition; } - private static Supplier createBean(ConfigurableListableBeanFactory beanFactory, - String beanName, Class type) { + private static Supplier createBean(ConfigurableListableBeanFactory beanFactory, String beanName, + Class type) { return () -> { // FIXME review - ConfigurationProperties annotation = getAnnotation(type, - ConfigurationProperties.class); + ConfigurationProperties annotation = getAnnotation(type, ConfigurationProperties.class); Validated validated = getAnnotation(type, Validated.class); - Annotation[] annotations = (validated != null) - ? new Annotation[] { annotation, validated } + Annotation[] annotations = (validated != null) ? new Annotation[] { annotation, validated } : new Annotation[] { annotation }; Bindable bindable = Bindable.of(type).withAnnotations(annotations); - ConfigurationPropertiesBinder binder = beanFactory.getBean( - ConfigurationPropertiesBinder.BEAN_NAME, + ConfigurationPropertiesBinder binder = beanFactory.getBean(ConfigurationPropertiesBinder.BEAN_NAME, ConfigurationPropertiesBinder.class); try { return binder.bind(bindable).orElseCreate(type); } catch (Exception ex) { - throw new ConfigurationPropertiesBindException(beanName, type, annotation, - ex); + throw new ConfigurationPropertiesBindException(beanName, type, annotation, ex); } }; } - private static A getAnnotation(Class type, - Class annotationType) { + private static A getAnnotation(Class type, Class annotationType) { return AnnotationUtils.findAnnotation(type, annotationType); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinitionRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinitionRegistrar.java index 7f471f1ec96..d35a13ca8da 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinitionRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanDefinitionRegistrar.java @@ -46,25 +46,22 @@ final class ConfigurationPropertiesBeanDefinitionRegistrar { private ConfigurationPropertiesBeanDefinitionRegistrar() { } - public static void register(BeanDefinitionRegistry registry, - ConfigurableListableBeanFactory beanFactory, Class type) { - MergedAnnotation annotation = MergedAnnotations - .from(type, SearchStrategy.EXHAUSTIVE).get(ConfigurationProperties.class); + public static void register(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory, + Class type) { + MergedAnnotation annotation = MergedAnnotations.from(type, SearchStrategy.EXHAUSTIVE) + .get(ConfigurationProperties.class); String name = getName(type, annotation); if (!containsBeanDefinition(beanFactory, name)) { registerBeanDefinition(registry, beanFactory, name, type, annotation); } } - private static String getName(Class type, - MergedAnnotation annotation) { + private static String getName(Class type, MergedAnnotation annotation) { String prefix = annotation.isPresent() ? annotation.getString("prefix") : ""; - return (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() - : type.getName()); + return (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() : type.getName()); } - private static boolean containsBeanDefinition( - ConfigurableListableBeanFactory beanFactory, String name) { + private static boolean containsBeanDefinition(ConfigurableListableBeanFactory beanFactory, String name) { if (beanFactory.containsBeanDefinition(name)) { return true; } @@ -78,15 +75,13 @@ final class ConfigurationPropertiesBeanDefinitionRegistrar { private static void registerBeanDefinition(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory, String name, Class type, MergedAnnotation annotation) { - Assert.isTrue(annotation.isPresent(), - () -> "No " + ConfigurationProperties.class.getSimpleName() - + " annotation found on '" + type.getName() + "'."); - registry.registerBeanDefinition(name, - createBeanDefinition(beanFactory, name, type)); + Assert.isTrue(annotation.isPresent(), () -> "No " + ConfigurationProperties.class.getSimpleName() + + " annotation found on '" + type.getName() + "'."); + registry.registerBeanDefinition(name, createBeanDefinition(beanFactory, name, type)); } - private static BeanDefinition createBeanDefinition( - ConfigurableListableBeanFactory beanFactory, String name, Class type) { + private static BeanDefinition createBeanDefinition(ConfigurableListableBeanFactory beanFactory, String name, + Class type) { if (canBindAtCreationTime(type)) { return ConfigurationPropertiesBeanDefinition.from(beanFactory, name, type); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java index 5a9e5f13109..fef8c68136a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java @@ -37,19 +37,16 @@ import org.springframework.util.MultiValueMap; class ConfigurationPropertiesBeanRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { ConfigurableListableBeanFactory beanFactory = (ConfigurableListableBeanFactory) registry; - getTypes(metadata) - .forEach((type) -> ConfigurationPropertiesBeanDefinitionRegistrar - .register(registry, beanFactory, type)); + getTypes(metadata).forEach( + (type) -> ConfigurationPropertiesBeanDefinitionRegistrar.register(registry, beanFactory, type)); } private List> getTypes(AnnotationMetadata metadata) { - MultiValueMap attributes = metadata.getAllAnnotationAttributes( - EnableConfigurationProperties.class.getName(), false); - return collectClasses( - (attributes != null) ? attributes.get("value") : Collections.emptyList()); + MultiValueMap attributes = metadata + .getAllAnnotationAttributes(EnableConfigurationProperties.class.getName(), false); + return collectClasses((attributes != null) ? attributes.get("value") : Collections.emptyList()); } private List> collectClasses(List values) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindException.java index 1c6b886ea06..fa91e8d823e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindException.java @@ -33,8 +33,8 @@ public class ConfigurationPropertiesBindException extends BeanCreationException private final ConfigurationProperties annotation; - ConfigurationPropertiesBindException(String beanName, Class beanType, - ConfigurationProperties annotation, Exception cause) { + ConfigurationPropertiesBindException(String beanName, Class beanType, ConfigurationProperties annotation, + Exception cause) { super(beanName, getMessage(beanType, annotation), cause); this.beanType = beanType; this.annotation = annotation; @@ -56,8 +56,7 @@ public class ConfigurationPropertiesBindException extends BeanCreationException return this.annotation; } - private static String getMessage(Class beanType, - ConfigurationProperties annotation) { + private static String getMessage(Class beanType, ConfigurationProperties annotation) { StringBuilder message = new StringBuilder(); message.append("Could not bind properties to '"); message.append(ClassUtils.getShortName(beanType)).append("' : "); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java index 726a253c45c..bf37e420c65 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java @@ -77,29 +77,24 @@ class ConfigurationPropertiesBinder implements ApplicationContextAware { } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; - this.propertySources = new PropertySourcesDeducer(applicationContext) - .getPropertySources(); - this.configurationPropertiesValidator = getConfigurationPropertiesValidator( - applicationContext, this.validatorBeanName); - this.jsr303Present = ConfigurationPropertiesJsr303Validator - .isJsr303Present(applicationContext); + this.propertySources = new PropertySourcesDeducer(applicationContext).getPropertySources(); + this.configurationPropertiesValidator = getConfigurationPropertiesValidator(applicationContext, + this.validatorBeanName); + this.jsr303Present = ConfigurationPropertiesJsr303Validator.isJsr303Present(applicationContext); } public BindResult bind(Bindable target) { - ConfigurationProperties annotation = target - .getAnnotation(ConfigurationProperties.class); - Assert.state(annotation != null, - () -> "Missing @ConfigurationProperties on " + target); + ConfigurationProperties annotation = target.getAnnotation(ConfigurationProperties.class); + Assert.state(annotation != null, () -> "Missing @ConfigurationProperties on " + target); List validators = getValidators(target); BindHandler bindHandler = getBindHandler(annotation, validators); return getBinder().bind(annotation.prefix(), target, bindHandler); } - private Validator getConfigurationPropertiesValidator( - ApplicationContext applicationContext, String validatorBeanName) { + private Validator getConfigurationPropertiesValidator(ApplicationContext applicationContext, + String validatorBeanName) { if (applicationContext.containsBean(validatorBeanName)) { return applicationContext.getBean(validatorBeanName, Validator.class); } @@ -122,14 +117,12 @@ class ConfigurationPropertiesBinder implements ApplicationContextAware { private Validator getJsr303Validator() { if (this.jsr303Validator == null) { - this.jsr303Validator = new ConfigurationPropertiesJsr303Validator( - this.applicationContext); + this.jsr303Validator = new ConfigurationPropertiesJsr303Validator(this.applicationContext); } return this.jsr303Validator; } - private BindHandler getBindHandler(ConfigurationProperties annotation, - List validators) { + private BindHandler getBindHandler(ConfigurationProperties annotation, List validators) { BindHandler handler = new IgnoreTopLevelConverterNotFoundBindHandler(); if (annotation.ignoreInvalidFields()) { handler = new IgnoreErrorsBindHandler(handler); @@ -139,8 +132,7 @@ class ConfigurationPropertiesBinder implements ApplicationContextAware { handler = new NoUnboundElementsBindHandler(handler, filter); } if (!validators.isEmpty()) { - handler = new ValidationBindHandler(handler, - validators.toArray(new Validator[0])); + handler = new ValidationBindHandler(handler, validators.toArray(new Validator[0])); } for (ConfigurationPropertiesBindHandlerAdvisor advisor : getBindHandlerAdvisors()) { handler = advisor.apply(handler); @@ -149,16 +141,14 @@ class ConfigurationPropertiesBinder implements ApplicationContextAware { } private List getBindHandlerAdvisors() { - return this.applicationContext - .getBeanProvider(ConfigurationPropertiesBindHandlerAdvisor.class) - .orderedStream().collect(Collectors.toList()); + return this.applicationContext.getBeanProvider(ConfigurationPropertiesBindHandlerAdvisor.class).orderedStream() + .collect(Collectors.toList()); } private Binder getBinder() { if (this.binder == null) { - this.binder = new Binder(getConfigurationPropertySources(), - getPropertySourcesPlaceholdersResolver(), getConversionService(), - getPropertyEditorInitializer()); + this.binder = new Binder(getConfigurationPropertySources(), getPropertySourcesPlaceholdersResolver(), + getConversionService(), getPropertyEditorInitializer()); } return this.binder; } @@ -172,14 +162,12 @@ class ConfigurationPropertiesBinder implements ApplicationContextAware { } private ConversionService getConversionService() { - return new ConversionServiceDeducer(this.applicationContext) - .getConversionService(); + return new ConversionServiceDeducer(this.applicationContext).getConversionService(); } private Consumer getPropertyEditorInitializer() { if (this.applicationContext instanceof ConfigurableApplicationContext) { - return ((ConfigurableApplicationContext) this.applicationContext) - .getBeanFactory()::copyRegisteredEditorsTo; + return ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory()::copyRegisteredEditorsTo; } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java index 897f08736bb..79965a2ba4e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java @@ -44,14 +44,13 @@ import org.springframework.validation.annotation.Validated; * @author Stephane Nicoll * @author Madhura Bhave */ -public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProcessor, - PriorityOrdered, ApplicationContextAware, InitializingBean { +public class ConfigurationPropertiesBindingPostProcessor + implements BeanPostProcessor, PriorityOrdered, ApplicationContextAware, InitializingBean { /** * The bean name that this post-processor is registered with. */ - public static final String BEAN_NAME = ConfigurationPropertiesBindingPostProcessor.class - .getName(); + public static final String BEAN_NAME = ConfigurationPropertiesBindingPostProcessor.class.getName(); /** * The bean name of the configuration properties validator. @@ -68,8 +67,7 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc private ConfigurationPropertiesBinder configurationPropertiesBinder; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -77,11 +75,9 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc public void afterPropertiesSet() throws Exception { // We can't use constructor injection of the application context because // it causes eager factory bean initialization - this.beanFactoryMetadata = this.applicationContext.getBean( - ConfigurationBeanFactoryMetadata.BEAN_NAME, + this.beanFactoryMetadata = this.applicationContext.getBean(ConfigurationBeanFactoryMetadata.BEAN_NAME, ConfigurationBeanFactoryMetadata.class); - this.configurationPropertiesBinder = this.applicationContext.getBean( - ConfigurationPropertiesBinder.BEAN_NAME, + this.configurationPropertiesBinder = this.applicationContext.getBean(ConfigurationPropertiesBinder.BEAN_NAME, ConfigurationPropertiesBinder.class); } @@ -91,10 +87,8 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { - ConfigurationProperties annotation = getAnnotation(bean, beanName, - ConfigurationProperties.class); + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + ConfigurationProperties annotation = getAnnotation(bean, beanName, ConfigurationProperties.class); if (annotation != null && !hasBeenBound(beanName)) { bind(bean, beanName, annotation); } @@ -114,17 +108,14 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc private void bind(Object bean, String beanName, ConfigurationProperties annotation) { ResolvableType type = getBeanType(bean, beanName); Validated validated = getAnnotation(bean, beanName, Validated.class); - Annotation[] annotations = (validated != null) - ? new Annotation[] { annotation, validated } + Annotation[] annotations = (validated != null) ? new Annotation[] { annotation, validated } : new Annotation[] { annotation }; - Bindable target = Bindable.of(type).withExistingValue(bean) - .withAnnotations(annotations); + Bindable target = Bindable.of(type).withExistingValue(bean).withAnnotations(annotations); try { this.configurationPropertiesBinder.bind(target); } catch (Exception ex) { - throw new ConfigurationPropertiesBindException(beanName, bean.getClass(), - annotation, ex); + throw new ConfigurationPropertiesBindException(beanName, bean.getClass(), annotation, ex); } } @@ -136,8 +127,7 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc return ResolvableType.forClass(bean.getClass()); } - private A getAnnotation(Object bean, String beanName, - Class type) { + private A getAnnotation(Object bean, String beanName, Class type) { A annotation = this.beanFactoryMetadata.findFactoryAnnotation(beanName, type); if (annotation == null) { annotation = AnnotationUtils.findAnnotation(bean.getClass(), type); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java index 1f43b1fc7ce..6e6d9a44f56 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java @@ -29,8 +29,7 @@ import org.springframework.core.type.AnnotationMetadata; * @author Dave Syer * @author Phillip Webb */ -public class ConfigurationPropertiesBindingPostProcessorRegistrar - implements ImportBeanDefinitionRegistrar { +public class ConfigurationPropertiesBindingPostProcessorRegistrar implements ImportBeanDefinitionRegistrar { /** * The bean name of the configuration properties validator. @@ -38,13 +37,11 @@ public class ConfigurationPropertiesBindingPostProcessorRegistrar public static final String VALIDATOR_BEAN_NAME = "configurationPropertiesValidator"; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(ConfigurationPropertiesBinder.BEAN_NAME)) { registerConfigurationPropertiesBinder(registry); } - if (!registry.containsBeanDefinition( - ConfigurationPropertiesBindingPostProcessor.BEAN_NAME)) { + if (!registry.containsBeanDefinition(ConfigurationPropertiesBindingPostProcessor.BEAN_NAME)) { registerConfigurationPropertiesBindingPostProcessor(registry); registerConfigurationBeanFactoryMetadata(registry); } @@ -54,28 +51,22 @@ public class ConfigurationPropertiesBindingPostProcessorRegistrar GenericBeanDefinition definition = new GenericBeanDefinition(); definition.setBeanClass(ConfigurationPropertiesBinder.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - definition.getConstructorArgumentValues().addIndexedArgumentValue(0, - VALIDATOR_BEAN_NAME); - registry.registerBeanDefinition(ConfigurationPropertiesBinder.BEAN_NAME, - definition); + definition.getConstructorArgumentValues().addIndexedArgumentValue(0, VALIDATOR_BEAN_NAME); + registry.registerBeanDefinition(ConfigurationPropertiesBinder.BEAN_NAME, definition); } - private void registerConfigurationPropertiesBindingPostProcessor( - BeanDefinitionRegistry registry) { + private void registerConfigurationPropertiesBindingPostProcessor(BeanDefinitionRegistry registry) { GenericBeanDefinition definition = new GenericBeanDefinition(); definition.setBeanClass(ConfigurationPropertiesBindingPostProcessor.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - registry.registerBeanDefinition( - ConfigurationPropertiesBindingPostProcessor.BEAN_NAME, definition); + registry.registerBeanDefinition(ConfigurationPropertiesBindingPostProcessor.BEAN_NAME, definition); } - private void registerConfigurationBeanFactoryMetadata( - BeanDefinitionRegistry registry) { + private void registerConfigurationBeanFactoryMetadata(BeanDefinitionRegistry registry) { GenericBeanDefinition definition = new GenericBeanDefinition(); definition.setBeanClass(ConfigurationBeanFactoryMetadata.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - registry.registerBeanDefinition(ConfigurationBeanFactoryMetadata.BEAN_NAME, - definition); + registry.registerBeanDefinition(ConfigurationBeanFactoryMetadata.BEAN_NAME, definition); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java index c8d5d93c1ef..c46e0fd3b3a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; final class ConfigurationPropertiesJsr303Validator implements Validator { private static final String[] VALIDATOR_CLASSES = { "javax.validation.Validator", - "javax.validation.ValidatorFactory", - "javax.validation.bootstrap.GenericBootstrap" }; + "javax.validation.ValidatorFactory", "javax.validation.bootstrap.GenericBootstrap" }; private final Delegate delegate; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java index 0e1c45da36a..b6e02e8c4ac 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java @@ -51,15 +51,14 @@ class ConfigurationPropertiesScanRegistrar private ResourceLoader resourceLoader; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Set packagesToScan = getPackagesToScan(importingClassMetadata); register(registry, (ConfigurableListableBeanFactory) registry, packagesToScan); } private Set getPackagesToScan(AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata - .getAnnotationAttributes(ConfigurationPropertiesScan.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ConfigurationPropertiesScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); @@ -72,15 +71,14 @@ class ConfigurationPropertiesScanRegistrar return packagesToScan; } - protected void register(BeanDefinitionRegistry registry, - ConfigurableListableBeanFactory beanFactory, Set packagesToScan) { + protected void register(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory, + Set packagesToScan) { scan(packagesToScan, beanFactory, registry); } protected void scan(Set packages, ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { - ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( - false); + ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.setEnvironment(this.environment); scanner.setResourceLoader(this.resourceLoader); scanner.addIncludeFilter(new AnnotationTypeFilter(ConfigurationProperties.class)); @@ -91,17 +89,14 @@ class ConfigurationPropertiesScanRegistrar } } - private void scan(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, - ClassPathScanningCandidateComponentProvider scanner, String basePackage) - throws LinkageError { + private void scan(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + ClassPathScanningCandidateComponentProvider scanner, String basePackage) throws LinkageError { for (BeanDefinition candidate : scanner.findCandidateComponents(basePackage)) { String beanClassName = candidate.getBeanClassName(); try { Class type = ClassUtils.forName(beanClassName, null); validateScanConfiguration(type); - ConfigurationPropertiesBeanDefinitionRegistrar.register(registry, - beanFactory, type); + ConfigurationPropertiesBeanDefinitionRegistrar.register(registry, beanFactory, type); } catch (ClassNotFoundException ex) { // Ignore @@ -111,11 +106,9 @@ class ConfigurationPropertiesScanRegistrar private void validateScanConfiguration(Class type) { MergedAnnotation component = MergedAnnotations - .from(type, MergedAnnotations.SearchStrategy.EXHAUSTIVE) - .get(Component.class); + .from(type, MergedAnnotations.SearchStrategy.EXHAUSTIVE).get(Component.class); if (component.isPresent()) { - throw new InvalidConfigurationPropertiesException(type, - component.getRoot().getType()); + throw new InvalidConfigurationPropertiesException(type, component.getRoot().getType()); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java index 530d7277660..f4199ed2464 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,13 +47,11 @@ class ConversionServiceDeducer { public ConversionService getConversionService() { try { - return this.applicationContext.getBean( - ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, + return this.applicationContext.getBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class); } catch (NoSuchBeanDefinitionException ex) { - return new Factory(this.applicationContext.getAutowireCapableBeanFactory()) - .create(); + return new Factory(this.applicationContext.getAutowireCapableBeanFactory()).create(); } } @@ -65,24 +63,20 @@ class ConversionServiceDeducer { private final List genericConverters; Factory(BeanFactory beanFactory) { - this.converters = beans(beanFactory, Converter.class, - ConfigurationPropertiesBinding.VALUE); - this.genericConverters = beans(beanFactory, GenericConverter.class, - ConfigurationPropertiesBinding.VALUE); + this.converters = beans(beanFactory, Converter.class, ConfigurationPropertiesBinding.VALUE); + this.genericConverters = beans(beanFactory, GenericConverter.class, ConfigurationPropertiesBinding.VALUE); } - private List beans(BeanFactory beanFactory, Class type, - String qualifier) { + private List beans(BeanFactory beanFactory, Class type, String qualifier) { if (beanFactory instanceof ListableBeanFactory) { return beans(type, qualifier, (ListableBeanFactory) beanFactory); } return Collections.emptyList(); } - private List beans(Class type, String qualifier, - ListableBeanFactory beanFactory) { - return new ArrayList<>(BeanFactoryAnnotationUtils - .qualifiedBeansOfType(beanFactory, type, qualifier).values()); + private List beans(Class type, String qualifier, ListableBeanFactory beanFactory) { + return new ArrayList<>( + BeanFactoryAnnotationUtils.qualifiedBeansOfType(beanFactory, type, qualifier).values()); } public ConversionService create() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationProperties.java index 4019f7c07f8..473aa966ab9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationProperties.java @@ -36,8 +36,7 @@ import org.springframework.context.annotation.Import; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented -@Import({ ConfigurationPropertiesBeanRegistrar.class, - ConfigurationPropertiesBindingPostProcessorRegistrar.class }) +@Import({ ConfigurationPropertiesBeanRegistrar.class, ConfigurationPropertiesBindingPostProcessorRegistrar.class }) public @interface EnableConfigurationProperties { /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/InvalidConfigurationPropertiesException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/InvalidConfigurationPropertiesException.java index 9c54d5a43d8..2e611d94e45 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/InvalidConfigurationPropertiesException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/InvalidConfigurationPropertiesException.java @@ -30,8 +30,7 @@ public class InvalidConfigurationPropertiesException extends RuntimeException { private final Class component; - public InvalidConfigurationPropertiesException(Class configurationProperties, - Class component) { + public InvalidConfigurationPropertiesException(Class configurationProperties, Class component) { super("Found @" + component.getSimpleName() + " and @ConfigurationProperties on " + configurationProperties.getName() + "."); Assert.notNull(configurationProperties, "Class must not be null"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java index 080ca7a55c3..f5486abb291 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -229,8 +229,7 @@ public final class PropertyMapper { * @return a new filtered source instance */ public Source whenNonNull() { - return new Source<>(new NullPointerExceptionSafeSupplier<>(this.supplier), - Objects::nonNull); + return new Source<>(new NullPointerExceptionSafeSupplier<>(this.supplier), Objects::nonNull); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java index 459bc0ca84c..3fbad00ecc7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,8 @@ class PropertySourcesDeducer { if (sources != null) { return sources; } - throw new IllegalStateException("Unable to obtain PropertySources from " - + "PropertySourcesPlaceholderConfigurer or Environment"); + throw new IllegalStateException( + "Unable to obtain PropertySources from " + "PropertySourcesPlaceholderConfigurer or Environment"); } private MutablePropertySources extractEnvironmentPropertySources() { @@ -72,9 +72,8 @@ class PropertySourcesDeducer { return beans.values().iterator().next(); } if (beans.size() > 1 && logger.isWarnEnabled()) { - logger.warn( - "Multiple PropertySourcesPlaceholderConfigurer " + "beans registered " - + beans.keySet() + ", falling back to Environment"); + logger.warn("Multiple PropertySourcesPlaceholderConfigurer " + "beans registered " + beans.keySet() + + ", falling back to Environment"); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AbstractBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AbstractBindHandler.java index 0dc767b20db..7c0fd742fd8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AbstractBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AbstractBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,26 +47,24 @@ public abstract class AbstractBindHandler implements BindHandler { } @Override - public Bindable onStart(ConfigurationPropertyName name, Bindable target, - BindContext context) { + public Bindable onStart(ConfigurationPropertyName name, Bindable target, BindContext context) { return this.parent.onStart(name, target, context); } @Override - public Object onSuccess(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) { + public Object onSuccess(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) { return this.parent.onSuccess(name, target, context, result); } @Override - public Object onFailure(ConfigurationPropertyName name, Bindable target, - BindContext context, Exception error) throws Exception { + public Object onFailure(ConfigurationPropertyName name, Bindable target, BindContext context, Exception error) + throws Exception { return this.parent.onFailure(name, target, context, error); } @Override - public void onFinish(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) throws Exception { + public void onFinish(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) + throws Exception { this.parent.onFinish(name, target, context, result); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateBinder.java index a445aa87ef2..bb3c3fe483b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ abstract class AggregateBinder { * @param source the configuration property source or {@code null} for all sources. * @return if recursive binding is supported */ - protected abstract boolean isAllowRecursiveBinding( - ConfigurationPropertySource source); + protected abstract boolean isAllowRecursiveBinding(ConfigurationPropertySource source); /** * Perform binding for the aggregate. @@ -53,8 +52,7 @@ abstract class AggregateBinder { * @return the bound aggregate or null */ @SuppressWarnings("unchecked") - public final Object bind(ConfigurationPropertyName name, Bindable target, - AggregateElementBinder elementBinder) { + public final Object bind(ConfigurationPropertyName name, Bindable target, AggregateElementBinder elementBinder) { Object result = bindAggregate(name, target, elementBinder); Supplier value = target.getValue(); if (result == null || value == null) { @@ -70,8 +68,8 @@ abstract class AggregateBinder { * @param elementBinder an element binder * @return the bound result */ - protected abstract Object bindAggregate(ConfigurationPropertyName name, - Bindable target, AggregateElementBinder elementBinder); + protected abstract Object bindAggregate(ConfigurationPropertyName name, Bindable target, + AggregateElementBinder elementBinder); /** * Merge any additional elements into the existing aggregate. diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateElementBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateElementBinder.java index 82885704202..d13359af779 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateElementBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateElementBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,6 @@ interface AggregateElementBinder { * @param source the source of the elements or {@code null} to use all sources * @return a bound object or {@code null} */ - Object bind(ConfigurationPropertyName name, Bindable target, - ConfigurationPropertySource source); + Object bind(ConfigurationPropertyName name, Bindable target, ConfigurationPropertySource source); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanBinder.java index f441ab78636..b2f27970c66 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,6 @@ interface BeanBinder { * @param the source type * @return a bound instance or {@code null} */ - T bind(ConfigurationPropertyName name, Bindable target, Context context, - BeanPropertyBinder propertyBinder); + T bind(ConfigurationPropertyName name, Bindable target, Context context, BeanPropertyBinder propertyBinder); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanPropertyName.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanPropertyName.java index 3fc27617d52..343f74a2f11 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanPropertyName.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BeanPropertyName.java @@ -47,8 +47,7 @@ abstract class BeanPropertyName { String replaced = name.replace('_', '-'); for (int i = start; i < replaced.length(); i++) { char ch = replaced.charAt(i); - if (Character.isUpperCase(ch) && result.length() > 0 - && result.charAt(result.length() - 1) != '-') { + if (Character.isUpperCase(ch) && result.length() > 0 && result.charAt(result.length() - 1) != '-') { result.append('-'); } result.append(Character.toLowerCase(ch)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindConverter.java index e3a3de385e1..3a3cc3f6dc0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,13 +63,12 @@ final class BindConverter { private BindConverter(ConversionService conversionService, Consumer propertyEditorInitializer) { Assert.notNull(conversionService, "ConversionService must not be null"); - List conversionServices = getConversionServices( - conversionService, propertyEditorInitializer); + List conversionServices = getConversionServices(conversionService, + propertyEditorInitializer); this.conversionService = new CompositeConversionService(conversionServices); } - private List getConversionServices( - ConversionService conversionService, + private List getConversionServices(ConversionService conversionService, Consumer propertyEditorInitializer) { List services = new ArrayList<>(); services.add(new TypeConverterConversionService(propertyEditorInitializer)); @@ -80,8 +79,7 @@ final class BindConverter { return services; } - public boolean canConvert(Object value, ResolvableType type, - Annotation... annotations) { + public boolean canConvert(Object value, ResolvableType type, Annotation... annotations) { return this.conversionService.canConvert(TypeDescriptor.forObject(value), new ResolvableTypeDescriptor(type, annotations)); } @@ -104,8 +102,7 @@ final class BindConverter { if (conversionService == ApplicationConversionService.getSharedInstance() && propertyEditorInitializer == null) { if (sharedInstance == null) { - sharedInstance = new BindConverter(conversionService, - propertyEditorInitializer); + sharedInstance = new BindConverter(conversionService, propertyEditorInitializer); } return sharedInstance; } @@ -117,8 +114,7 @@ final class BindConverter { */ private static class ResolvableTypeDescriptor extends TypeDescriptor { - ResolvableTypeDescriptor(ResolvableType resolvableType, - Annotation[] annotations) { + ResolvableTypeDescriptor(ResolvableType resolvableType, Annotation[] annotations) { super(resolvableType, null, annotations); } @@ -138,8 +134,7 @@ final class BindConverter { @Override public boolean canConvert(Class sourceType, Class targetType) { Assert.notNull(targetType, "Target type to convert to cannot be null"); - return canConvert( - (sourceType != null) ? TypeDescriptor.valueOf(sourceType) : null, + return canConvert((sourceType != null) ? TypeDescriptor.valueOf(sourceType) : null, TypeDescriptor.valueOf(targetType)); } @@ -157,13 +152,11 @@ final class BindConverter { @SuppressWarnings("unchecked") public T convert(Object source, Class targetType) { Assert.notNull(targetType, "Target type to convert to cannot be null"); - return (T) convert(source, TypeDescriptor.forObject(source), - TypeDescriptor.valueOf(targetType)); + return (T) convert(source, TypeDescriptor.forObject(source), TypeDescriptor.valueOf(targetType)); } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { for (int i = 0; i < this.delegates.size() - 1; i++) { try { ConversionService delegate = this.delegates.get(i); @@ -174,8 +167,7 @@ final class BindConverter { catch (ConversionException ex) { } } - return this.delegates.get(this.delegates.size() - 1).convert(source, - sourceType, targetType); + return this.delegates.get(this.delegates.size() - 1).convert(source, sourceType, targetType); } } @@ -192,8 +184,7 @@ final class BindConverter { ApplicationConversionService.addDelimitedStringConverters(this); } - private SimpleTypeConverter createTypeConverter( - Consumer initializer) { + private SimpleTypeConverter createTypeConverter(Consumer initializer) { SimpleTypeConverter typeConverter = new SimpleTypeConverter(); if (initializer != null) { initializer.accept(typeConverter); @@ -204,8 +195,7 @@ final class BindConverter { @Override public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) { // Prefer conversion service to handle things like String to char[]. - if (targetType.isArray() - && targetType.getElementTypeDescriptor().isPrimitive()) { + if (targetType.isArray() && targetType.getElementTypeDescriptor().isPrimitive()) { return false; } return super.canConvert(sourceType, targetType); @@ -235,15 +225,13 @@ final class BindConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { SimpleTypeConverter typeConverter = this.typeConverter; return typeConverter.convertIfNecessary(source, targetType.getType()); } private PropertyEditor getPropertyEditor(Class type) { - if (type == null || type == Object.class - || Collection.class.isAssignableFrom(type) + if (type == null || type == Object.class || Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindException.java index f9039f5a8ca..b11ba330b51 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class BindException extends RuntimeException implements OriginProvider { private final ConfigurationPropertyName name; - BindException(ConfigurationPropertyName name, Bindable target, - ConfigurationProperty property, Throwable cause) { + BindException(ConfigurationPropertyName name, Bindable target, ConfigurationProperty property, Throwable cause) { super(buildMessage(name, target), cause); this.name = name; this.target = target; @@ -73,8 +72,7 @@ public class BindException extends RuntimeException implements OriginProvider { return Origin.from(this.name); } - private static String buildMessage(ConfigurationPropertyName name, - Bindable target) { + private static String buildMessage(ConfigurationPropertyName name, Bindable target) { StringBuilder message = new StringBuilder(); message.append("Failed to bind properties"); message.append((name != null) ? " under '" + name + "'" : ""); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindHandler.java index 2a1dd69850e..1e21ca2ad60 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public interface BindHandler { * @param context the bind context * @return the actual item that should be used for binding (may be {@code null}) */ - default Bindable onStart(ConfigurationPropertyName name, Bindable target, - BindContext context) { + default Bindable onStart(ConfigurationPropertyName name, Bindable target, BindContext context) { return target; } @@ -57,8 +56,7 @@ public interface BindHandler { * @param result the bound result (never {@code null}) * @return the actual result that should be used (may be {@code null}) */ - default Object onSuccess(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) { + default Object onSuccess(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) { return result; } @@ -73,8 +71,8 @@ public interface BindHandler { * @return the actual result that should be used (may be {@code null}). * @throws Exception if the binding isn't valid */ - default Object onFailure(ConfigurationPropertyName name, Bindable target, - BindContext context, Exception error) throws Exception { + default Object onFailure(ConfigurationPropertyName name, Bindable target, BindContext context, Exception error) + throws Exception { throw error; } @@ -86,8 +84,8 @@ public interface BindHandler { * @param result the bound result (may be {@code null}) * @throws Exception if the binding isn't valid */ - default void onFinish(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) throws Exception { + default void onFinish(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) + throws Exception { } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindResult.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindResult.java index 87d294211ea..e7446915d0d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindResult.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,8 +132,7 @@ public final class BindResult { * @return the present value * @throws X if there is no value present */ - public T orElseThrow(Supplier exceptionSupplier) - throws X { + public T orElseThrow(Supplier exceptionSupplier) throws X { if (this.value == null) { throw exceptionSupplier.get(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Bindable.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Bindable.java index ab0d41aa73f..4f8f4069b84 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Bindable.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Bindable.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public final class Bindable { private final Annotation[] annotations; - private Bindable(ResolvableType type, ResolvableType boxedType, Supplier value, - Annotation[] annotations) { + private Bindable(ResolvableType type, ResolvableType boxedType, Supplier value, Annotation[] annotations) { this.type = type; this.boxedType = boxedType; this.value = value; @@ -160,8 +159,7 @@ public final class Bindable { */ public Bindable withExistingValue(T existingValue) { Assert.isTrue( - existingValue == null || this.type.isArray() - || this.boxedType.resolve().isInstance(existingValue), + existingValue == null || this.type.isArray() || this.boxedType.resolve().isInstance(existingValue), () -> "ExistingValue must be an instance of " + this.type); Supplier value = (existingValue != null) ? () -> existingValue : null; return new Bindable<>(this.type, this.boxedType, value, NO_ANNOTATIONS); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java index 10b0804fe9d..142b5e106a9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java @@ -98,8 +98,7 @@ public class Binder { * @param sources the sources used for binding * @param placeholdersResolver strategy to resolve any property placeholders */ - public Binder(Iterable sources, - PlaceholdersResolver placeholdersResolver) { + public Binder(Iterable sources, PlaceholdersResolver placeholdersResolver) { this(sources, placeholdersResolver, null, null); } @@ -110,8 +109,7 @@ public class Binder { * @param conversionService the conversion service to convert values (or {@code null} * to use {@link ApplicationConversionService}) */ - public Binder(Iterable sources, - PlaceholdersResolver placeholdersResolver, + public Binder(Iterable sources, PlaceholdersResolver placeholdersResolver, ConversionService conversionService) { this(sources, placeholdersResolver, conversionService, null); } @@ -126,14 +124,11 @@ public class Binder { * that can convert values (or {@code null} if no initialization is required). Often * used to call {@link ConfigurableListableBeanFactory#copyRegisteredEditorsTo}. */ - public Binder(Iterable sources, - PlaceholdersResolver placeholdersResolver, - ConversionService conversionService, - Consumer propertyEditorInitializer) { + public Binder(Iterable sources, PlaceholdersResolver placeholdersResolver, + ConversionService conversionService, Consumer propertyEditorInitializer) { Assert.notNull(sources, "Sources must not be null"); this.sources = sources; - this.placeholdersResolver = (placeholdersResolver != null) ? placeholdersResolver - : PlaceholdersResolver.NONE; + this.placeholdersResolver = (placeholdersResolver != null) ? placeholdersResolver : PlaceholdersResolver.NONE; this.conversionService = (conversionService != null) ? conversionService : ApplicationConversionService.getSharedInstance(); this.propertyEditorInitializer = propertyEditorInitializer; @@ -200,8 +195,7 @@ public class Binder { * @param the bound type * @return the binding result (never {@code null}) */ - public BindResult bind(ConfigurationPropertyName name, Bindable target, - BindHandler handler) { + public BindResult bind(ConfigurationPropertyName name, Bindable target, BindHandler handler) { Assert.notNull(name, "Name must not be null"); Assert.notNull(target, "Target must not be null"); handler = (handler != null) ? handler : BindHandler.DEFAULT; @@ -210,16 +204,15 @@ public class Binder { return BindResult.of(bound); } - protected final T bind(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, boolean allowRecursiveBinding) { + protected final T bind(ConfigurationPropertyName name, Bindable target, BindHandler handler, Context context, + boolean allowRecursiveBinding) { context.clearConfigurationProperty(); try { target = handler.onStart(name, target, context); if (target == null) { return null; } - Object bound = bindObject(name, target, handler, context, - allowRecursiveBinding); + Object bound = bindObject(name, target, handler, context, allowRecursiveBinding); return handleBindResult(name, target, handler, context, bound); } catch (Exception ex) { @@ -227,8 +220,8 @@ public class Binder { } } - private T handleBindResult(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, Object result) throws Exception { + private T handleBindResult(ConfigurationPropertyName name, Bindable target, BindHandler handler, + Context context, Object result) throws Exception { if (result != null) { result = handler.onSuccess(name, target, context, result); result = context.getConverter().convert(result, target); @@ -237,8 +230,8 @@ public class Binder { return context.getConverter().convert(result, target); } - private T handleBindError(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, Exception error) { + private T handleBindError(ConfigurationPropertyName name, Bindable target, BindHandler handler, + Context context, Exception error) { try { Object result = handler.onFailure(name, target, context, error); return context.getConverter().convert(result, target); @@ -251,11 +244,10 @@ public class Binder { } } - private Object bindObject(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, boolean allowRecursiveBinding) { + private Object bindObject(ConfigurationPropertyName name, Bindable target, BindHandler handler, + Context context, boolean allowRecursiveBinding) { ConfigurationProperty property = findProperty(name, context); - if (property == null && containsNoDescendantOf(context.getSources(), name) - && context.depth != 0) { + if (property == null && containsNoDescendantOf(context.getSources(), name) && context.depth != 0) { return null; } AggregateBinder aggregateBinder = getAggregateBinder(target, context); @@ -268,8 +260,7 @@ public class Binder { } catch (ConverterNotFoundException ex) { // We might still be able to bind it as a bean - Object bean = bindBean(name, target, handler, context, - allowRecursiveBinding); + Object bean = bindBean(name, target, handler, context, allowRecursiveBinding); if (bean != null) { return bean; } @@ -293,21 +284,17 @@ public class Binder { return null; } - private Object bindAggregate(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, AggregateBinder aggregateBinder) { + private Object bindAggregate(ConfigurationPropertyName name, Bindable target, BindHandler handler, + Context context, AggregateBinder aggregateBinder) { AggregateElementBinder elementBinder = (itemName, itemTarget, source) -> { - boolean allowRecursiveBinding = aggregateBinder - .isAllowRecursiveBinding(source); - Supplier supplier = () -> bind(itemName, itemTarget, handler, context, - allowRecursiveBinding); + boolean allowRecursiveBinding = aggregateBinder.isAllowRecursiveBinding(source); + Supplier supplier = () -> bind(itemName, itemTarget, handler, context, allowRecursiveBinding); return context.withSource(source, supplier); }; - return context.withIncreasedDepth( - () -> aggregateBinder.bind(name, target, elementBinder)); + return context.withIncreasedDepth(() -> aggregateBinder.bind(name, target, elementBinder)); } - private ConfigurationProperty findProperty(ConfigurationPropertyName name, - Context context) { + private ConfigurationProperty findProperty(ConfigurationPropertyName name, Context context) { if (name.isEmpty()) { return null; } @@ -320,8 +307,7 @@ public class Binder { return null; } - private Object bindProperty(Bindable target, Context context, - ConfigurationProperty property) { + private Object bindProperty(Bindable target, Context context, ConfigurationProperty property) { context.setConfigurationProperty(property); Object result = property.getValue(); result = this.placeholdersResolver.resolvePlaceholders(result); @@ -329,8 +315,8 @@ public class Binder { return result; } - private Object bindBean(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, boolean allowRecursiveBinding) { + private Object bindBean(ConfigurationPropertyName name, Bindable target, BindHandler handler, Context context, + boolean allowRecursiveBinding) { if (isUnbindableBean(name, target, context)) { return null; } @@ -338,17 +324,15 @@ public class Binder { if (!allowRecursiveBinding && context.hasBoundBean(type)) { return null; } - BeanPropertyBinder propertyBinder = (propertyName, propertyTarget) -> bind( - name.append(propertyName), propertyTarget, handler, context, false); + BeanPropertyBinder propertyBinder = (propertyName, propertyTarget) -> bind(name.append(propertyName), + propertyTarget, handler, context, false); return context.withBean(type, () -> { - Stream boundBeans = BEAN_BINDERS.stream() - .map((b) -> b.bind(name, target, context, propertyBinder)); + Stream boundBeans = BEAN_BINDERS.stream().map((b) -> b.bind(name, target, context, propertyBinder)); return boundBeans.filter(Objects::nonNull).findFirst().orElse(null); }); } - private boolean isUnbindableBean(ConfigurationPropertyName name, Bindable target, - Context context) { + private boolean isUnbindableBean(ConfigurationPropertyName name, Bindable target, Context context) { for (ConfigurationPropertySource source : context.getSources()) { if (source.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT) { // We know there are properties to bind so we can't bypass anything @@ -392,8 +376,7 @@ public class Binder { private int depth; - private final List source = Arrays - .asList((ConfigurationPropertySource) null); + private final List source = Arrays.asList((ConfigurationPropertySource) null); private int sourcePushCount; @@ -402,8 +385,7 @@ public class Binder { private ConfigurationProperty configurationProperty; Context() { - this.converter = BindConverter.get(Binder.this.conversionService, - Binder.this.propertyEditorInitializer); + this.converter = BindConverter.get(Binder.this.conversionService, Binder.this.propertyEditorInitializer); } private void increaseDepth() { @@ -414,8 +396,7 @@ public class Binder { this.depth--; } - private T withSource(ConfigurationPropertySource source, - Supplier supplier) { + private T withSource(ConfigurationPropertySource source, Supplier supplier) { if (source == null) { return supplier.get(); } @@ -453,8 +434,7 @@ public class Binder { } } - private void setConfigurationProperty( - ConfigurationProperty configurationProperty) { + private void setConfigurationProperty(ConfigurationProperty configurationProperty) { this.configurationProperty = configurationProperty; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/CollectionBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/CollectionBinder.java index 8820e330bfb..7ddee6aaa26 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/CollectionBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/CollectionBinder.java @@ -40,14 +40,12 @@ class CollectionBinder extends IndexedElementsBinder> { @Override protected Object bindAggregate(ConfigurationPropertyName name, Bindable target, AggregateElementBinder elementBinder) { - Class collectionType = (target.getValue() != null) ? List.class - : target.getType().resolve(Object.class); + Class collectionType = (target.getValue() != null) ? List.class : target.getType().resolve(Object.class); ResolvableType aggregateType = ResolvableType.forClassWithGenerics(List.class, target.getType().asCollection().getGenerics()); ResolvableType elementType = target.getType().asCollection().getGeneric(); IndexedCollectionSupplier result = new IndexedCollectionSupplier( - () -> CollectionFactory.createCollection(collectionType, - elementType.resolve(), 0)); + () -> CollectionFactory.createCollection(collectionType, elementType.resolve(), 0)); bindIndexed(name, target, elementBinder, aggregateType, elementType, result); if (result.wasSupplied()) { return result.get(); @@ -56,8 +54,7 @@ class CollectionBinder extends IndexedElementsBinder> { } @Override - protected Collection merge(Supplier> existing, - Collection additional) { + protected Collection merge(Supplier> existing, Collection additional) { Collection existingCollection = getExistingIfPossible(existing); if (existingCollection == null) { return additional; @@ -72,8 +69,7 @@ class CollectionBinder extends IndexedElementsBinder> { } } - private Collection getExistingIfPossible( - Supplier> existing) { + private Collection getExistingIfPossible(Supplier> existing) { try { return existing.get(); } @@ -92,8 +88,7 @@ class CollectionBinder extends IndexedElementsBinder> { } private Collection createNewCollection(Collection collection) { - Collection result = CollectionFactory - .createCollection(collection.getClass(), collection.size()); + Collection result = CollectionFactory.createCollection(collection.getClass(), collection.size()); result.addAll(collection); return result; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinder.java index 587fc94a12f..cf0d158b235 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinder.java @@ -50,8 +50,8 @@ class ConstructorParametersBinder implements BeanBinder { @Override @SuppressWarnings("unchecked") - public T bind(ConfigurationPropertyName name, Bindable target, - Binder.Context context, BeanPropertyBinder propertyBinder) { + public T bind(ConfigurationPropertyName name, Bindable target, Binder.Context context, + BeanPropertyBinder propertyBinder) { Bean bean = Bean.get(target); if (bean == null) { return null; @@ -60,8 +60,7 @@ class ConstructorParametersBinder implements BeanBinder { return (T) BeanUtils.instantiateClass(bean.getConstructor(), bound.toArray()); } - private List bind(BeanPropertyBinder propertyBinder, Bean bean, - BindConverter converter) { + private List bind(BeanPropertyBinder propertyBinder, Bean bean, BindConverter converter) { Collection parameters = bean.getParameters().values(); List boundParameters = new ArrayList<>(parameters.size()); for (ConstructorParameter parameter : parameters) { @@ -74,17 +73,14 @@ class ConstructorParametersBinder implements BeanBinder { return boundParameters; } - private Object getDefaultValue(ConstructorParameter parameter, - BindConverter converter) { + private Object getDefaultValue(ConstructorParameter parameter, BindConverter converter) { if (parameter.getDefaultValue() == null) { return null; } - return converter.convert(parameter.getDefaultValue(), parameter.getType(), - parameter.getAnnotations()); + return converter.convert(parameter.getDefaultValue(), parameter.getType(), parameter.getAnnotations()); } - private Object bind(ConstructorParameter parameter, - BeanPropertyBinder propertyBinder) { + private Object bind(ConstructorParameter parameter, BeanPropertyBinder propertyBinder) { String propertyName = parameter.getName(); ResolvableType type = parameter.getType(); return propertyBinder.bindProperty(propertyName, Bindable.of(type)); @@ -96,8 +92,7 @@ class ConstructorParametersBinder implements BeanBinder { private final Map parameters; - private Bean(Constructor constructor, - Map parameters) { + private Bean(Constructor constructor, Map parameters) { this.constructor = constructor; this.parameters = parameters; } @@ -134,32 +129,28 @@ class ConstructorParametersBinder implements BeanBinder { public static Bean get(Class type) { Constructor primaryConstructor = BeanUtils.findPrimaryConstructor(type); - if (primaryConstructor != null - && primaryConstructor.getParameterCount() > 0) { + if (primaryConstructor != null && primaryConstructor.getParameterCount() > 0) { return get(primaryConstructor); } return null; } private static Bean get(Constructor constructor) { - KFunction kotlinConstructor = ReflectJvmMapping - .getKotlinFunction(constructor); + KFunction kotlinConstructor = ReflectJvmMapping.getKotlinFunction(constructor); if (kotlinConstructor != null) { return new Bean(constructor, parseParameters(kotlinConstructor)); } return SimpleBeanProvider.get(constructor); } - private static Map parseParameters( - KFunction constructor) { + private static Map parseParameters(KFunction constructor) { Map parameters = new LinkedHashMap<>(); for (KParameter parameter : constructor.getParameters()) { String name = parameter.getName(); Type type = ReflectJvmMapping.getJavaType(parameter.getType()); - Annotation[] annotations = parameter.getAnnotations() - .toArray(new Annotation[0]); - parameters.computeIfAbsent(name, (s) -> new ConstructorParameter(name, - ResolvableType.forType(type), annotations, null)); + Annotation[] annotations = parameter.getAnnotations().toArray(new Annotation[0]); + parameters.computeIfAbsent(name, + (s) -> new ConstructorParameter(name, ResolvableType.forType(type), annotations, null)); } return parameters; } @@ -186,24 +177,18 @@ class ConstructorParametersBinder implements BeanBinder { return new Bean(constructor, parseParameters(constructor)); } - private static Map parseParameters( - Constructor constructor) { - String[] parameterNames = PARAMETER_NAME_DISCOVERER - .getParameterNames(constructor); - Assert.state(parameterNames != null, - () -> "Failed to extract parameter names for " + constructor); + private static Map parseParameters(Constructor constructor) { + String[] parameterNames = PARAMETER_NAME_DISCOVERER.getParameterNames(constructor); + Assert.state(parameterNames != null, () -> "Failed to extract parameter names for " + constructor); Map parametersByName = new LinkedHashMap<>(); Parameter[] parameters = constructor.getParameters(); for (int i = 0; i < parameterNames.length; i++) { String name = parameterNames[i]; Parameter parameter = parameters[i]; - DefaultValue[] annotationsByType = parameter - .getAnnotationsByType(DefaultValue.class); - String[] defaultValue = (annotationsByType.length > 0) - ? annotationsByType[0].value() : null; + DefaultValue[] annotationsByType = parameter.getAnnotationsByType(DefaultValue.class); + String[] defaultValue = (annotationsByType.length > 0) ? annotationsByType[0].value() : null; parametersByName.computeIfAbsent(name, - (key) -> new ConstructorParameter(name, - ResolvableType.forClass(parameter.getType()), + (key) -> new ConstructorParameter(name, ResolvableType.forClass(parameter.getType()), parameter.getDeclaredAnnotations(), defaultValue)); } return parametersByName; @@ -224,8 +209,7 @@ class ConstructorParametersBinder implements BeanBinder { private final String[] defaultValue; - ConstructorParameter(String name, ResolvableType type, Annotation[] annotations, - String[] defaultValue) { + ConstructorParameter(String name, ResolvableType type, Annotation[] annotations, String[] defaultValue) { this.name = BeanPropertyName.toDashedForm(name); this.type = type; this.annotations = annotations; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java index 152a64a614c..7ceed825d8f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,51 +65,44 @@ abstract class IndexedElementsBinder extends AggregateBinder { * @param result the destination for results */ protected final void bindIndexed(ConfigurationPropertyName name, Bindable target, - AggregateElementBinder elementBinder, ResolvableType aggregateType, - ResolvableType elementType, IndexedCollectionSupplier result) { + AggregateElementBinder elementBinder, ResolvableType aggregateType, ResolvableType elementType, + IndexedCollectionSupplier result) { for (ConfigurationPropertySource source : getContext().getSources()) { - bindIndexed(source, name, target, elementBinder, result, aggregateType, - elementType); + bindIndexed(source, name, target, elementBinder, result, aggregateType, elementType); if (result.wasSupplied() && result.get() != null) { return; } } } - private void bindIndexed(ConfigurationPropertySource source, - ConfigurationPropertyName root, Bindable target, - AggregateElementBinder elementBinder, IndexedCollectionSupplier collection, - ResolvableType aggregateType, ResolvableType elementType) { + private void bindIndexed(ConfigurationPropertySource source, ConfigurationPropertyName root, Bindable target, + AggregateElementBinder elementBinder, IndexedCollectionSupplier collection, ResolvableType aggregateType, + ResolvableType elementType) { ConfigurationProperty property = source.getConfigurationProperty(root); if (property != null) { - bindValue(target, collection.get(), aggregateType, elementType, - property.getValue()); + bindValue(target, collection.get(), aggregateType, elementType, property.getValue()); } else { bindIndexed(source, root, elementBinder, collection, elementType); } } - private void bindValue(Bindable target, Collection collection, - ResolvableType aggregateType, ResolvableType elementType, Object value) { + private void bindValue(Bindable target, Collection collection, ResolvableType aggregateType, + ResolvableType elementType, Object value) { if (value instanceof String && !StringUtils.hasText((String) value)) { return; } Object aggregate = convert(value, aggregateType, target.getAnnotations()); - ResolvableType collectionType = ResolvableType - .forClassWithGenerics(collection.getClass(), elementType); + ResolvableType collectionType = ResolvableType.forClassWithGenerics(collection.getClass(), elementType); Collection elements = convert(aggregate, collectionType); collection.addAll(elements); } - private void bindIndexed(ConfigurationPropertySource source, - ConfigurationPropertyName root, AggregateElementBinder elementBinder, - IndexedCollectionSupplier collection, ResolvableType elementType) { - MultiValueMap knownIndexedChildren = getKnownIndexedChildren( - source, root); + private void bindIndexed(ConfigurationPropertySource source, ConfigurationPropertyName root, + AggregateElementBinder elementBinder, IndexedCollectionSupplier collection, ResolvableType elementType) { + MultiValueMap knownIndexedChildren = getKnownIndexedChildren(source, root); for (int i = 0; i < Integer.MAX_VALUE; i++) { - ConfigurationPropertyName name = root - .append((i != 0) ? "[" + i + "]" : INDEX_ZERO); + ConfigurationPropertyName name = root.append((i != 0) ? "[" + i + "]" : INDEX_ZERO); Object value = elementBinder.bind(name, Bindable.of(elementType), source); if (value == null) { break; @@ -120,16 +113,14 @@ abstract class IndexedElementsBinder extends AggregateBinder { assertNoUnboundChildren(knownIndexedChildren); } - private MultiValueMap getKnownIndexedChildren( - ConfigurationPropertySource source, ConfigurationPropertyName root) { + private MultiValueMap getKnownIndexedChildren(ConfigurationPropertySource source, + ConfigurationPropertyName root) { MultiValueMap children = new LinkedMultiValueMap<>(); if (!(source instanceof IterableConfigurationPropertySource)) { return children; } - for (ConfigurationPropertyName name : (IterableConfigurationPropertySource) source - .filter(root::isAncestorOf)) { - ConfigurationPropertyName choppedName = name - .chop(root.getNumberOfElements() + 1); + for (ConfigurationPropertyName name : (IterableConfigurationPropertySource) source.filter(root::isAncestorOf)) { + ConfigurationPropertyName choppedName = name.chop(root.getNumberOfElements() + 1); if (choppedName.isLastElementIndexed()) { String key = choppedName.getLastElement(Form.UNIFORM); ConfigurationProperty value = source.getConfigurationProperty(name); @@ -139,12 +130,10 @@ abstract class IndexedElementsBinder extends AggregateBinder { return children; } - private void assertNoUnboundChildren( - MultiValueMap children) { + private void assertNoUnboundChildren(MultiValueMap children) { if (!children.isEmpty()) { throw new UnboundConfigurationPropertiesException( - children.values().stream().flatMap(List::stream) - .collect(Collectors.toCollection(TreeSet::new))); + children.values().stream().flatMap(List::stream).collect(Collectors.toCollection(TreeSet::new))); } } @@ -157,8 +146,7 @@ abstract class IndexedElementsBinder extends AggregateBinder { * {@link AggregateBinder.AggregateSupplier AggregateSupplier} for an indexed * collection. */ - protected static class IndexedCollectionSupplier - extends AggregateSupplier> { + protected static class IndexedCollectionSupplier extends AggregateSupplier> { public IndexedCollectionSupplier(Supplier> supplier) { super(supplier); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/JavaBeanBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/JavaBeanBinder.java index 3d808d2f043..d700a349e4d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/JavaBeanBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/JavaBeanBinder.java @@ -55,8 +55,7 @@ class JavaBeanBinder implements BeanBinder { return (bound ? beanSupplier.get() : null); } - private boolean hasKnownBindableProperties(ConfigurationPropertyName name, - Context context) { + private boolean hasKnownBindableProperties(ConfigurationPropertyName name, Context context) { for (ConfigurationPropertySource source : context.getSources()) { if (source.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT) { return true; @@ -65,8 +64,7 @@ class JavaBeanBinder implements BeanBinder { return false; } - private boolean bind(BeanPropertyBinder propertyBinder, Bean bean, - BeanSupplier beanSupplier) { + private boolean bind(BeanPropertyBinder propertyBinder, Bean bean, BeanSupplier beanSupplier) { boolean bound = false; for (BeanProperty beanProperty : bean.getProperties().values()) { bound |= bind(beanSupplier, propertyBinder, beanProperty); @@ -74,8 +72,7 @@ class JavaBeanBinder implements BeanBinder { return bound; } - private boolean bind(BeanSupplier beanSupplier, - BeanPropertyBinder propertyBinder, BeanProperty property) { + private boolean bind(BeanSupplier beanSupplier, BeanPropertyBinder propertyBinder, BeanProperty property) { String propertyName = property.getName(); ResolvableType type = property.getType(); Supplier value = property.getValue(beanSupplier); @@ -89,8 +86,7 @@ class JavaBeanBinder implements BeanBinder { property.setValue(beanSupplier, bound); } else if (value == null || !bound.equals(value.get())) { - throw new IllegalStateException( - "No setter found for property: " + property.getName()); + throw new IllegalStateException("No setter found for property: " + property.getName()); } return true; } @@ -145,21 +141,17 @@ class JavaBeanBinder implements BeanBinder { private boolean isCandidate(Method method) { int modifiers = method.getModifiers(); - return Modifier.isPublic(modifiers) && !Modifier.isAbstract(modifiers) - && !Modifier.isStatic(modifiers) + return Modifier.isPublic(modifiers) && !Modifier.isAbstract(modifiers) && !Modifier.isStatic(modifiers) && !Object.class.equals(method.getDeclaringClass()) && !Class.class.equals(method.getDeclaringClass()); } private void addMethodIfPossible(Method method, String prefix, int parameterCount, BiConsumer consumer) { - if (method != null && method.getParameterCount() == parameterCount - && method.getName().startsWith(prefix) + if (method != null && method.getParameterCount() == parameterCount && method.getName().startsWith(prefix) && method.getName().length() > prefix.length()) { - String propertyName = Introspector - .decapitalize(method.getName().substring(prefix.length())); - consumer.accept(this.properties.computeIfAbsent(propertyName, - this::getBeanProperty), method); + String propertyName = Introspector.decapitalize(method.getName().substring(prefix.length())); + consumer.accept(this.properties.computeIfAbsent(propertyName, this::getBeanProperty), method); } } @@ -288,8 +280,7 @@ class JavaBeanBinder implements BeanBinder { } private boolean isBetterSetter(Method setter) { - return this.getter != null - && this.getter.getReturnType().equals(setter.getParameterTypes()[0]); + return this.getter != null && this.getter.getReturnType().equals(setter.getParameterTypes()[0]); } public void addField(Field field) { @@ -305,12 +296,10 @@ class JavaBeanBinder implements BeanBinder { public ResolvableType getType() { if (this.setter != null) { MethodParameter methodParameter = new MethodParameter(this.setter, 0); - return ResolvableType.forMethodParameter(methodParameter, - this.declaringClassType); + return ResolvableType.forMethodParameter(methodParameter, this.declaringClassType); } MethodParameter methodParameter = new MethodParameter(this.getter, -1); - return ResolvableType.forMethodParameter(methodParameter, - this.declaringClassType); + return ResolvableType.forMethodParameter(methodParameter, this.declaringClassType); } public Annotation[] getAnnotations() { @@ -332,8 +321,7 @@ class JavaBeanBinder implements BeanBinder { return this.getter.invoke(instance.get()); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to get value for property " + this.name, ex); + throw new IllegalStateException("Unable to get value for property " + this.name, ex); } }; } @@ -348,8 +336,7 @@ class JavaBeanBinder implements BeanBinder { this.setter.invoke(instance.get(), value); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to set value for property " + this.name, ex); + throw new IllegalStateException("Unable to set value for property " + this.name, ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java index b2b77c2b492..af886c54520 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.core.ResolvableType; */ class MapBinder extends AggregateBinder> { - private static final Bindable> STRING_STRING_MAP = Bindable - .mapOf(String.class, String.class); + private static final Bindable> STRING_STRING_MAP = Bindable.mapOf(String.class, String.class); MapBinder(Context context) { super(context); @@ -54,16 +53,15 @@ class MapBinder extends AggregateBinder> { @Override protected Object bindAggregate(ConfigurationPropertyName name, Bindable target, AggregateElementBinder elementBinder) { - Map map = CollectionFactory.createMap((target.getValue() != null) - ? Map.class : target.getType().resolve(Object.class), 0); + Map map = CollectionFactory + .createMap((target.getValue() != null) ? Map.class : target.getType().resolve(Object.class), 0); Bindable resolvedTarget = resolveTarget(target); boolean hasDescendants = hasDescendants(name); for (ConfigurationPropertySource source : getContext().getSources()) { if (!ConfigurationPropertyName.EMPTY.equals(name)) { ConfigurationProperty property = source.getConfigurationProperty(name); if (property != null && !hasDescendants) { - return getContext().getConverter().convert(property.getValue(), - target); + return getContext().getConverter().convert(property.getValue(), target); } source = source.filter(name::isAncestorOf); } @@ -90,8 +88,7 @@ class MapBinder extends AggregateBinder> { } @Override - protected Map merge(Supplier> existing, - Map additional) { + protected Map merge(Supplier> existing, Map additional) { Map existingMap = getExistingIfPossible(existing); if (existingMap == null) { return additional; @@ -107,8 +104,7 @@ class MapBinder extends AggregateBinder> { } } - private Map getExistingIfPossible( - Supplier> existing) { + private Map getExistingIfPossible(Supplier> existing) { try { return existing.get(); } @@ -144,8 +140,7 @@ class MapBinder extends AggregateBinder> { private final ResolvableType valueType; - EntryBinder(ConfigurationPropertyName root, Bindable target, - AggregateElementBinder elementBinder) { + EntryBinder(ConfigurationPropertyName root, Bindable target, AggregateElementBinder elementBinder) { this.root = root; this.elementBinder = elementBinder; this.mapType = target.getType().asMap(); @@ -153,16 +148,13 @@ class MapBinder extends AggregateBinder> { this.valueType = this.mapType.getGeneric(1); } - public void bindEntries(ConfigurationPropertySource source, - Map map) { + public void bindEntries(ConfigurationPropertySource source, Map map) { if (source instanceof IterableConfigurationPropertySource) { for (ConfigurationPropertyName name : (IterableConfigurationPropertySource) source) { Bindable valueBindable = getValueBindable(name); ConfigurationPropertyName entryName = getEntryName(source, name); - Object key = getContext().getConverter() - .convert(getKeyName(entryName), this.keyType); - map.computeIfAbsent(key, - (k) -> this.elementBinder.bind(entryName, valueBindable)); + Object key = getContext().getConverter().convert(getKeyName(entryName), this.keyType); + map.computeIfAbsent(key, (k) -> this.elementBinder.bind(entryName, valueBindable)); } } } @@ -180,15 +172,13 @@ class MapBinder extends AggregateBinder> { if (Collection.class.isAssignableFrom(resolved) || this.valueType.isArray()) { return chopNameAtNumericIndex(name); } - if (!this.root.isParentOf(name) - && (isValueTreatedAsNestedMap() || !isScalarValue(source, name))) { + if (!this.root.isParentOf(name) && (isValueTreatedAsNestedMap() || !isScalarValue(source, name))) { return name.chop(this.root.getNumberOfElements() + 1); } return name; } - private ConfigurationPropertyName chopNameAtNumericIndex( - ConfigurationPropertyName name) { + private ConfigurationPropertyName chopNameAtNumericIndex(ConfigurationPropertyName name) { int start = this.root.getNumberOfElements() + 1; int size = name.getNumberOfElements(); for (int i = start; i < size; i++) { @@ -203,8 +193,7 @@ class MapBinder extends AggregateBinder> { return Object.class.equals(this.valueType.resolve(Object.class)); } - private boolean isScalarValue(ConfigurationPropertySource source, - ConfigurationPropertyName name) { + private boolean isScalarValue(ConfigurationPropertySource source, ConfigurationPropertyName name) { Class resolved = this.valueType.resolve(Object.class); if (!resolved.getName().startsWith("java.lang") && !resolved.isEnum()) { return false; @@ -220,8 +209,7 @@ class MapBinder extends AggregateBinder> { private String getKeyName(ConfigurationPropertyName name) { StringBuilder result = new StringBuilder(); - for (int i = this.root.getNumberOfElements(); i < name - .getNumberOfElements(); i++) { + for (int i = this.root.getNumberOfElements(); i < name.getNumberOfElements(); i++) { if (result.length() != 0) { result.append('.'); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java index f54b5b294aa..705ad3f88b5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,20 +45,16 @@ public class PropertySourcesPlaceholdersResolver implements PlaceholdersResolver this(sources, null); } - public PropertySourcesPlaceholdersResolver(Iterable> sources, - PropertyPlaceholderHelper helper) { + public PropertySourcesPlaceholdersResolver(Iterable> sources, PropertyPlaceholderHelper helper) { this.sources = sources; - this.helper = (helper != null) ? helper - : new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX, - SystemPropertyUtils.PLACEHOLDER_SUFFIX, - SystemPropertyUtils.VALUE_SEPARATOR, true); + this.helper = (helper != null) ? helper : new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX, + SystemPropertyUtils.PLACEHOLDER_SUFFIX, SystemPropertyUtils.VALUE_SEPARATOR, true); } @Override public Object resolvePlaceholders(Object value) { if (value != null && value instanceof String) { - return this.helper.replacePlaceholders((String) value, - this::resolvePlaceholder); + return this.helper.replacePlaceholders((String) value, this::resolvePlaceholder); } return value; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/UnboundConfigurationPropertiesException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/UnboundConfigurationPropertiesException.java index 1715b0e55cb..3ae316b66a5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/UnboundConfigurationPropertiesException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/UnboundConfigurationPropertiesException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class UnboundConfigurationPropertiesException extends RuntimeException { private final Set unboundProperties; - public UnboundConfigurationPropertiesException( - Set unboundProperties) { + public UnboundConfigurationPropertiesException(Set unboundProperties) { super(buildMessage(unboundProperties)); this.unboundProperties = Collections.unmodifiableSet(unboundProperties); } @@ -48,8 +47,7 @@ public class UnboundConfigurationPropertiesException extends RuntimeException { private static String buildMessage(Set unboundProperties) { StringBuilder builder = new StringBuilder(); builder.append("The elements ["); - String message = unboundProperties.stream().map((p) -> p.getName().toString()) - .collect(Collectors.joining(",")); + String message = unboundProperties.stream().map((p) -> p.getName().toString()).collect(Collectors.joining(",")); builder.append(message).append("] were left unbound."); return builder.toString(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandler.java index 03b24e39178..6c8a4e8e00f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class IgnoreErrorsBindHandler extends AbstractBindHandler { } @Override - public Object onFailure(ConfigurationPropertyName name, Bindable target, - BindContext context, Exception error) throws Exception { + public Object onFailure(ConfigurationPropertyName name, Bindable target, BindContext context, Exception error) + throws Exception { return (target.getValue() != null) ? target.getValue().get() : null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandler.java index 80e06057a2e..7d2f9eb264c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,8 @@ public class IgnoreTopLevelConverterNotFoundBindHandler extends AbstractBindHand } @Override - public Object onFailure(ConfigurationPropertyName name, Bindable target, - BindContext context, Exception error) throws Exception { + public Object onFailure(ConfigurationPropertyName name, Bindable target, BindContext context, Exception error) + throws Exception { if (context.getDepth() == 0 && error instanceof ConverterNotFoundException) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandler.java index 7fd638063bb..754fce22bfb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandler.java @@ -53,35 +53,30 @@ public class NoUnboundElementsBindHandler extends AbstractBindHandler { this(parent, (configurationPropertySource) -> true); } - public NoUnboundElementsBindHandler(BindHandler parent, - Function filter) { + public NoUnboundElementsBindHandler(BindHandler parent, Function filter) { super(parent); this.filter = filter; } @Override - public Object onSuccess(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) { + public Object onSuccess(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) { this.boundNames.add(name); return super.onSuccess(name, target, context, result); } @Override - public void onFinish(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) throws Exception { + public void onFinish(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) + throws Exception { if (context.getDepth() == 0) { checkNoUnboundElements(name, context); } } - private void checkNoUnboundElements(ConfigurationPropertyName name, - BindContext context) { + private void checkNoUnboundElements(ConfigurationPropertyName name, BindContext context) { Set unbound = new TreeSet<>(); for (ConfigurationPropertySource source : context.getSources()) { - if (source instanceof IterableConfigurationPropertySource - && this.filter.apply(source)) { - collectUnbound(name, unbound, - (IterableConfigurationPropertySource) source); + if (source instanceof IterableConfigurationPropertySource && this.filter.apply(source)) { + collectUnbound(name, unbound, (IterableConfigurationPropertySource) source); } } if (!unbound.isEmpty()) { @@ -89,26 +84,22 @@ public class NoUnboundElementsBindHandler extends AbstractBindHandler { } } - private void collectUnbound(ConfigurationPropertyName name, - Set unbound, + private void collectUnbound(ConfigurationPropertyName name, Set unbound, IterableConfigurationPropertySource source) { - IterableConfigurationPropertySource filtered = source - .filter((candidate) -> isUnbound(name, candidate)); + IterableConfigurationPropertySource filtered = source.filter((candidate) -> isUnbound(name, candidate)); for (ConfigurationPropertyName unboundName : filtered) { try { - unbound.add(source.filter((candidate) -> isUnbound(name, candidate)) - .getConfigurationProperty(unboundName)); + unbound.add( + source.filter((candidate) -> isUnbound(name, candidate)).getConfigurationProperty(unboundName)); } catch (Exception ex) { } } } - private boolean isUnbound(ConfigurationPropertyName name, - ConfigurationPropertyName candidate) { + private boolean isUnbound(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { if (name.isAncestorOf(candidate)) { - if (!this.boundNames.contains(candidate) - && !isOverriddenCollectionElement(candidate)) { + if (!this.boundNames.contains(candidate) && !isOverriddenCollectionElement(candidate)) { return true; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/BindValidationException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/BindValidationException.java index 0c99065603e..b1be6d24c85 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/BindValidationException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/BindValidationException.java @@ -49,8 +49,7 @@ public class BindValidationException extends RuntimeException { StringBuilder message = new StringBuilder("Binding validation errors"); if (errors != null) { message.append(" on ").append(errors.getName()); - errors.getAllErrors().forEach( - (error) -> message.append(String.format("%n - %s", error))); + errors.getAllErrors().forEach((error) -> message.append(String.format("%n - %s", error))); } return message.toString(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldError.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldError.java index 941e94938d6..bb78cb85d72 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldError.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldError.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,9 +31,8 @@ final class OriginTrackedFieldError extends FieldError implements OriginProvider private final Origin origin; private OriginTrackedFieldError(FieldError fieldError, Origin origin) { - super(fieldError.getObjectName(), fieldError.getField(), - fieldError.getRejectedValue(), fieldError.isBindingFailure(), - fieldError.getCodes(), fieldError.getArguments(), + super(fieldError.getObjectName(), fieldError.getField(), fieldError.getRejectedValue(), + fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), fieldError.getDefaultMessage()); this.origin = origin; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java index 0db0a2f930b..d9f93d6e823 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java @@ -58,8 +58,7 @@ public class ValidationBindHandler extends AbstractBindHandler { } @Override - public Object onSuccess(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) { + public Object onSuccess(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) { if (context.getConfigurationProperty() != null) { this.boundProperties.add(context.getConfigurationProperty()); } @@ -67,22 +66,21 @@ public class ValidationBindHandler extends AbstractBindHandler { } @Override - public void onFinish(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) throws Exception { + public void onFinish(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) + throws Exception { validate(name, target, context, result); super.onFinish(name, target, context, result); } @Override - public Object onFailure(ConfigurationPropertyName name, Bindable target, - BindContext context, Exception error) throws Exception { + public Object onFailure(ConfigurationPropertyName name, Bindable target, BindContext context, Exception error) + throws Exception { Object result = super.onFailure(name, target, context, error); validate(name, target, context, null); return result; } - private void validate(ConfigurationPropertyName name, Bindable target, - BindContext context, Object result) { + private void validate(ConfigurationPropertyName name, Bindable target, BindContext context, Object result) { Object validationTarget = getValidationTarget(target, context, result); Class validationType = target.getBoxedType().resolve(); if (validationTarget != null) { @@ -93,8 +91,7 @@ public class ValidationBindHandler extends AbstractBindHandler { } } - private Object getValidationTarget(Bindable target, BindContext context, - Object result) { + private Object getValidationTarget(Bindable target, BindContext context, Object result) { if (result != null) { return result; } @@ -104,8 +101,7 @@ public class ValidationBindHandler extends AbstractBindHandler { return null; } - private void validateAndPush(ConfigurationPropertyName name, Object target, - Class type) { + private void validateAndPush(ConfigurationPropertyName name, Object target, Class type) { BindingResult errors = new BeanPropertyBindingResult(target, name.toString()); Arrays.stream(this.validators).filter((validator) -> validator.supports(type)) .forEach((validator) -> validator.validate(target, errors)); @@ -114,13 +110,11 @@ public class ValidationBindHandler extends AbstractBindHandler { } } - private BindValidationException getBindValidationException( - ConfigurationPropertyName name, BindingResult errors) { + private BindValidationException getBindValidationException(ConfigurationPropertyName name, BindingResult errors) { Set boundProperties = this.boundProperties.stream() .filter((property) -> name.isAncestorOf(property.getName())) .collect(Collectors.toCollection(LinkedHashSet::new)); - ValidationErrors validationErrors = new ValidationErrors(name, boundProperties, - errors.getAllErrors()); + ValidationErrors validationErrors = new ValidationErrors(name, boundProperties, errors.getAllErrors()); return new BindValidationException(validationErrors); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java index 63eecc28568..36a101e38f9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,8 @@ public class ValidationErrors implements Iterable { private final List errors; - ValidationErrors(ConfigurationPropertyName name, - Set boundProperties, List errors) { + ValidationErrors(ConfigurationPropertyName name, Set boundProperties, + List errors) { Assert.notNull(name, "Name must not be null"); Assert.notNull(boundProperties, "BoundProperties must not be null"); Assert.notNull(errors, "Errors must not be null"); @@ -57,8 +57,8 @@ public class ValidationErrors implements Iterable { this.errors = convertErrors(name, boundProperties, errors); } - private List convertErrors(ConfigurationPropertyName name, - Set boundProperties, List errors) { + private List convertErrors(ConfigurationPropertyName name, Set boundProperties, + List errors) { List converted = new ArrayList<>(errors.size()); for (ObjectError error : errors) { converted.add(convertError(name, boundProperties, error)); @@ -66,25 +66,24 @@ public class ValidationErrors implements Iterable { return Collections.unmodifiableList(converted); } - private ObjectError convertError(ConfigurationPropertyName name, - Set boundProperties, ObjectError error) { + private ObjectError convertError(ConfigurationPropertyName name, Set boundProperties, + ObjectError error) { if (error instanceof FieldError) { return convertFieldError(name, boundProperties, (FieldError) error); } return error; } - private FieldError convertFieldError(ConfigurationPropertyName name, - Set boundProperties, FieldError error) { + private FieldError convertFieldError(ConfigurationPropertyName name, Set boundProperties, + FieldError error) { if (error instanceof OriginProvider) { return error; } - return OriginTrackedFieldError.of(error, - findFieldErrorOrigin(name, boundProperties, error)); + return OriginTrackedFieldError.of(error, findFieldErrorOrigin(name, boundProperties, error)); } - private Origin findFieldErrorOrigin(ConfigurationPropertyName name, - Set boundProperties, FieldError error) { + private Origin findFieldErrorOrigin(ConfigurationPropertyName name, Set boundProperties, + FieldError error) { for (ConfigurationProperty boundProperty : boundProperties) { if (isForError(name, boundProperty.getName(), error)) { return Origin.from(boundProperty); @@ -93,10 +92,10 @@ public class ValidationErrors implements Iterable { return null; } - private boolean isForError(ConfigurationPropertyName name, - ConfigurationPropertyName boundPropertyName, FieldError error) { - return name.isParentOf(boundPropertyName) && boundPropertyName - .getLastElement(Form.UNIFORM).equalsIgnoreCase(error.getField()); + private boolean isForError(ConfigurationPropertyName name, ConfigurationPropertyName boundPropertyName, + FieldError error) { + return name.isParentOf(boundPropertyName) + && boundPropertyName.getLastElement(Form.UNIFORM).equalsIgnoreCase(error.getField()); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySource.java index 60165a420da..6c48ed3b43f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ class AliasedConfigurationPropertySource implements ConfigurationPropertySource private final ConfigurationPropertyNameAliases aliases; - AliasedConfigurationPropertySource(ConfigurationPropertySource source, - ConfigurationPropertyNameAliases aliases) { + AliasedConfigurationPropertySource(ConfigurationPropertySource source, ConfigurationPropertyNameAliases aliases) { Assert.notNull(source, "Source must not be null"); Assert.notNull(aliases, "Aliases must not be null"); this.source = source; @@ -39,8 +38,7 @@ class AliasedConfigurationPropertySource implements ConfigurationPropertySource } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { Assert.notNull(name, "Name must not be null"); ConfigurationProperty result = getSource().getConfigurationProperty(name); if (result == null) { @@ -51,16 +49,14 @@ class AliasedConfigurationPropertySource implements ConfigurationPropertySource } @Override - public ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { Assert.notNull(name, "Name must not be null"); ConfigurationPropertyState result = this.source.containsDescendantOf(name); if (result != ConfigurationPropertyState.ABSENT) { return result; } for (ConfigurationPropertyName alias : getAliases().getAliases(name)) { - ConfigurationPropertyState aliasResult = this.source - .containsDescendantOf(alias); + ConfigurationPropertyState aliasResult = this.source.containsDescendantOf(alias); if (aliasResult != ConfigurationPropertyState.ABSENT) { return aliasResult; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySource.java index e6c4af27edf..9adf4610cbf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import org.springframework.util.CollectionUtils; * @author Phillip Webb * @author Madhura Bhave */ -class AliasedIterableConfigurationPropertySource - extends AliasedConfigurationPropertySource +class AliasedIterableConfigurationPropertySource extends AliasedConfigurationPropertySource implements IterableConfigurationPropertySource { AliasedIterableConfigurationPropertySource(IterableConfigurationPropertySource source, diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java index b528054a85e..7b07f5ebd1a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.util.ObjectUtils; * @author Madhura Bhave * @since 2.0.0 */ -public final class ConfigurationProperty - implements OriginProvider, Comparable { +public final class ConfigurationProperty implements OriginProvider, Comparable { private final ConfigurationPropertyName name; @@ -41,8 +40,7 @@ public final class ConfigurationProperty private final Origin origin; - public ConfigurationProperty(ConfigurationPropertyName name, Object value, - Origin origin) { + public ConfigurationProperty(ConfigurationPropertyName name, Object value, Origin origin) { Assert.notNull(name, "Name must not be null"); Assert.notNull(value, "Value must not be null"); this.name = name; @@ -87,8 +85,8 @@ public final class ConfigurationProperty @Override public String toString() { - return new ToStringCreator(this).append("name", this.name) - .append("value", this.value).append("origin", this.origin).toString(); + return new ToStringCreator(this).append("name", this.name).append("value", this.value) + .append("origin", this.origin).toString(); } @Override @@ -96,16 +94,14 @@ public final class ConfigurationProperty return this.name.compareTo(other.name); } - static ConfigurationProperty of(ConfigurationPropertyName name, - OriginTrackedValue value) { + static ConfigurationProperty of(ConfigurationPropertyName name, OriginTrackedValue value) { if (value == null) { return null; } return new ConfigurationProperty(name, value.getValue(), value.getOrigin()); } - static ConfigurationProperty of(ConfigurationPropertyName name, Object value, - Origin origin) { + static ConfigurationProperty of(ConfigurationPropertyName name, Object value, Origin origin) { if (value == null) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java index 7f6e85ea0b2..4223e1f7aaa 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java @@ -49,16 +49,14 @@ import org.springframework.util.Assert; * @see #of(CharSequence) * @see ConfigurationPropertySource */ -public final class ConfigurationPropertyName - implements Comparable { +public final class ConfigurationPropertyName implements Comparable { private static final String EMPTY_STRING = ""; /** * An empty {@link ConfigurationPropertyName}. */ - public static final ConfigurationPropertyName EMPTY = new ConfigurationPropertyName( - Elements.EMPTY); + public static final ConfigurationPropertyName EMPTY = new ConfigurationPropertyName(Elements.EMPTY); private Elements elements; @@ -142,16 +140,15 @@ public final class ConfigurationPropertyName } CharSequence uniformElement = this.uniformElements[elementIndex]; if (uniformElement == null) { - uniformElement = (type != ElementType.UNIFORM) - ? convertToUniformElement(element) : element; + uniformElement = (type != ElementType.UNIFORM) ? convertToUniformElement(element) : element; this.uniformElements[elementIndex] = uniformElement.toString(); } return uniformElement.toString(); } private CharSequence convertToOriginalForm(CharSequence element) { - return convertElement(element, false, (ch, i) -> ch == '_' - || ElementsParser.isValidChar(Character.toLowerCase(ch), i)); + return convertElement(element, false, + (ch, i) -> ch == '_' || ElementsParser.isValidChar(Character.toLowerCase(ch), i)); } private CharSequence convertToDashedElement(CharSequence element) { @@ -159,16 +156,13 @@ public final class ConfigurationPropertyName } private CharSequence convertToUniformElement(CharSequence element) { - return convertElement(element, true, - (ch, i) -> ElementsParser.isAlphaNumeric(ch)); + return convertElement(element, true, (ch, i) -> ElementsParser.isAlphaNumeric(ch)); } - private CharSequence convertElement(CharSequence element, boolean lowercase, - ElementCharPredicate filter) { + private CharSequence convertElement(CharSequence element, boolean lowercase, ElementCharPredicate filter) { StringBuilder result = new StringBuilder(element.length()); for (int i = 0; i < element.length(); i++) { - char ch = lowercase ? Character.toLowerCase(element.charAt(i)) - : element.charAt(i); + char ch = lowercase ? Character.toLowerCase(element.charAt(i)) : element.charAt(i); if (filter.test(ch, i)) { result.append(ch); } @@ -279,8 +273,7 @@ public final class ConfigurationPropertyName if (result != 0) { return result; } - if (type1 == ElementType.NUMERICALLY_INDEXED - && type2 == ElementType.NUMERICALLY_INDEXED) { + if (type1 == ElementType.NUMERICALLY_INDEXED && type2 == ElementType.NUMERICALLY_INDEXED) { long v1 = Long.parseLong(e1); long v2 = Long.parseLong(e2); return Long.compare(v1, v2); @@ -322,8 +315,7 @@ public final class ConfigurationPropertyName if (type1.allowsFastEqualityCheck() && type2.allowsFastEqualityCheck()) { return !fastElementEquals(e1, e2, i); } - else if (type1.allowsDashIgnoringEqualityCheck() - && type2.allowsDashIgnoringEqualityCheck()) { + else if (type1.allowsDashIgnoringEqualityCheck() && type2.allowsDashIgnoringEqualityCheck()) { return !dashIgnoringElementEquals(e1, e2, i); } else { @@ -342,10 +334,8 @@ public final class ConfigurationPropertyName if (i2 >= l2) { return false; } - char ch1 = indexed1 ? e1.charAt(i, i1) - : Character.toLowerCase(e1.charAt(i, i1)); - char ch2 = indexed2 ? e2.charAt(i, i2) - : Character.toLowerCase(e2.charAt(i, i2)); + char ch1 = indexed1 ? e1.charAt(i, i1) : Character.toLowerCase(e1.charAt(i, i1)); + char ch2 = indexed2 ? e2.charAt(i, i2) : Character.toLowerCase(e2.charAt(i, i2)); if (!indexed1 && !ElementsParser.isAlphaNumeric(ch1)) { i1++; } @@ -447,8 +437,7 @@ public final class ConfigurationPropertyName } private String buildToString() { - if (this.elements.canShortcutWithSource(ElementType.UNIFORM, - ElementType.DASHED)) { + if (this.elements.canShortcutWithSource(ElementType.UNIFORM, ElementType.DASHED)) { return this.elements.getSource().toString(); } int elements = getNumberOfElements(); @@ -511,8 +500,7 @@ public final class ConfigurationPropertyName return elementsOf(name, returnNullIfInvalid, ElementsParser.DEFAULT_CAPACITY); } - private static Elements elementsOf(CharSequence name, boolean returnNullIfInvalid, - int parserCapacity) { + private static Elements elementsOf(CharSequence name, boolean returnNullIfInvalid, int parserCapacity) { if (name == null) { Assert.isTrue(returnNullIfInvalid, "Name must not be null"); return null; @@ -524,8 +512,7 @@ public final class ConfigurationPropertyName if (returnNullIfInvalid) { return null; } - throw new InvalidConfigurationPropertyNameException(name, - Collections.singletonList('.')); + throw new InvalidConfigurationPropertyNameException(name, Collections.singletonList('.')); } Elements elements = new ElementsParser(name, '.', parserCapacity).parse(); for (int i = 0; i < elements.getSize(); i++) { @@ -533,8 +520,7 @@ public final class ConfigurationPropertyName if (returnNullIfInvalid) { return null; } - throw new InvalidConfigurationPropertyNameException(name, - getInvalidChars(elements, i)); + throw new InvalidConfigurationPropertyNameException(name, getInvalidChars(elements, i)); } } return elements; @@ -581,8 +567,7 @@ public final class ConfigurationPropertyName if (name.length() == 0) { return EMPTY; } - Elements elements = new ElementsParser(name, separator) - .parse(elementValueProcessor); + Elements elements = new ElementsParser(name, separator).parse(elementValueProcessor); if (elements.getSize() == 0) { return EMPTY; } @@ -642,8 +627,7 @@ public final class ConfigurationPropertyName private static final ElementType[] NO_TYPE = {}; - public static final Elements EMPTY = new Elements("", 0, NO_POSITION, NO_POSITION, - NO_TYPE, null); + public static final Elements EMPTY = new Elements("", 0, NO_POSITION, NO_POSITION, NO_TYPE, null); private final CharSequence source; @@ -665,8 +649,7 @@ public final class ConfigurationPropertyName */ private final CharSequence[] resolved; - Elements(CharSequence source, int size, int[] start, int[] end, - ElementType[] type, CharSequence[] resolved) { + Elements(CharSequence source, int size, int[] start, int[] end, ElementType[] type, CharSequence[] resolved) { super(); this.source = source; this.size = size; @@ -677,28 +660,25 @@ public final class ConfigurationPropertyName } public Elements append(Elements additional) { - Assert.isTrue(additional.getSize() == 1, () -> "Element value '" - + additional.getSource() + "' must be a single item"); + Assert.isTrue(additional.getSize() == 1, + () -> "Element value '" + additional.getSource() + "' must be a single item"); ElementType[] type = new ElementType[this.size + 1]; System.arraycopy(this.type, 0, type, 0, this.size); type[this.size] = additional.type[0]; CharSequence[] resolved = newResolved(this.size + 1); resolved[this.size] = additional.get(0); - return new Elements(this.source, this.size + 1, this.start, this.end, type, - resolved); + return new Elements(this.source, this.size + 1, this.start, this.end, type, resolved); } public Elements chop(int size) { CharSequence[] resolved = newResolved(size); - return new Elements(this.source, size, this.start, this.end, this.type, - resolved); + return new Elements(this.source, size, this.start, this.end, this.type, resolved); } private CharSequence[] newResolved(int size) { CharSequence[] resolved = new CharSequence[size]; if (this.resolved != null) { - System.arraycopy(this.resolved, 0, resolved, 0, - Math.min(size, this.size)); + System.arraycopy(this.resolved, 0, resolved, 0, Math.min(size, this.size)); } return resolved; } @@ -758,8 +738,7 @@ public final class ConfigurationPropertyName * @param alternativeType and alternative required type * @return {@code true} if all elements match at least one of the types */ - public boolean canShortcutWithSource(ElementType requiredType, - ElementType alternativeType) { + public boolean canShortcutWithSource(ElementType requiredType, ElementType alternativeType) { if (this.resolved != null) { return false; } @@ -850,8 +829,7 @@ public final class ConfigurationPropertyName type = ElementType.NON_UNIFORM; } add(start, length, type, valueProcessor); - return new Elements(this.source, this.size, this.start, this.end, this.type, - this.resolved); + return new Elements(this.source, this.size, this.start, this.end, this.type, this.resolved); } private ElementType updateType(ElementType existingType, char ch, int index) { @@ -868,8 +846,7 @@ public final class ConfigurationPropertyName return ElementType.DASHED; } if (!isValidChar(ch, index)) { - if (existingType == ElementType.EMPTY - && !isValidChar(Character.toLowerCase(ch), index)) { + if (existingType == ElementType.EMPTY && !isValidChar(Character.toLowerCase(ch), index)) { return ElementType.EMPTY; } return ElementType.NON_UNIFORM; @@ -877,8 +854,7 @@ public final class ConfigurationPropertyName return existingType; } - private void add(int start, int end, ElementType type, - Function valueProcessor) { + private void add(int start, int end, ElementType type, Function valueProcessor) { if ((end - start) < 1 || type == ElementType.EMPTY) { return; } @@ -892,11 +868,9 @@ public final class ConfigurationPropertyName if (this.resolved == null) { this.resolved = new CharSequence[this.start.length]; } - CharSequence resolved = valueProcessor - .apply(this.source.subSequence(start, end)); + CharSequence resolved = valueProcessor.apply(this.source.subSequence(start, end)); Elements resolvedElements = new ElementsParser(resolved, '.').parse(); - Assert.state(resolvedElements.getSize() == 1, - "Resolved element must not contain multiple elements"); + Assert.state(resolvedElements.getSize() == 1, "Resolved element must not contain multiple elements"); this.resolved[this.size] = resolvedElements.get(0); type = resolvedElements.getType(0); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliases.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliases.java index 558b02e2b2d..b0ba54b3417 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliases.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliases.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import org.springframework.util.MultiValueMap; * @since 2.0.0 * @see ConfigurationPropertySource#withAliases(ConfigurationPropertyNameAliases) */ -public final class ConfigurationPropertyNameAliases - implements Iterable { +public final class ConfigurationPropertyNameAliases implements Iterable { private final MultiValueMap aliases = new LinkedMultiValueMap<>(); @@ -46,8 +45,7 @@ public final class ConfigurationPropertyNameAliases addAliases(name, aliases); } - public ConfigurationPropertyNameAliases(ConfigurationPropertyName name, - ConfigurationPropertyName... aliases) { + public ConfigurationPropertyNameAliases(ConfigurationPropertyName name, ConfigurationPropertyName... aliases) { addAliases(name, aliases); } @@ -55,12 +53,10 @@ public final class ConfigurationPropertyNameAliases Assert.notNull(name, "Name must not be null"); Assert.notNull(aliases, "Aliases must not be null"); addAliases(ConfigurationPropertyName.of(name), - Arrays.stream(aliases).map(ConfigurationPropertyName::of) - .toArray(ConfigurationPropertyName[]::new)); + Arrays.stream(aliases).map(ConfigurationPropertyName::of).toArray(ConfigurationPropertyName[]::new)); } - public void addAliases(ConfigurationPropertyName name, - ConfigurationPropertyName... aliases) { + public void addAliases(ConfigurationPropertyName name, ConfigurationPropertyName... aliases) { Assert.notNull(name, "Name must not be null"); Assert.notNull(aliases, "Aliases must not be null"); this.aliases.addAll(name, Arrays.asList(aliases)); @@ -71,8 +67,7 @@ public final class ConfigurationPropertyNameAliases } public ConfigurationPropertyName getNameForAlias(ConfigurationPropertyName alias) { - return this.aliases.entrySet().stream() - .filter((e) -> e.getValue().contains(alias)).map(Map.Entry::getKey) + return this.aliases.entrySet().stream().filter((e) -> e.getValue().contains(alias)).map(Map.Entry::getKey) .findFirst().orElse(null); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySource.java index 2e9edd2b4b1..a1739294c3e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public interface ConfigurationPropertySource { * @param name the name to check * @return if the source contains any descendants */ - default ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + default ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { return ConfigurationPropertyState.UNKNOWN; } @@ -61,8 +60,7 @@ public interface ConfigurationPropertySource { * @param filter the filter to match * @return a filtered {@link ConfigurationPropertySource} instance */ - default ConfigurationPropertySource filter( - Predicate filter) { + default ConfigurationPropertySource filter(Predicate filter) { return new FilteredConfigurationPropertiesSource(this, filter); } @@ -71,8 +69,7 @@ public interface ConfigurationPropertySource { * @param aliases a function that returns a stream of aliases for any given name * @return a {@link ConfigurationPropertySource} instance supporting name aliases */ - default ConfigurationPropertySource withAliases( - ConfigurationPropertyNameAliases aliases) { + default ConfigurationPropertySource withAliases(ConfigurationPropertyNameAliases aliases) { return new AliasedConfigurationPropertySource(this, aliases); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java index 28cfaa6ae58..6c823075bf3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ public final class ConfigurationPropertySources { * @param propertySource the property source to test * @return {@code true} if this is the attached {@link ConfigurationPropertySource} */ - public static boolean isAttachedConfigurationPropertySource( - PropertySource propertySource) { + public static boolean isAttachedConfigurationPropertySource(PropertySource propertySource) { return ATTACHED_PROPERTY_SOURCE_NAME.equals(propertySource.getName()); } @@ -71,16 +70,14 @@ public final class ConfigurationPropertySources { */ public static void attach(Environment environment) { Assert.isInstanceOf(ConfigurableEnvironment.class, environment); - MutablePropertySources sources = ((ConfigurableEnvironment) environment) - .getPropertySources(); + MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources(); PropertySource attached = sources.get(ATTACHED_PROPERTY_SOURCE_NAME); if (attached != null && attached.getSource() != sources) { sources.remove(ATTACHED_PROPERTY_SOURCE_NAME); attached = null; } if (attached == null) { - sources.addFirst(new ConfigurationPropertySourcesPropertySource( - ATTACHED_PROPERTY_SOURCE_NAME, + sources.addFirst(new ConfigurationPropertySourcesPropertySource(ATTACHED_PROPERTY_SOURCE_NAME, new SpringConfigurationPropertySources(sources))); } } @@ -96,8 +93,7 @@ public final class ConfigurationPropertySources { */ public static Iterable get(Environment environment) { Assert.isInstanceOf(ConfigurableEnvironment.class, environment); - MutablePropertySources sources = ((ConfigurableEnvironment) environment) - .getPropertySources(); + MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources(); ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) sources .get(ATTACHED_PROPERTY_SOURCE_NAME); if (attached == null) { @@ -130,21 +126,18 @@ public final class ConfigurationPropertySources { * @return an {@link Iterable} containing newly adapted * {@link SpringConfigurationPropertySource} instances */ - public static Iterable from( - Iterable> sources) { + public static Iterable from(Iterable> sources) { return new SpringConfigurationPropertySources(sources); } - private static Stream> streamPropertySources( - PropertySources sources) { + private static Stream> streamPropertySources(PropertySources sources) { return sources.stream().flatMap(ConfigurationPropertySources::flatten) .filter(ConfigurationPropertySources::isIncluded); } private static Stream> flatten(PropertySource source) { if (source.getSource() instanceof ConfigurableEnvironment) { - return streamPropertySources( - ((ConfigurableEnvironment) source.getSource()).getPropertySources()); + return streamPropertySources(((ConfigurableEnvironment) source.getSource()).getPropertySources()); } return Stream.of(source); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySource.java index 2d791704580..128594aaa59 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,12 +30,10 @@ import org.springframework.core.env.PropertySource; * @author Phillip Webb * @author Madhura Bhave */ -class ConfigurationPropertySourcesPropertySource - extends PropertySource> +class ConfigurationPropertySourcesPropertySource extends PropertySource> implements OriginLookup { - ConfigurationPropertySourcesPropertySource(String name, - Iterable source) { + ConfigurationPropertySourcesPropertySource(String name, Iterable source) { super(name, source); } @@ -59,14 +57,12 @@ class ConfigurationPropertySourcesPropertySource } } - private ConfigurationProperty findConfigurationProperty( - ConfigurationPropertyName name) { + private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) { if (name == null) { return null; } for (ConfigurationPropertySource configurationPropertySource : getSource()) { - ConfigurationProperty configurationProperty = configurationPropertySource - .getConfigurationProperty(name); + ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name); if (configurationProperty != null) { return configurationProperty; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyState.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyState.java index 5121201a2d4..1b88a9a6e1f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyState.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyState.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,7 @@ public enum ConfigurationPropertyState { * @return {@link #PRESENT} if the iterable contains a matching item, otherwise * {@link #ABSENT}. */ - static ConfigurationPropertyState search(Iterable source, - Predicate predicate) { + static ConfigurationPropertyState search(Iterable source, Predicate predicate) { Assert.notNull(source, "Source must not be null"); Assert.notNull(predicate, "Predicate must not be null"); for (T item : source) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/DefaultPropertyMapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/DefaultPropertyMapper.java index ad4bd2e251d..2c0bb649a6b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/DefaultPropertyMapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/DefaultPropertyMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,10 +47,8 @@ final class DefaultPropertyMapper implements PropertyMapper { return last.getMapping(); } String convertedName = configurationPropertyName.toString(); - PropertyMapping[] mapping = { - new PropertyMapping(convertedName, configurationPropertyName) }; - this.lastMappedConfigurationPropertyName = new LastMapping<>( - configurationPropertyName, mapping); + PropertyMapping[] mapping = { new PropertyMapping(convertedName, configurationPropertyName) }; + this.lastMappedConfigurationPropertyName = new LastMapping<>(configurationPropertyName, mapping); return mapping; } @@ -68,11 +66,9 @@ final class DefaultPropertyMapper implements PropertyMapper { private PropertyMapping[] tryMap(String propertySourceName) { try { - ConfigurationPropertyName convertedName = ConfigurationPropertyName - .adapt(propertySourceName, '.'); + ConfigurationPropertyName convertedName = ConfigurationPropertyName.adapt(propertySourceName, '.'); if (!convertedName.isEmpty()) { - return new PropertyMapping[] { - new PropertyMapping(propertySourceName, convertedName) }; + return new PropertyMapping[] { new PropertyMapping(propertySourceName, convertedName) }; } } catch (Exception ex) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSource.java index f6a800127bf..86a266f0133 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,15 +41,13 @@ class FilteredConfigurationPropertiesSource implements ConfigurationPropertySour } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { boolean filtered = getFilter().test(name); return filtered ? getSource().getConfigurationProperty(name) : null; } @Override - public ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { ConfigurationPropertyState result = this.source.containsDescendantOf(name); if (result == ConfigurationPropertyState.PRESENT) { // We can't be sure a contained descendant won't be filtered diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSource.java index b66a535727b..fc357ded160 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,10 @@ import java.util.stream.Stream; * @author Phillip Webb * @author Madhura Bhave */ -class FilteredIterableConfigurationPropertiesSource - extends FilteredConfigurationPropertiesSource +class FilteredIterableConfigurationPropertiesSource extends FilteredConfigurationPropertiesSource implements IterableConfigurationPropertySource { - FilteredIterableConfigurationPropertiesSource( - IterableConfigurationPropertySource source, + FilteredIterableConfigurationPropertiesSource(IterableConfigurationPropertySource source, Predicate filter) { super(source, filter); } @@ -46,8 +44,7 @@ class FilteredIterableConfigurationPropertiesSource } @Override - public ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { return ConfigurationPropertyState.search(this, name::isAncestorOf); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyNameException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyNameException.java index 5e569a5c03a..a05597bafb8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyNameException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyNameException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ public class InvalidConfigurationPropertyNameException extends RuntimeException private final List invalidCharacters; - public InvalidConfigurationPropertyNameException(CharSequence name, - List invalidCharacters) { + public InvalidConfigurationPropertyNameException(CharSequence name, List invalidCharacters) { super("Configuration property name '" + name + "' is not valid"); this.name = name; this.invalidCharacters = invalidCharacters; @@ -45,8 +44,7 @@ public class InvalidConfigurationPropertyNameException extends RuntimeException return this.name; } - public static void throwIfHasInvalidChars(CharSequence name, - List invalidCharacters) { + public static void throwIfHasInvalidChars(CharSequence name, List invalidCharacters) { if (!invalidCharacters.isEmpty()) { throw new InvalidConfigurationPropertyNameException(name, invalidCharacters); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyValueException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyValueException.java index d0ee6e39576..edba3777cab 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyValueException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/InvalidConfigurationPropertyValueException.java @@ -42,8 +42,7 @@ public class InvalidConfigurationPropertyValueException extends RuntimeException * Starts with an upper-case and ends with a dot. Several sentences and carriage * returns are allowed. */ - public InvalidConfigurationPropertyValueException(String name, Object value, - String reason) { + public InvalidConfigurationPropertyValueException(String name, Object value, String reason) { super("Property " + name + " with value '" + value + "' is invalid: " + reason); Assert.notNull(name, "Name must not be null"); this.name = name; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/IterableConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/IterableConfigurationPropertySource.java index ffa25c14655..f60ac9ba7ab 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/IterableConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/IterableConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,20 +59,17 @@ public interface IterableConfigurationPropertySource Stream stream(); @Override - default ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + default ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { return ConfigurationPropertyState.search(this, name::isAncestorOf); } @Override - default IterableConfigurationPropertySource filter( - Predicate filter) { + default IterableConfigurationPropertySource filter(Predicate filter) { return new FilteredIterableConfigurationPropertiesSource(this, filter); } @Override - default IterableConfigurationPropertySource withAliases( - ConfigurationPropertyNameAliases aliases) { + default IterableConfigurationPropertySource withAliases(ConfigurationPropertyNameAliases aliases) { return new AliasedIterableConfigurationPropertySource(this, aliases); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java index fefe640dd39..540cf75461b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import org.springframework.util.Assert; * @author Phillip Webb * @author Madhura Bhave */ -public class MapConfigurationPropertySource - implements IterableConfigurationPropertySource { +public class MapConfigurationPropertySource implements IterableConfigurationPropertySource { private final Map source; @@ -53,8 +52,7 @@ public class MapConfigurationPropertySource */ public MapConfigurationPropertySource(Map map) { this.source = new LinkedHashMap<>(); - this.delegate = new SpringIterableConfigurationPropertySource( - new MapPropertySource("source", this.source), + this.delegate = new SpringIterableConfigurationPropertySource(new MapPropertySource("source", this.source), DefaultPropertyMapper.INSTANCE); putAll(map); } @@ -84,8 +82,7 @@ public class MapConfigurationPropertySource } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { return this.delegate.getConfigurationProperty(name); } @@ -104,8 +101,7 @@ public class MapConfigurationPropertySource map.size(); } catch (UnsupportedOperationException ex) { - throw new IllegalArgumentException( - "Security restricted maps are not supported", ex); + throw new IllegalArgumentException("Security restricted maps are not supported", ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/PropertyMapping.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/PropertyMapping.java index 14161dc2e3c..09ceb0eb795 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/PropertyMapping.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/PropertyMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ class PropertyMapping { * @param configurationPropertyName the {@link ConfigurationPropertySource} * {@link ConfigurationPropertyName} */ - PropertyMapping(String propertySourceName, - ConfigurationPropertyName configurationPropertyName) { + PropertyMapping(String propertySourceName, ConfigurationPropertyName configurationPropertyName) { this.propertySourceName = propertySourceName; this.configurationPropertyName = configurationPropertyName; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java index de59a26a6c4..2dda53a933e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ import org.springframework.util.ObjectUtils; */ class SpringConfigurationPropertySource implements ConfigurationPropertySource { - private static final ConfigurationPropertyName RANDOM = ConfigurationPropertyName - .of("random"); + private static final ConfigurationPropertyName RANDOM = ConfigurationPropertyName.of("random"); private final PropertySource propertySource; @@ -69,28 +68,24 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { * @param containsDescendantOf function used to implement * {@link #containsDescendantOf(ConfigurationPropertyName)} (may be {@code null}) */ - SpringConfigurationPropertySource(PropertySource propertySource, - PropertyMapper mapper, + SpringConfigurationPropertySource(PropertySource propertySource, PropertyMapper mapper, Function containsDescendantOf) { Assert.notNull(propertySource, "PropertySource must not be null"); Assert.notNull(mapper, "Mapper must not be null"); this.propertySource = propertySource; - this.mapper = (mapper instanceof DelegatingPropertyMapper) ? mapper - : new DelegatingPropertyMapper(mapper); + this.mapper = (mapper instanceof DelegatingPropertyMapper) ? mapper : new DelegatingPropertyMapper(mapper); this.containsDescendantOf = (containsDescendantOf != null) ? containsDescendantOf : (n) -> ConfigurationPropertyState.UNKNOWN; } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { PropertyMapping[] mappings = getMapper().map(name); return find(mappings, name); } @Override - public ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { return this.containsDescendantOf.apply(name); } @@ -99,8 +94,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { return this.propertySource; } - protected final ConfigurationProperty find(PropertyMapping[] mappings, - ConfigurationPropertyName name) { + protected final ConfigurationProperty find(PropertyMapping[] mappings, ConfigurationPropertyName name) { for (PropertyMapping candidate : mappings) { if (candidate.isApplicable(name)) { ConfigurationProperty result = find(candidate); @@ -118,8 +112,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { if (value == null) { return null; } - ConfigurationPropertyName configurationPropertyName = mapping - .getConfigurationPropertyName(); + ConfigurationPropertyName configurationPropertyName = mapping.getConfigurationPropertyName(); Origin origin = PropertySourceOrigin.get(this.propertySource, propertySourceName); return ConfigurationProperty.of(configurationPropertyName, value, origin); } @@ -148,16 +141,13 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { Assert.notNull(source, "Source must not be null"); PropertyMapper mapper = getPropertyMapper(source); if (isFullEnumerable(source)) { - return new SpringIterableConfigurationPropertySource( - (EnumerablePropertySource) source, mapper); + return new SpringIterableConfigurationPropertySource((EnumerablePropertySource) source, mapper); } - return new SpringConfigurationPropertySource(source, mapper, - getContainsDescendantOfForSource(source)); + return new SpringConfigurationPropertySource(source, mapper, getContainsDescendantOfForSource(source)); } private static PropertyMapper getPropertyMapper(PropertySource source) { - if (source instanceof SystemEnvironmentPropertySource - && hasSystemEnvironmentName(source)) { + if (source instanceof SystemEnvironmentPropertySource && hasSystemEnvironmentName(source)) { return new DelegatingPropertyMapper(SystemEnvironmentPropertyMapper.INSTANCE, DefaultPropertyMapper.INSTANCE); } @@ -167,8 +157,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { private static boolean hasSystemEnvironmentName(PropertySource source) { String name = source.getName(); return StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME.equals(name) - || name.endsWith("-" - + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + || name.endsWith("-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); } private static boolean isFullEnumerable(PropertySource source) { @@ -186,8 +175,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { } private static PropertySource getRootSource(PropertySource source) { - while (source.getSource() != null - && source.getSource() instanceof PropertySource) { + while (source.getSource() != null && source.getSource() instanceof PropertySource) { source = (PropertySource) source.getSource(); } return source; @@ -201,8 +189,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { return null; } - private static ConfigurationPropertyState containsDescendantOfForRandom( - ConfigurationPropertyName name) { + private static ConfigurationPropertyState containsDescendantOfForRandom(ConfigurationPropertyName name) { if (name.isAncestorOf(RANDOM) || name.equals(RANDOM)) { return ConfigurationPropertyState.PRESENT; } @@ -231,15 +218,13 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { } @Override - public PropertyMapping[] map( - ConfigurationPropertyName configurationPropertyName) { + public PropertyMapping[] map(ConfigurationPropertyName configurationPropertyName) { PropertyMapping[] first = map(this.first, configurationPropertyName); PropertyMapping[] second = map(this.second, configurationPropertyName); return merge(first, second); } - private PropertyMapping[] map(PropertyMapper mapper, - ConfigurationPropertyName configurationPropertyName) { + private PropertyMapping[] map(PropertyMapper mapper, ConfigurationPropertyName configurationPropertyName) { try { return (mapper != null) ? mapper.map(configurationPropertyName) : NONE; } @@ -264,8 +249,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { } } - private PropertyMapping[] merge(PropertyMapping[] first, - PropertyMapping[] second) { + private PropertyMapping[] merge(PropertyMapping[] first, PropertyMapping[] second) { if (ObjectUtils.isEmpty(second)) { return first; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java index 6c9d69b704c..feb31215c42 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,13 +37,12 @@ import org.springframework.util.ConcurrentReferenceHashMap.ReferenceType; * * @author Phillip Webb */ -class SpringConfigurationPropertySources - implements Iterable { +class SpringConfigurationPropertySources implements Iterable { private final Iterable> sources; - private final Map, ConfigurationPropertySource> cache = new ConcurrentReferenceHashMap<>( - 16, ReferenceType.SOFT); + private final Map, ConfigurationPropertySource> cache = new ConcurrentReferenceHashMap<>(16, + ReferenceType.SOFT); SpringConfigurationPropertySources(Iterable> sources) { Assert.notNull(sources, "Sources must not be null"); @@ -67,8 +66,7 @@ class SpringConfigurationPropertySources return result; } - private static class SourcesIterator - implements Iterator { + private static class SourcesIterator implements Iterator { private final Deque>> iterators; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java index 93bc099fd0e..2124c8d3bfe 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java @@ -49,8 +49,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope private volatile Cache cache; - SpringIterableConfigurationPropertySource(EnumerablePropertySource propertySource, - PropertyMapper mapper) { + SpringIterableConfigurationPropertySource(EnumerablePropertySource propertySource, PropertyMapper mapper) { super(propertySource, mapper, null); assertEnumerablePropertySource(); } @@ -61,17 +60,14 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope ((MapPropertySource) getPropertySource()).getSource().size(); } catch (UnsupportedOperationException ex) { - throw new IllegalArgumentException( - "PropertySource must be fully enumerable"); + throw new IllegalArgumentException("PropertySource must be fully enumerable"); } } } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { - ConfigurationProperty configurationProperty = super.getConfigurationProperty( - name); + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { + ConfigurationProperty configurationProperty = super.getConfigurationProperty(name); if (configurationProperty == null) { configurationProperty = find(getPropertyMappings(getCache()), name); } @@ -89,8 +85,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope } @Override - public ConfigurationPropertyState containsDescendantOf( - ConfigurationPropertyName name) { + public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { return ConfigurationPropertyState.search(this, name::isAncestorOf); } @@ -192,8 +187,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope private static final class CacheKey { - private static final CacheKey IMMUTABLE_PROPERTY_SOURCE = new CacheKey( - new Object[0]); + private static final CacheKey IMMUTABLE_PROPERTY_SOURCE = new CacheKey(new Object[0]); private final Object key; @@ -247,8 +241,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope if (source instanceof OriginTrackedMapPropertySource) { return ((OriginTrackedMapPropertySource) source).isImmutable(); } - if (StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME - .equals(source.getName())) { + if (StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME.equals(source.getName())) { return source.getSource() == System.getenv(); } return false; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapper.java index d25dcd46803..1f58211eb49 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,11 +41,9 @@ final class SystemEnvironmentPropertyMapper implements PropertyMapper { String name = convertName(configurationPropertyName); String legacyName = convertLegacyName(configurationPropertyName); if (name.equals(legacyName)) { - return new PropertyMapping[] { - new PropertyMapping(name, configurationPropertyName) }; + return new PropertyMapping[] { new PropertyMapping(name, configurationPropertyName) }; } - return new PropertyMapping[] { - new PropertyMapping(name, configurationPropertyName), + return new PropertyMapping[] { new PropertyMapping(name, configurationPropertyName), new PropertyMapping(legacyName, configurationPropertyName) }; } @@ -60,8 +58,7 @@ final class SystemEnvironmentPropertyMapper implements PropertyMapper { private ConfigurationPropertyName convertName(String propertySourceName) { try { - return ConfigurationPropertyName.adapt(propertySourceName, '_', - this::processElementValue); + return ConfigurationPropertyName.adapt(propertySourceName, '_', this::processElementValue); } catch (Exception ex) { return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java index 6439eee538a..07c000cc207 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,12 +34,10 @@ import org.springframework.core.env.StandardEnvironment; * @author Madhura Bhave * @since 2.0.0 */ -public class UnboundElementsSourceFilter - implements Function { +public class UnboundElementsSourceFilter implements Function { private static final Set BENIGN_PROPERTY_SOURCE_NAMES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + .unmodifiableSet(new HashSet<>(Arrays.asList(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ArrayToDelimitedStringConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ArrayToDelimitedStringConverter.java index d8b138263e9..63ee0ff3c24 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ArrayToDelimitedStringConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ArrayToDelimitedStringConverter.java @@ -50,8 +50,7 @@ final class ArrayToDelimitedStringConverter implements ConditionalGenericConvert } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { List list = Arrays.asList(ObjectUtils.toObjectArray(source)); return this.delegate.convert(list, sourceType, targetType); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java index 710d10d493d..6d6f6d39ae8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,7 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } @@ -66,13 +65,11 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo return convert(sourceCollection, sourceType, targetType); } - private Object convert(Collection source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + private Object convert(Collection source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source.isEmpty()) { return ""; } - return source.stream() - .map((element) -> convertElement(element, sourceType, targetType)) + return source.stream().map((element) -> convertElement(element, sourceType, targetType)) .collect(Collectors.joining(getDelimiter(sourceType))); } @@ -81,10 +78,9 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo return (annotation != null) ? annotation.value() : ","; } - private String convertElement(Object element, TypeDescriptor sourceType, - TypeDescriptor targetType) { - return String.valueOf(this.conversionService.convert(element, - sourceType.elementTypeDescriptor(element), targetType)); + private String convertElement(Object element, TypeDescriptor sourceType, TypeDescriptor targetType) { + return String.valueOf( + this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToArrayConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToArrayConverter.java index 6e678d81a96..e2b4237924b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToArrayConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToArrayConverter.java @@ -47,38 +47,33 @@ final class DelimitedStringToArrayConverter implements ConditionalGenericConvert @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return targetType.getElementTypeDescriptor() == null || this.conversionService - .canConvert(sourceType, targetType.getElementTypeDescriptor()); + return targetType.getElementTypeDescriptor() == null + || this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } - private Object convert(String source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); - String[] elements = getElements(source, - (delimiter != null) ? delimiter.value() : ","); + String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Object target = Array.newInstance(elementDescriptor.getType(), elements.length); for (int i = 0; i < elements.length; i++) { String sourceElement = elements[i]; - Object targetElement = this.conversionService.convert(sourceElement.trim(), - sourceType, elementDescriptor); + Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, elementDescriptor); Array.set(target, i, targetElement); } return target; } private String[] getElements(String source, String delimiter) { - return StringUtils.delimitedListToStringArray(source, - Delimiter.NONE.equals(delimiter) ? null : delimiter); + return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java index 32fd0214e9c..7f5281a28f9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java @@ -50,45 +50,39 @@ final class DelimitedStringToCollectionConverter implements ConditionalGenericCo @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return targetType.getElementTypeDescriptor() == null || this.conversionService - .canConvert(sourceType, targetType.getElementTypeDescriptor()); + return targetType.getElementTypeDescriptor() == null + || this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } - private Object convert(String source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); - String[] elements = getElements(source, - (delimiter != null) ? delimiter.value() : ","); + String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); - Collection target = createCollection(targetType, elementDescriptor, - elements.length); + Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { - stream = stream.map((element) -> this.conversionService.convert(element, - sourceType, elementDescriptor)); + stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } - private Collection createCollection(TypeDescriptor targetType, - TypeDescriptor elementDescriptor, int length) { + private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, + int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { - return StringUtils.delimitedListToStringArray(source, - Delimiter.NONE.equals(delimiter) ? null : delimiter); + return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/Delimiter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/Delimiter.java index fea7e84c160..139c5a81d06 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/Delimiter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/Delimiter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import java.lang.annotation.Target; */ @Documented @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) public @interface Delimiter { /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java index 0370e9b1a7d..5d4969439d0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,12 +44,11 @@ public enum DurationStyle { Matcher matcher = matcher(value); Assert.state(matcher.matches(), "Does not match simple duration pattern"); String suffix = matcher.group(2); - return (StringUtils.hasLength(suffix) ? Unit.fromSuffix(suffix) - : Unit.fromChronoUnit(unit)).parse(matcher.group(1)); + return (StringUtils.hasLength(suffix) ? Unit.fromSuffix(suffix) : Unit.fromChronoUnit(unit)) + .parse(matcher.group(1)); } catch (Exception ex) { - throw new IllegalArgumentException( - "'" + value + "' is not a valid simple duration", ex); + throw new IllegalArgumentException("'" + value + "' is not a valid simple duration", ex); } } @@ -71,8 +70,7 @@ public enum DurationStyle { return Duration.parse(value); } catch (Exception ex) { - throw new IllegalArgumentException( - "'" + value + "' is not a valid ISO-8601 duration", ex); + throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java index 397a3c1c1ea..abf2bae3f1f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,13 +41,11 @@ final class DurationToNumberConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } - return convert((Duration) source, getDurationUnit(sourceType), - targetType.getObjectType()); + return convert((Duration) source, getDurationUnit(sourceType), targetType.getObjectType()); } private ChronoUnit getDurationUnit(TypeDescriptor sourceType) { @@ -57,8 +55,8 @@ final class DurationToNumberConverter implements GenericConverter { private Object convert(Duration source, ChronoUnit unit, Class type) { try { - return type.getConstructor(String.class).newInstance(String - .valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source))); + return type.getConstructor(String.class) + .newInstance(String.valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source))); } catch (Exception ex) { ReflectionUtils.rethrowRuntimeException(ex); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToStringConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToStringConverter.java index 9371d34c229..e1acd4a14ab 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToStringConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToStringConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,13 +40,11 @@ final class DurationToStringConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } - return convert((Duration) source, getDurationStyle(sourceType), - getDurationUnit(sourceType)); + return convert((Duration) source, getDurationStyle(sourceType), getDurationUnit(sourceType)); } private ChronoUnit getDurationUnit(TypeDescriptor sourceType) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDataSizeConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDataSizeConverter.java index 14f2f2f35ae..b2b52b0c5d7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDataSizeConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDataSizeConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,9 @@ final class NumberToDataSizeConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { - return this.delegate.convert((source != null) ? source.toString() : null, - TypeDescriptor.valueOf(String.class), targetType); + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + return this.delegate.convert((source != null) ? source.toString() : null, TypeDescriptor.valueOf(String.class), + targetType); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDurationConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDurationConverter.java index 9b4088ca8c9..c7ef6f8851e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDurationConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDurationConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,10 +42,9 @@ final class NumberToDurationConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { - return this.delegate.convert((source != null) ? source.toString() : null, - TypeDescriptor.valueOf(String.class), targetType); + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + return this.delegate.convert((source != null) ? source.toString() : null, TypeDescriptor.valueOf(String.class), + targetType); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDataSizeConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDataSizeConverter.java index ae0a8656512..b23f1f7c51e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDataSizeConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDataSizeConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ final class StringToDataSizeConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (ObjectUtils.isEmpty(source)) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java index 78d9c1436ca..6781c277e6b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,13 +42,11 @@ final class StringToDurationConverter implements GenericConverter { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (ObjectUtils.isEmpty(source)) { return null; } - return convert(source.toString(), getStyle(targetType), - getDurationUnit(targetType)); + return convert(source.toString(), getStyle(targetType), getDurationUnit(targetType)); } private DurationStyle getStyle(TypeDescriptor targetType) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactory.java index 0c803e5cdce..dd856d03cb6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.util.Assert; * @author Phillip Webb */ @SuppressWarnings({ "unchecked", "rawtypes" }) -final class StringToEnumIgnoringCaseConverterFactory - implements ConverterFactory { +final class StringToEnumIgnoringCaseConverterFactory implements ConverterFactory { @Override public Converter getConverter(Class targetType) { @@ -39,8 +38,7 @@ final class StringToEnumIgnoringCaseConverterFactory while (enumType != null && !enumType.isEnum()) { enumType = enumType.getSuperclass(); } - Assert.notNull(enumType, () -> "The target type " + targetType.getName() - + " does not refer to an enum"); + Assert.notNull(enumType, () -> "The target type " + targetType.getName() + " does not refer to an enum"); return new StringToEnum(enumType); } @@ -73,14 +71,13 @@ final class StringToEnumIgnoringCaseConverterFactory return candidate; } } - throw new IllegalArgumentException("No enum constant " - + this.enumType.getCanonicalName() + "." + source); + throw new IllegalArgumentException("No enum constant " + this.enumType.getCanonicalName() + "." + source); } private String getLettersAndDigits(String name) { StringBuilder canonicalName = new StringBuilder(name.length()); - name.chars().map((c) -> (char) c).filter(Character::isLetterOrDigit) - .map(Character::toLowerCase).forEach(canonicalName::append); + name.chars().map((c) -> (char) c).filter(Character::isLetterOrDigit).map(Character::toLowerCase) + .forEach(canonicalName::append); return canonicalName.toString(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java index 39431a041ec..d2641962db8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import org.springframework.core.ResolvableType; * @author Phillip Webb * @since 1.4.0 */ -public abstract class AbstractFailureAnalyzer - implements FailureAnalyzer { +public abstract class AbstractFailureAnalyzer implements FailureAnalyzer { @Override public FailureAnalysis analyze(Throwable failure) { @@ -54,8 +53,7 @@ public abstract class AbstractFailureAnalyzer */ @SuppressWarnings("unchecked") protected Class getCauseType() { - return (Class) ResolvableType - .forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric(); + return (Class) ResolvableType.forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric(); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java index 3eed97f97c1..2661e260f6b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,13 +67,11 @@ final class FailureAnalyzers implements SpringBootExceptionReporter { } private List loadFailureAnalyzers(ClassLoader classLoader) { - List analyzerNames = SpringFactoriesLoader - .loadFactoryNames(FailureAnalyzer.class, classLoader); + List analyzerNames = SpringFactoriesLoader.loadFactoryNames(FailureAnalyzer.class, classLoader); List analyzers = new ArrayList<>(); for (String analyzerName : analyzerNames) { try { - Constructor constructor = ClassUtils.forName(analyzerName, classLoader) - .getDeclaredConstructor(); + Constructor constructor = ClassUtils.forName(analyzerName, classLoader).getDeclaredConstructor(); ReflectionUtils.makeAccessible(constructor); analyzers.add((FailureAnalyzer) constructor.newInstance()); } @@ -85,15 +83,13 @@ final class FailureAnalyzers implements SpringBootExceptionReporter { return analyzers; } - private void prepareFailureAnalyzers(List analyzers, - ConfigurableApplicationContext context) { + private void prepareFailureAnalyzers(List analyzers, ConfigurableApplicationContext context) { for (FailureAnalyzer analyzer : analyzers) { prepareAnalyzer(context, analyzer); } } - private void prepareAnalyzer(ConfigurableApplicationContext context, - FailureAnalyzer analyzer) { + private void prepareAnalyzer(ConfigurableApplicationContext context, FailureAnalyzer analyzer) { if (analyzer instanceof BeanFactoryAware) { ((BeanFactoryAware) analyzer).setBeanFactory(context.getBeanFactory()); } @@ -124,8 +120,8 @@ final class FailureAnalyzers implements SpringBootExceptionReporter { } private boolean report(FailureAnalysis analysis, ClassLoader classLoader) { - List reporters = SpringFactoriesLoader - .loadFactories(FailureAnalysisReporter.class, classLoader); + List reporters = SpringFactoriesLoader.loadFactories(FailureAnalysisReporter.class, + classLoader); if (analysis == null || reporters.isEmpty()) { return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java index 6227d1b4135..04d75f9b78b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,14 +29,12 @@ import org.springframework.util.StringUtils; */ public final class LoggingFailureAnalysisReporter implements FailureAnalysisReporter { - private static final Log logger = LogFactory - .getLog(LoggingFailureAnalysisReporter.class); + private static final Log logger = LogFactory.getLog(LoggingFailureAnalysisReporter.class); @Override public void report(FailureAnalysis failureAnalysis) { if (logger.isDebugEnabled()) { - logger.debug("Application failed to start due to an exception", - failureAnalysis.getCause()); + logger.debug("Application failed to start due to an exception", failureAnalysis.getCause()); } if (logger.isErrorEnabled()) { logger.error(buildMessage(failureAnalysis)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java index 745b0715289..b3c335cc113 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.util.ClassUtils; * @author Stephane Nicoll * @since 1.4.1 */ -public abstract class AbstractInjectionFailureAnalyzer - extends AbstractFailureAnalyzer { +public abstract class AbstractInjectionFailureAnalyzer extends AbstractFailureAnalyzer { @Override protected final FailureAnalysis analyze(Throwable rootFailure, T cause) { @@ -42,13 +41,13 @@ public abstract class AbstractInjectionFailureAnalyzer } private String getDescription(Throwable rootFailure) { - UnsatisfiedDependencyException unsatisfiedDependency = findMostNestedCause( - rootFailure, UnsatisfiedDependencyException.class); + UnsatisfiedDependencyException unsatisfiedDependency = findMostNestedCause(rootFailure, + UnsatisfiedDependencyException.class); if (unsatisfiedDependency != null) { return getDescription(unsatisfiedDependency); } - BeanInstantiationException beanInstantiationException = findMostNestedCause( - rootFailure, BeanInstantiationException.class); + BeanInstantiationException beanInstantiationException = findMostNestedCause(rootFailure, + BeanInstantiationException.class); if (beanInstantiationException != null) { return getDescription(beanInstantiationException); } @@ -72,22 +71,19 @@ public abstract class AbstractInjectionFailureAnalyzer InjectionPoint injectionPoint = ex.getInjectionPoint(); if (injectionPoint != null) { if (injectionPoint.getField() != null) { - return String.format("Field %s in %s", - injectionPoint.getField().getName(), + return String.format("Field %s in %s", injectionPoint.getField().getName(), injectionPoint.getField().getDeclaringClass().getName()); } if (injectionPoint.getMethodParameter() != null) { if (injectionPoint.getMethodParameter().getConstructor() != null) { return String.format("Parameter %d of constructor in %s", injectionPoint.getMethodParameter().getParameterIndex(), - injectionPoint.getMethodParameter().getDeclaringClass() - .getName()); + injectionPoint.getMethodParameter().getDeclaringClass().getName()); } return String.format("Parameter %d of method %s in %s", injectionPoint.getMethodParameter().getParameterIndex(), injectionPoint.getMethodParameter().getMethod().getName(), - injectionPoint.getMethodParameter().getDeclaringClass() - .getName()); + injectionPoint.getMethodParameter().getDeclaringClass().getName()); } } return ex.getResourceDescription(); @@ -99,8 +95,8 @@ public abstract class AbstractInjectionFailureAnalyzer ex.getConstructingMethod().getDeclaringClass().getName()); } if (ex.getConstructor() != null) { - return String.format("Constructor in %s", ClassUtils - .getUserClass(ex.getConstructor().getDeclaringClass()).getName()); + return String.format("Constructor in %s", + ClassUtils.getUserClass(ex.getConstructor().getDeclaringClass()).getName()); } return ex.getBeanClass().getName(); } @@ -113,7 +109,6 @@ public abstract class AbstractInjectionFailureAnalyzer * @param description the description of the injection point or {@code null} * @return the analysis or {@code null} */ - protected abstract FailureAnalysis analyze(Throwable rootFailure, T cause, - String description); + protected abstract FailureAnalysis analyze(Throwable rootFailure, T cause, String description); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java index 1881708dc39..4f5b9bf7991 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,12 +33,10 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -class BeanCurrentlyInCreationFailureAnalyzer - extends AbstractFailureAnalyzer { +class BeanCurrentlyInCreationFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - BeanCurrentlyInCreationException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, BeanCurrentlyInCreationException cause) { DependencyCycle dependencyCycle = findCycle(rootFailure); if (dependencyCycle == null) { return null; @@ -69,8 +67,8 @@ class BeanCurrentlyInCreationFailureAnalyzer private String buildMessage(DependencyCycle dependencyCycle) { StringBuilder message = new StringBuilder(); - message.append(String.format("The dependencies of some of the beans in the " - + "application context form a cycle:%n%n")); + message.append(String + .format("The dependencies of some of the beans in the " + "application context form a cycle:%n%n")); List beansInCycle = dependencyCycle.getBeansInCycle(); int cycleStart = dependencyCycle.getCycleStart(); for (int i = 0; i < beansInCycle.size(); i++) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzer.java index f01dda9ff46..3664695ef9f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,15 +29,13 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Andy Wilkinson */ -class BeanDefinitionOverrideFailureAnalyzer - extends AbstractFailureAnalyzer { +class BeanDefinitionOverrideFailureAnalyzer extends AbstractFailureAnalyzer { private static final String ACTION = "Consider renaming one of the beans or enabling " + "overriding by setting spring.main.allow-bean-definition-overriding=true"; @Override - protected FailureAnalysis analyze(Throwable rootFailure, - BeanDefinitionOverrideException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, BeanDefinitionOverrideException cause) { return new FailureAnalysis(getDescription(cause), ACTION, cause); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java index 2b9143f3c42..d07c63f24e8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,17 +30,14 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Andy Wilkinson */ -public class BeanNotOfRequiredTypeFailureAnalyzer - extends AbstractFailureAnalyzer { +public class BeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer { private static final String ACTION = "Consider injecting the bean as one of its " + "interfaces or forcing the use of CGLib-based " - + "proxies by setting proxyTargetClass=true on @EnableAsync and/or " - + "@EnableCaching."; + + "proxies by setting proxyTargetClass=true on @EnableAsync and/or " + "@EnableCaching."; @Override - protected FailureAnalysis analyze(Throwable rootFailure, - BeanNotOfRequiredTypeException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) { if (!Proxy.isProxyClass(cause.getActualType())) { return null; } @@ -50,10 +47,8 @@ public class BeanNotOfRequiredTypeFailureAnalyzer private String getDescription(BeanNotOfRequiredTypeException ex) { StringWriter description = new StringWriter(); PrintWriter printer = new PrintWriter(description); - printer.printf( - "The bean '%s' could not be injected as a '%s' because it is a " - + "JDK dynamic proxy that implements:%n", - ex.getBeanName(), ex.getRequiredType().getName()); + printer.printf("The bean '%s' could not be injected as a '%s' because it is a " + + "JDK dynamic proxy that implements:%n", ex.getBeanName(), ex.getRequiredType().getName()); for (Class requiredTypeInterface : ex.getRequiredType().getInterfaces()) { printer.println("\t" + requiredTypeInterface.getName()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java index ff0b719016e..1a735ed667e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,16 +52,14 @@ class BindFailureAnalyzer extends AbstractFailureAnalyzer { } private FailureAnalysis analyzeGenericBindException(BindException cause) { - StringBuilder description = new StringBuilder( - String.format("%s:%n", cause.getMessage())); + StringBuilder description = new StringBuilder(String.format("%s:%n", cause.getMessage())); ConfigurationProperty property = cause.getProperty(); buildDescription(description, property); description.append(String.format("%n Reason: %s", getMessage(cause))); return getFailureAnalysis(description, cause); } - private void buildDescription(StringBuilder description, - ConfigurationProperty property) { + private void buildDescription(StringBuilder description, ConfigurationProperty property) { if (property != null) { description.append(String.format("%n Property: %s", property.getName())); description.append(String.format("%n Value: %s", property.getValue())); @@ -70,8 +68,7 @@ class BindFailureAnalyzer extends AbstractFailureAnalyzer { } private String getMessage(BindException cause) { - ConversionFailedException conversionFailure = findCause(cause, - ConversionFailedException.class); + ConversionFailedException conversionFailure = findCause(cause, ConversionFailedException.class); if (conversionFailure != null) { return "failed to convert " + conversionFailure.getSourceType() + " to " + conversionFailure.getTargetType(); @@ -80,31 +77,25 @@ class BindFailureAnalyzer extends AbstractFailureAnalyzer { while (failure.getCause() != null) { failure = failure.getCause(); } - return (StringUtils.hasText(failure.getMessage()) ? failure.getMessage() - : cause.getMessage()); + return (StringUtils.hasText(failure.getMessage()) ? failure.getMessage() : cause.getMessage()); } private FailureAnalysis getFailureAnalysis(Object description, BindException cause) { - StringBuilder message = new StringBuilder( - "Update your application's configuration"); + StringBuilder message = new StringBuilder("Update your application's configuration"); Collection validValues = findValidValues(cause); if (!validValues.isEmpty()) { message.append(String.format(". The following values are valid:%n")); - validValues - .forEach((value) -> message.append(String.format("%n %s", value))); + validValues.forEach((value) -> message.append(String.format("%n %s", value))); } return new FailureAnalysis(description.toString(), message.toString(), cause); } private Collection findValidValues(BindException ex) { - ConversionFailedException conversionFailure = findCause(ex, - ConversionFailedException.class); + ConversionFailedException conversionFailure = findCause(ex, ConversionFailedException.class); if (conversionFailure != null) { - Object[] enumConstants = conversionFailure.getTargetType().getType() - .getEnumConstants(); + Object[] enumConstants = conversionFailure.getTargetType().getType().getEnumConstants(); if (enumConstants != null) { - return Stream.of(enumConstants).map(Object::toString) - .collect(Collectors.toCollection(TreeSet::new)); + return Stream.of(enumConstants).map(Object::toString).collect(Collectors.toCollection(TreeSet::new)); } } return Collections.emptySet(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzer.java index ebd093e2b54..f9e28087bbc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,16 +45,14 @@ class BindValidationFailureAnalyzer extends AbstractFailureAnalyzer { } private ExceptionDetails getBindValidationExceptionDetails(Throwable rootFailure) { - BindValidationException validationException = findCause(rootFailure, - BindValidationException.class); + BindValidationException validationException = findCause(rootFailure, BindValidationException.class); if (validationException != null) { BindException target = findCause(rootFailure, BindException.class); - List errors = validationException.getValidationErrors() - .getAllErrors(); + List errors = validationException.getValidationErrors().getAllErrors(); return new ExceptionDetails(errors, target, validationException); } - org.springframework.validation.BindException bindException = findCause( - rootFailure, org.springframework.validation.BindException.class); + org.springframework.validation.BindException bindException = findCause(rootFailure, + org.springframework.validation.BindException.class); if (bindException != null) { List errors = bindException.getAllErrors(); return new ExceptionDetails(errors, bindException.getTarget(), bindException); @@ -69,16 +67,14 @@ class BindValidationFailureAnalyzer extends AbstractFailureAnalyzer { if (error instanceof FieldError) { appendFieldError(description, (FieldError) error); } - description.append( - String.format("%n Reason: %s%n", error.getDefaultMessage())); + description.append(String.format("%n Reason: %s%n", error.getDefaultMessage())); } return getFailureAnalysis(description, details.getCause()); } private void appendFieldError(StringBuilder description, FieldError error) { Origin origin = Origin.from(error); - description.append(String.format("%n Property: %s", - error.getObjectName() + "." + error.getField())); + description.append(String.format("%n Property: %s", error.getObjectName() + "." + error.getField())); description.append(String.format("%n Value: %s", error.getRejectedValue())); if (origin != null) { description.append(String.format("%n Origin: %s", origin)); @@ -86,8 +82,7 @@ class BindValidationFailureAnalyzer extends AbstractFailureAnalyzer { } private FailureAnalysis getFailureAnalysis(Object description, Throwable cause) { - return new FailureAnalysis(description.toString(), - "Update your application's configuration", cause); + return new FailureAnalysis(description.toString(), "Update your application's configuration", cause); } private static class ExceptionDetails { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java index a4e6e272e46..23d71fe54b3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,19 +25,14 @@ import org.springframework.boot.web.embedded.tomcat.ConnectorStartFailedExceptio * * @author Andy Wilkinson */ -class ConnectorStartFailureAnalyzer - extends AbstractFailureAnalyzer { +class ConnectorStartFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - ConnectorStartFailedException cause) { - return new FailureAnalysis( - "The Tomcat connector configured to listen on port " + cause.getPort() - + " failed to start. The port may already be in use or the" - + " connector may be misconfigured.", - "Verify the connector's configuration, identify and stop any process " - + "that's listening on port " + cause.getPort() - + ", or configure this application to listen on another port.", + protected FailureAnalysis analyze(Throwable rootFailure, ConnectorStartFailedException cause) { + return new FailureAnalysis("The Tomcat connector configured to listen on port " + cause.getPort() + + " failed to start. The port may already be in use or the" + " connector may be misconfigured.", + "Verify the connector's configuration, identify and stop any process " + "that's listening on port " + + cause.getPort() + ", or configure this application to listen on another port.", cause); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzer.java index 3fa7e2e038d..365dd8a039d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzer.java @@ -30,8 +30,7 @@ public class InvalidConfigurationPropertiesFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - InvalidConfigurationPropertiesException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, InvalidConfigurationPropertiesException cause) { String configurationProperties = cause.getConfigurationProperties().getName(); String component = cause.getComponent().getSimpleName(); return new FailureAnalysis(getDescription(configurationProperties, component), @@ -39,8 +38,7 @@ public class InvalidConfigurationPropertiesFailureAnalyzer } private String getDescription(String configurationProperties, String component) { - return configurationProperties - + " is annotated with @ConfigurationProperties and @" + component + return configurationProperties + " is annotated with @ConfigurationProperties and @" + component + ". This may cause the @ConfigurationProperties bean to be registered twice."; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzer.java index 1442cc38157..838f1dfc237 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,29 +33,23 @@ class InvalidConfigurationPropertyNameFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - InvalidConfigurationPropertyNameException cause) { - BeanCreationException exception = findCause(rootFailure, - BeanCreationException.class); - String action = String.format( - "Modify '%s' so that it conforms to the canonical names requirements.", + protected FailureAnalysis analyze(Throwable rootFailure, InvalidConfigurationPropertyNameException cause) { + BeanCreationException exception = findCause(rootFailure, BeanCreationException.class); + String action = String.format("Modify '%s' so that it conforms to the canonical names requirements.", cause.getName()); return new FailureAnalysis(buildDescription(cause, exception), action, cause); } - private String buildDescription(InvalidConfigurationPropertyNameException cause, - BeanCreationException exception) { - StringBuilder description = new StringBuilder(String.format( - "Configuration property name '%s' is not valid:%n", cause.getName())); - String invalid = cause.getInvalidCharacters().stream().map(this::quote) - .collect(Collectors.joining(", ")); + private String buildDescription(InvalidConfigurationPropertyNameException cause, BeanCreationException exception) { + StringBuilder description = new StringBuilder( + String.format("Configuration property name '%s' is not valid:%n", cause.getName())); + String invalid = cause.getInvalidCharacters().stream().map(this::quote).collect(Collectors.joining(", ")); description.append(String.format("%n Invalid characters: %s", invalid)); if (exception != null) { description.append(String.format("%n Bean: %s", exception.getBeanName())); } description.append(String.format("%n Reason: Canonical names should be " - + "kebab-case ('-' separated), lowercase alpha-numeric characters" - + " and must start with a letter")); + + "kebab-case ('-' separated), lowercase alpha-numeric characters" + " and must start with a letter")); return description.toString(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java index 2dabc4480ad..1a33bbfd454 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java @@ -40,8 +40,7 @@ import org.springframework.util.StringUtils; * @author Stephane Nicoll */ class InvalidConfigurationPropertyValueFailureAnalyzer - extends AbstractFailureAnalyzer - implements EnvironmentAware { + extends AbstractFailureAnalyzer implements EnvironmentAware { private ConfigurableEnvironment environment; @@ -51,8 +50,7 @@ class InvalidConfigurationPropertyValueFailureAnalyzer } @Override - protected FailureAnalysis analyze(Throwable rootFailure, - InvalidConfigurationPropertyValueException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, InvalidConfigurationPropertyValueException cause) { List descriptors = getDescriptors(cause.getName()); if (descriptors.isEmpty()) { return null; @@ -65,10 +63,8 @@ class InvalidConfigurationPropertyValueFailureAnalyzer } private List getDescriptors(String propertyName) { - return getPropertySources() - .filter((source) -> source.containsProperty(propertyName)) - .map((source) -> Descriptor.get(source, propertyName)) - .collect(Collectors.toList()); + return getPropertySources().filter((source) -> source.containsProperty(propertyName)) + .map((source) -> Descriptor.get(source, propertyName)).collect(Collectors.toList()); } private Stream> getPropertySources() { @@ -76,26 +72,21 @@ class InvalidConfigurationPropertyValueFailureAnalyzer return Stream.empty(); } return this.environment.getPropertySources().stream() - .filter((source) -> !ConfigurationPropertySources - .isAttachedConfigurationPropertySource(source)); + .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); } - private void appendDetails(StringBuilder message, - InvalidConfigurationPropertyValueException cause, + private void appendDetails(StringBuilder message, InvalidConfigurationPropertyValueException cause, List descriptors) { Descriptor mainDescriptor = descriptors.get(0); - message.append("Invalid value '").append(mainDescriptor.getValue()) - .append("' for configuration property '"); + message.append("Invalid value '").append(mainDescriptor.getValue()).append("' for configuration property '"); message.append(cause.getName()).append("'"); mainDescriptor.appendOrigin(message); message.append("."); } - private void appendReason(StringBuilder message, - InvalidConfigurationPropertyValueException cause) { + private void appendReason(StringBuilder message, InvalidConfigurationPropertyValueException cause) { if (StringUtils.hasText(cause.getReason())) { - message.append(String - .format(" Validation failed for the following " + "reason:%n%n")); + message.append(String.format(" Validation failed for the following " + "reason:%n%n")); message.append(cause.getReason()); } else { @@ -103,14 +94,12 @@ class InvalidConfigurationPropertyValueFailureAnalyzer } } - private void appendAdditionalProperties(StringBuilder message, - List descriptors) { + private void appendAdditionalProperties(StringBuilder message, List descriptors) { List others = descriptors.subList(1, descriptors.size()); if (!others.isEmpty()) { - message.append(String.format( - "%n%nAdditionally, this property is also set in the following " - + "property %s:%n%n", - (others.size() > 1) ? "sources" : "source")); + message.append( + String.format("%n%nAdditionally, this property is also set in the following " + "property %s:%n%n", + (others.size() > 1) ? "sources" : "source")); for (Descriptor other : others) { message.append("\t- In '").append(other.getPropertySource()).append("'"); message.append(" with the value '").append(other.getValue()).append("'"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java index e1d6d62f24c..739ffb5b344 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java @@ -50,8 +50,8 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer findCandidates(String className) { try { return Collections.list(NoSuchMethodFailureAnalyzer.class.getClassLoader() - .getResources(ClassUtils.convertClassNameToResourcePath(className) - + ".class")); + .getResources(ClassUtils.convertClassNameToResourcePath(className) + ".class")); } catch (Throwable ex) { return null; @@ -81,16 +80,14 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer candidates, URL actual) { + private String getDescription(NoSuchMethodError cause, String className, List candidates, URL actual) { StringWriter description = new StringWriter(); PrintWriter writer = new PrintWriter(description); writer.println("An attempt was made to call a method that does not" @@ -104,8 +101,7 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer +class NoUniqueBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyzer implements BeanFactoryAware { private ConfigurableBeanFactory beanFactory; @@ -46,8 +45,8 @@ class NoUniqueBeanDefinitionFailureAnalyzer } @Override - protected FailureAnalysis analyze(Throwable rootFailure, - NoUniqueBeanDefinitionException cause, String description) { + protected FailureAnalysis analyze(Throwable rootFailure, NoUniqueBeanDefinitionException cause, + String description) { if (description == null) { return null; } @@ -56,8 +55,7 @@ class NoUniqueBeanDefinitionFailureAnalyzer return null; } StringBuilder message = new StringBuilder(); - message.append(String.format("%s required a single bean, but %d were found:%n", - description, beanNames.length)); + message.append(String.format("%s required a single bean, but %d were found:%n", description, beanNames.length)); for (String beanName : beanNames) { buildMessage(message, beanName); } @@ -70,30 +68,26 @@ class NoUniqueBeanDefinitionFailureAnalyzer private void buildMessage(StringBuilder message, String beanName) { try { - BeanDefinition definition = this.beanFactory - .getMergedBeanDefinition(beanName); + BeanDefinition definition = this.beanFactory.getMergedBeanDefinition(beanName); message.append(getDefinitionDescription(beanName, definition)); } catch (NoSuchBeanDefinitionException ex) { - message.append(String - .format("\t- %s: a programmatically registered singleton", beanName)); + message.append(String.format("\t- %s: a programmatically registered singleton", beanName)); } } private String getDefinitionDescription(String beanName, BeanDefinition definition) { if (StringUtils.hasText(definition.getFactoryMethodName())) { - return String.format("\t- %s: defined by method '%s' in %s%n", beanName, - definition.getFactoryMethodName(), + return String.format("\t- %s: defined by method '%s' in %s%n", beanName, definition.getFactoryMethodName(), definition.getResourceDescription()); } - return String.format("\t- %s: defined in %s%n", beanName, - definition.getResourceDescription()); + return String.format("\t- %s: defined in %s%n", beanName, definition.getResourceDescription()); } private String[] extractBeanNames(NoUniqueBeanDefinitionException cause) { if (cause.getMessage().contains("but found")) { - return StringUtils.commaDelimitedListToStringArray(cause.getMessage() - .substring(cause.getMessage().lastIndexOf(':') + 1).trim()); + return StringUtils.commaDelimitedListToStringArray( + cause.getMessage().substring(cause.getMessage().lastIndexOf(':') + 1).trim()); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java index a8720cc7b2c..1d68e98fb16 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,11 +30,8 @@ class PortInUseFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - UnboundConfigurationPropertiesException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, UnboundConfigurationPropertiesException cause) { BindException exception = findCause(rootFailure, BindException.class); return analyzeUnboundConfigurationPropertiesException(exception, cause); } - private FailureAnalysis analyzeUnboundConfigurationPropertiesException( - BindException cause, UnboundConfigurationPropertiesException exception) { + private FailureAnalysis analyzeUnboundConfigurationPropertiesException(BindException cause, + UnboundConfigurationPropertiesException exception) { StringBuilder description = new StringBuilder( String.format("Binding to target %s failed:%n", cause.getTarget())); for (ConfigurationProperty property : exception.getUnboundProperties()) { @@ -49,8 +48,7 @@ class UnboundConfigurationPropertyFailureAnalyzer return getFailureAnalysis(description, cause); } - private void buildDescription(StringBuilder description, - ConfigurationProperty property) { + private void buildDescription(StringBuilder description, ConfigurationProperty property) { if (property != null) { description.append(String.format("%n Property: %s", property.getName())); description.append(String.format("%n Value: %s", property.getValue())); @@ -59,8 +57,7 @@ class UnboundConfigurationPropertyFailureAnalyzer } private FailureAnalysis getFailureAnalysis(Object description, BindException cause) { - return new FailureAnalysis(description.toString(), - "Update your application's configuration", cause); + return new FailureAnalysis(description.toString(), "Update your application's configuration", cause); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java index f76c1c20e2d..f56a4b9118e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import org.springframework.boot.diagnostics.FailureAnalyzer; * * @author Andy Wilkinson */ -class ValidationExceptionFailureAnalyzer - extends AbstractFailureAnalyzer { +class ValidationExceptionFailureAnalyzer extends AbstractFailureAnalyzer { private static final String MISSING_IMPLEMENTATION_MESSAGE = "Unable to create a " + "Configuration, because no Bean Validation provider could be found"; @@ -38,11 +37,8 @@ class ValidationExceptionFailureAnalyzer protected FailureAnalysis analyze(Throwable rootFailure, ValidationException cause) { if (cause.getMessage().startsWith(MISSING_IMPLEMENTATION_MESSAGE)) { return new FailureAnalysis( - "The Bean Validation API is on the classpath but no implementation" - + " could be found", - "Add an implementation, such as Hibernate Validator, to the" - + " classpath", - cause); + "The Bean Validation API is on the classpath but no implementation" + " could be found", + "Add an implementation, such as Hibernate Validator, to the" + " classpath", cause); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java index bcc0fe87f36..7d25ef15c07 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,6 @@ public interface EnvironmentPostProcessor { * @param environment the environment to post-process * @param application the application to which the environment belongs */ - void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application); + void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java index d7b130e293e..b4c762c3271 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.core.env.PropertySource; * @since 2.0.0 * @see OriginTrackedValue */ -public final class OriginTrackedMapPropertySource extends MapPropertySource - implements OriginLookup { +public final class OriginTrackedMapPropertySource extends MapPropertySource implements OriginLookup { private final boolean immutable; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java index 1a048a2774b..70c668b62b4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,15 +97,13 @@ class OriginTrackedPropertiesLoader { } } - private void put(Map result, String key, - OriginTrackedValue value) { + private void put(Map result, String key, OriginTrackedValue value) { if (!key.isEmpty()) { result.put(key, value); } } - private String loadKey(StringBuilder buffer, CharacterReader reader) - throws IOException { + private String loadKey(StringBuilder buffer, CharacterReader reader) throws IOException { buffer.setLength(0); boolean previousWhitespace = false; while (!reader.isEndOfLine()) { @@ -123,8 +121,8 @@ class OriginTrackedPropertiesLoader { return buffer.toString(); } - private OriginTrackedValue loadValue(StringBuilder buffer, CharacterReader reader, - boolean splitLists) throws IOException { + private OriginTrackedValue loadValue(StringBuilder buffer, CharacterReader reader, boolean splitLists) + throws IOException { buffer.setLength(0); while (reader.isWhiteSpace() && !reader.isEndOfLine()) { reader.read(); @@ -155,8 +153,8 @@ class OriginTrackedPropertiesLoader { private int character; CharacterReader(Resource resource) throws IOException { - this.reader = new LineNumberReader(new InputStreamReader( - resource.getInputStream(), StandardCharsets.ISO_8859_1)); + this.reader = new LineNumberReader( + new InputStreamReader(resource.getInputStream(), StandardCharsets.ISO_8859_1)); } @Override @@ -240,8 +238,7 @@ class OriginTrackedPropertiesLoader { } public boolean isWhiteSpace() { - return !this.escaped && (this.character == ' ' || this.character == '\t' - || this.character == '\f'); + return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f'); } public boolean isEndOfFile() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java index 1f3fc597e3d..7b2d260d589 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,8 +95,7 @@ class OriginTrackedYamlLoader extends YamlProcessor { } private void replaceMappingNodeKeys(MappingNode node) { - node.setValue(node.getValue().stream().map(KeyScalarNode::get) - .collect(Collectors.toList())); + node.setValue(node.getValue().stream().map(KeyScalarNode::get).collect(Collectors.toList())); } private Object constructTrackedObject(Node node, Object value) { @@ -111,8 +110,7 @@ class OriginTrackedYamlLoader extends YamlProcessor { private Origin getOrigin(Node node) { Mark mark = node.getStartMark(); Location location = new Location(mark.getLine(), mark.getColumn()); - return new TextResourceOrigin(OriginTrackedYamlLoader.this.resource, - location); + return new TextResourceOrigin(OriginTrackedYamlLoader.this.resource, location); } } @@ -123,8 +121,7 @@ class OriginTrackedYamlLoader extends YamlProcessor { private static class KeyScalarNode extends ScalarNode { KeyScalarNode(ScalarNode node) { - super(node.getTag(), node.getValue(), node.getStartMark(), node.getEndMark(), - node.getScalarStyle()); + super(node.getTag(), node.getValue(), node.getStartMark(), node.getEndMark(), node.getScalarStyle()); } public static NodeTuple get(NodeTuple nodeTuple) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java index 00bf634e75c..08140310014 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,13 @@ public class PropertiesPropertySourceLoader implements PropertySourceLoader { } @Override - public List> load(String name, Resource resource) - throws IOException { + public List> load(String name, Resource resource) throws IOException { Map properties = loadProperties(resource); if (properties.isEmpty()) { return Collections.emptyList(); } - return Collections.singletonList(new OriginTrackedMapPropertySource(name, - Collections.unmodifiableMap(properties), true)); + return Collections + .singletonList(new OriginTrackedMapPropertySource(name, Collections.unmodifiableMap(properties), true)); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/RandomValuePropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/RandomValuePropertySource.java index 994c397d039..5ef03c57870 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/RandomValuePropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/RandomValuePropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -137,8 +137,7 @@ public class RandomValuePropertySource extends PropertySource { } public static void addToEnvironment(ConfigurableEnvironment environment) { - environment.getPropertySources().addAfter( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME)); logger.trace("RandomValuePropertySource add to Environment"); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java index 0c5a24804a0..19f5bb44d73 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ import org.springframework.web.context.support.StandardServletEnvironment; * @author Artsiom Yudovin * @since 1.3.0 */ -public class SpringApplicationJsonEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { +public class SpringApplicationJsonEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { /** * Name of the {@code spring.application.json} property. @@ -83,20 +82,17 @@ public class SpringApplicationJsonEnvironmentPostProcessor } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources propertySources = environment.getPropertySources(); - propertySources.stream().map(JsonPropertyValue::get).filter(Objects::nonNull) - .findFirst().ifPresent((v) -> processJson(environment, v)); + propertySources.stream().map(JsonPropertyValue::get).filter(Objects::nonNull).findFirst() + .ifPresent((v) -> processJson(environment, v)); } - private void processJson(ConfigurableEnvironment environment, - JsonPropertyValue propertyValue) { + private void processJson(ConfigurableEnvironment environment, JsonPropertyValue propertyValue) { JsonParser parser = JsonParserFactory.getJsonParser(); Map map = parser.parseMap(propertyValue.getJson()); if (!map.isEmpty()) { - addJsonPropertySource(environment, - new JsonPropertySource(propertyValue, flatten(map))); + addJsonPropertySource(environment, new JsonPropertySource(propertyValue, flatten(map))); } } @@ -111,8 +107,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor return result; } - private void flatten(String prefix, Map result, - Map map) { + private void flatten(String prefix, Map result, Map map) { String namePrefix = (prefix != null) ? prefix + "." : ""; map.forEach((key, value) -> extract(namePrefix + key, result, value)); } @@ -134,8 +129,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor } } - private void addJsonPropertySource(ConfigurableEnvironment environment, - PropertySource source) { + private void addJsonPropertySource(ConfigurableEnvironment environment, PropertySource source) { MutablePropertySources sources = environment.getPropertySources(); String name = findPropertySource(sources); if (sources.contains(name)) { @@ -147,16 +141,15 @@ public class SpringApplicationJsonEnvironmentPostProcessor } private String findPropertySource(MutablePropertySources sources) { - if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) && sources - .contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) { + if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) + && sources.contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) { return StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME; } return StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME; } - private static class JsonPropertySource extends MapPropertySource - implements OriginLookup { + private static class JsonPropertySource extends MapPropertySource implements OriginLookup { private final JsonPropertyValue propertyValue; @@ -183,8 +176,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor private final String json; - JsonPropertyValue(PropertySource propertySource, String propertyName, - String json) { + JsonPropertyValue(PropertySource propertySource, String propertyName, String json) { this.propertySource = propertySource; this.propertyName = propertyName; this.json = json; @@ -201,10 +193,8 @@ public class SpringApplicationJsonEnvironmentPostProcessor public static JsonPropertyValue get(PropertySource propertySource) { for (String candidate : CANDIDATES) { Object value = propertySource.getProperty(candidate); - if (value != null && value instanceof String - && StringUtils.hasLength((String) value)) { - return new JsonPropertyValue(propertySource, candidate, - (String) value); + if (value != null && value instanceof String && StringUtils.hasLength((String) value)) { + return new JsonPropertyValue(propertySource, candidate, (String) value); } } return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessor.java index ee06418634a..f23d6c8fcc3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,35 +37,30 @@ import org.springframework.core.env.SystemEnvironmentPropertySource; * @author Madhura Bhave * @since 2.0.0 */ -public class SystemEnvironmentPropertySourceEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { +public class SystemEnvironmentPropertySourceEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { /** * The default order for the processor. */ - public static final int DEFAULT_ORDER = SpringApplicationJsonEnvironmentPostProcessor.DEFAULT_ORDER - - 1; + public static final int DEFAULT_ORDER = SpringApplicationJsonEnvironmentPostProcessor.DEFAULT_ORDER - 1; private int order = DEFAULT_ORDER; @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { String sourceName = StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME; - PropertySource propertySource = environment.getPropertySources() - .get(sourceName); + PropertySource propertySource = environment.getPropertySources().get(sourceName); if (propertySource != null) { replacePropertySource(environment, sourceName, propertySource); } } @SuppressWarnings("unchecked") - private void replacePropertySource(ConfigurableEnvironment environment, - String sourceName, PropertySource propertySource) { - Map originalSource = (Map) propertySource - .getSource(); - SystemEnvironmentPropertySource source = new OriginAwareSystemEnvironmentPropertySource( - sourceName, originalSource); + private void replacePropertySource(ConfigurableEnvironment environment, String sourceName, + PropertySource propertySource) { + Map originalSource = (Map) propertySource.getSource(); + SystemEnvironmentPropertySource source = new OriginAwareSystemEnvironmentPropertySource(sourceName, + originalSource); environment.getPropertySources().replace(sourceName, source); } @@ -81,11 +76,10 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessor /** * {@link SystemEnvironmentPropertySource} that also tracks {@link Origin}. */ - protected static class OriginAwareSystemEnvironmentPropertySource - extends SystemEnvironmentPropertySource implements OriginLookup { + protected static class OriginAwareSystemEnvironmentPropertySource extends SystemEnvironmentPropertySource + implements OriginLookup { - OriginAwareSystemEnvironmentPropertySource(String name, - Map source) { + OriginAwareSystemEnvironmentPropertySource(String name, Map source) { super(name, source); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java index ecd54423951..4d3c7690120 100755 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,11 +41,10 @@ public class YamlPropertySourceLoader implements PropertySourceLoader { } @Override - public List> load(String name, Resource resource) - throws IOException { + public List> load(String name, Resource resource) throws IOException { if (!ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) { - throw new IllegalStateException("Attempted to load " + name - + " but snakeyaml was not found on the classpath"); + throw new IllegalStateException( + "Attempted to load " + name + " but snakeyaml was not found on the classpath"); } List> loaded = new OriginTrackedYamlLoader(resource).load(); if (loaded.isEmpty()) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java index 2ac4c4491e3..76ec3485aaf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,8 +90,8 @@ public class BuildProperties extends InfoProperties { String value = properties.getProperty(key); if (value != null) { try { - String updatedValue = String.valueOf(DateTimeFormatter.ISO_INSTANT - .parse(value, Instant::from).toEpochMilli()); + String updatedValue = String + .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); properties.setProperty(key, updatedValue); } catch (DateTimeException ex) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java index 56b31f2447b..17cb7969112 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,8 +83,7 @@ public class InfoProperties implements Iterable { * @return a {@link PropertySource} */ public PropertySource toPropertySource() { - return new PropertiesPropertySource(getClass().getSimpleName(), - copy(this.entries)); + return new PropertiesPropertySource(getClass().getSimpleName(), copy(this.entries)); } private Properties copy(Properties properties) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java index 750327900f3..d6ab7043801 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java @@ -68,22 +68,19 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar addJsonBeans((ListableBeanFactory) beanFactory); } beanFactory = (beanFactory instanceof HierarchicalBeanFactory) - ? ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory() - : null; + ? ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory() : null; } } private void addJsonBeans(ListableBeanFactory beanFactory) { - Map beans = beanFactory - .getBeansWithAnnotation(JsonComponent.class); + Map beans = beanFactory.getBeansWithAnnotation(JsonComponent.class); for (Object bean : beans.values()) { addJsonBean(bean); } } private void addJsonBean(Object bean) { - MergedAnnotation annotation = MergedAnnotations - .from(bean.getClass(), SearchStrategy.EXHAUSTIVE) + MergedAnnotation annotation = MergedAnnotations.from(bean.getClass(), SearchStrategy.EXHAUSTIVE) .get(JsonComponent.class); Class[] types = annotation.getClassArray("type"); Scope scope = annotation.getEnum("scope", JsonComponent.Scope.class); @@ -109,27 +106,23 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar } private boolean isSuitableInnerClass(Class innerClass) { - return !Modifier.isAbstract(innerClass.getModifiers()) - && (JsonSerializer.class.isAssignableFrom(innerClass) - || JsonDeserializer.class.isAssignableFrom(innerClass) - || KeyDeserializer.class.isAssignableFrom(innerClass)); + return !Modifier.isAbstract(innerClass.getModifiers()) && (JsonSerializer.class.isAssignableFrom(innerClass) + || JsonDeserializer.class.isAssignableFrom(innerClass) + || KeyDeserializer.class.isAssignableFrom(innerClass)); } @SuppressWarnings("unchecked") - private void addJsonSerializerBean(JsonSerializer serializer, - JsonComponent.Scope scope, Class[] types) { - Class baseType = (Class) ResolvableType - .forClass(JsonSerializer.class, serializer.getClass()).resolveGeneric(); + private void addJsonSerializerBean(JsonSerializer serializer, JsonComponent.Scope scope, Class[] types) { + Class baseType = (Class) ResolvableType.forClass(JsonSerializer.class, serializer.getClass()) + .resolveGeneric(); addBeanToModule(serializer, baseType, types, (scope == Scope.VALUES) ? this::addSerializer : this::addKeySerializer); } @SuppressWarnings("unchecked") - private void addJsonDeserializerBean(JsonDeserializer deserializer, - Class[] types) { - Class baseType = (Class) ResolvableType - .forClass(JsonDeserializer.class, deserializer.getClass()) + private void addJsonDeserializerBean(JsonDeserializer deserializer, Class[] types) { + Class baseType = (Class) ResolvableType.forClass(JsonDeserializer.class, deserializer.getClass()) .resolveGeneric(); addBeanToModule(deserializer, baseType, types, this::addDeserializer); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java index d030503e7c6..9b361ad774c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,12 +40,10 @@ import org.springframework.util.Assert; * @since 1.4.0 * @see JsonObjectSerializer */ -public abstract class JsonObjectDeserializer - extends com.fasterxml.jackson.databind.JsonDeserializer { +public abstract class JsonObjectDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer { @Override - public final T deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException { + public final T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { try { ObjectCodec codec = jp.getCodec(); JsonNode tree = codec.readTree(jp); @@ -71,9 +69,8 @@ public abstract class JsonObjectDeserializer * @throws IOException on error * @see #deserialize(JsonParser, DeserializationContext) */ - protected abstract T deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException; + protected abstract T deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) throws IOException; /** * Helper method to extract a value from the given {@code jsonNode} or return @@ -130,8 +127,7 @@ public abstract class JsonObjectDeserializer protected final JsonNode getRequiredNode(JsonNode tree, String fieldName) { Assert.notNull(tree, "Tree must not be null"); JsonNode node = tree.get(fieldName); - Assert.state(node != null && !(node instanceof NullNode), - () -> "Missing JSON field '" + fieldName + "'"); + Assert.state(node != null && !(node instanceof NullNode), () -> "Missing JSON field '" + fieldName + "'"); return node; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java index 065f4a98c61..b4ccf3d8b82 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import com.fasterxml.jackson.databind.SerializerProvider; public abstract class JsonObjectSerializer extends JsonSerializer { @Override - public final void serialize(T value, JsonGenerator jgen, SerializerProvider provider) - throws IOException { + public final void serialize(T value, JsonGenerator jgen, SerializerProvider provider) throws IOException { try { jgen.writeStartObject(); serializeObject(value, jgen, provider); @@ -56,7 +55,7 @@ public abstract class JsonObjectSerializer extends JsonSerializer { * @param provider the serializer provider * @throws IOException on error */ - protected abstract void serializeObject(T value, JsonGenerator jgen, - SerializerProvider provider) throws IOException; + protected abstract void serializeObject(T value, JsonGenerator jgen, SerializerProvider provider) + throws IOException; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/AbstractDataSourceInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/AbstractDataSourceInitializer.java index be04439d0fa..49eda08e9b2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/AbstractDataSourceInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/AbstractDataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public abstract class AbstractDataSourceInitializer { private final ResourceLoader resourceLoader; - protected AbstractDataSourceInitializer(DataSource dataSource, - ResourceLoader resourceLoader) { + protected AbstractDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) { Assert.notNull(dataSource, "DataSource must not be null"); Assert.notNull(resourceLoader, "ResourceLoader must not be null"); this.dataSource = dataSource; @@ -90,9 +89,8 @@ public abstract class AbstractDataSourceInitializer { protected String getDatabaseName() { try { - String productName = JdbcUtils.commonDatabaseName(JdbcUtils - .extractDatabaseMetaData(this.dataSource, "getDatabaseProductName") - .toString()); + String productName = JdbcUtils.commonDatabaseName( + JdbcUtils.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName").toString()); DatabaseDriver databaseDriver = DatabaseDriver.fromProductName(productName); if (databaseDriver == DatabaseDriver.UNKNOWN) { throw new IllegalStateException("Unable to detect database type"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java index 2a883f28ac6..f21da930eff 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,10 +46,8 @@ import org.springframework.util.ClassUtils; */ public final class DataSourceBuilder { - private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] { - "com.zaxxer.hikari.HikariDataSource", - "org.apache.tomcat.jdbc.pool.DataSource", - "org.apache.commons.dbcp2.BasicDataSource" }; + private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] { "com.zaxxer.hikari.HikariDataSource", + "org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource" }; private Class type; @@ -79,8 +77,7 @@ public final class DataSourceBuilder { } private void maybeGetDriverClassName() { - if (!this.properties.containsKey("driverClassName") - && this.properties.containsKey("url")) { + if (!this.properties.containsKey("driverClassName") && this.properties.containsKey("url")) { String url = this.properties.get("url"); String driverClass = DatabaseDriver.fromJdbcUrl(url).getDriverClassName(); this.properties.put("driverClassName", driverClass); @@ -88,8 +85,7 @@ public final class DataSourceBuilder { } private void bind(DataSource result) { - ConfigurationPropertySource source = new MapConfigurationPropertySource( - this.properties); + ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties); ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("url", "jdbc-url"); aliases.addAliases("username", "user"); @@ -127,8 +123,7 @@ public final class DataSourceBuilder { public static Class findType(ClassLoader classLoader) { for (String name : DATA_SOURCE_TYPE_NAMES) { try { - return (Class) ClassUtils.forName(name, - classLoader); + return (Class) ClassUtils.forName(name, classLoader); } catch (Exception ex) { // Swallow and continue @@ -138,8 +133,7 @@ public final class DataSourceBuilder { } private Class getType() { - Class type = (this.type != null) ? this.type - : findType(this.classLoader); + Class type = (this.type != null) ? this.type : findType(this.classLoader); if (type != null) { return type; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java index 06428110cdb..7ddd99b2a4e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java @@ -36,8 +36,7 @@ import org.springframework.util.ClassUtils; public final class DataSourceUnwrapper { private static final boolean DELEGATING_DATA_SOURCE_PRESENT = ClassUtils.isPresent( - "org.springframework.jdbc.datasource.DelegatingDataSource", - DataSourceUnwrapper.class.getClassLoader()); + "org.springframework.jdbc.datasource.DelegatingDataSource", DataSourceUnwrapper.class.getClassLoader()); private DataSourceUnwrapper() { } @@ -59,8 +58,7 @@ public final class DataSourceUnwrapper { return unwrapped; } if (DELEGATING_DATA_SOURCE_PRESENT) { - DataSource targetDataSource = DelegatingDataSourceUnwrapper - .getTargetDataSource(dataSource); + DataSource targetDataSource = DelegatingDataSourceUnwrapper.getTargetDataSource(dataSource); if (targetDataSource != null) { return unwrap(targetDataSource, target); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java index 787a78a0d1d..3c40b52bf84 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java @@ -43,8 +43,7 @@ public enum DatabaseDriver { /** * Apache Derby. */ - DERBY("Apache Derby", "org.apache.derby.jdbc.EmbeddedDriver", - "org.apache.derby.jdbc.EmbeddedXADataSource", + DERBY("Apache Derby", "org.apache.derby.jdbc.EmbeddedDriver", "org.apache.derby.jdbc.EmbeddedXADataSource", "SELECT 1 FROM SYSIBM.SYSDUMMY1"), /** @@ -55,8 +54,7 @@ public enum DatabaseDriver { /** * HyperSQL DataBase. */ - HSQLDB("HSQL Database Engine", "org.hsqldb.jdbc.JDBCDriver", - "org.hsqldb.jdbc.pool.JDBCXADataSource", + HSQLDB("HSQL Database Engine", "org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource", "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SYSTEM_USERS"), /** @@ -67,14 +65,12 @@ public enum DatabaseDriver { /** * MySQL. */ - MYSQL("MySQL", "com.mysql.cj.jdbc.Driver", "com.mysql.cj.jdbc.MysqlXADataSource", - "/* ping */ SELECT 1"), + MYSQL("MySQL", "com.mysql.cj.jdbc.Driver", "com.mysql.cj.jdbc.MysqlXADataSource", "/* ping */ SELECT 1"), /** * Maria DB. */ - MARIADB("MySQL", "org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource", - "SELECT 1") { + MARIADB("MySQL", "org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource", "SELECT 1") { @Override public String getId() { @@ -90,14 +86,13 @@ public enum DatabaseDriver { /** * Oracle. */ - ORACLE("Oracle", "oracle.jdbc.OracleDriver", - "oracle.jdbc.xa.client.OracleXADataSource", "SELECT 'Hello' from DUAL"), + ORACLE("Oracle", "oracle.jdbc.OracleDriver", "oracle.jdbc.xa.client.OracleXADataSource", + "SELECT 'Hello' from DUAL"), /** * Postgres. */ - POSTGRESQL("PostgreSQL", "org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", - "SELECT 1"), + POSTGRESQL("PostgreSQL", "org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", "SELECT 1"), /** * Amazon Redshift. @@ -109,8 +104,7 @@ public enum DatabaseDriver { * HANA - SAP HANA Database - HDB. * @since 2.1.0 */ - HANA("HDB", "com.sap.db.jdbc.Driver", "com.sap.db.jdbcext.XADataSourceSAP", - "SELECT 1 FROM SYS.DUMMY") { + HANA("HDB", "com.sap.db.jdbc.Driver", "com.sap.db.jdbcext.XADataSourceSAP", "SELECT 1 FROM SYS.DUMMY") { @Override protected Collection getUrlPrefixes() { return Collections.singleton("sap"); @@ -131,8 +125,7 @@ public enum DatabaseDriver { @Override protected boolean matchProductName(String productName) { - return super.matchProductName(productName) - || "SQL SERVER".equalsIgnoreCase(productName); + return super.matchProductName(productName) || "SQL SERVER".equalsIgnoreCase(productName); } @@ -141,8 +134,8 @@ public enum DatabaseDriver { /** * Firebird. */ - FIREBIRD("Firebird", "org.firebirdsql.jdbc.FBDriver", - "org.firebirdsql.ds.FBXADataSource", "SELECT 1 FROM RDB$DATABASE") { + FIREBIRD("Firebird", "org.firebirdsql.jdbc.FBDriver", "org.firebirdsql.ds.FBXADataSource", + "SELECT 1 FROM RDB$DATABASE") { @Override protected Collection getUrlPrefixes() { @@ -159,13 +152,11 @@ public enum DatabaseDriver { /** * DB2 Server. */ - DB2("DB2", "com.ibm.db2.jcc.DB2Driver", "com.ibm.db2.jcc.DB2XADataSource", - "SELECT 1 FROM SYSIBM.SYSDUMMY1") { + DB2("DB2", "com.ibm.db2.jcc.DB2Driver", "com.ibm.db2.jcc.DB2XADataSource", "SELECT 1 FROM SYSIBM.SYSDUMMY1") { @Override protected boolean matchProductName(String productName) { - return super.matchProductName(productName) - || productName.toLowerCase(Locale.ENGLISH).startsWith("db2/"); + return super.matchProductName(productName) || productName.toLowerCase(Locale.ENGLISH).startsWith("db2/"); } }, @@ -173,8 +164,7 @@ public enum DatabaseDriver { * DB2 AS400 Server. */ DB2_AS400("DB2 UDB for AS/400", "com.ibm.as400.access.AS400JDBCDriver", - "com.ibm.as400.access.AS400JDBCXADataSource", - "SELECT 1 FROM SYSIBM.SYSDUMMY1") { + "com.ibm.as400.access.AS400JDBCXADataSource", "SELECT 1 FROM SYSIBM.SYSDUMMY1") { @Override public String getId() { @@ -188,8 +178,7 @@ public enum DatabaseDriver { @Override protected boolean matchProductName(String productName) { - return super.matchProductName(productName) - || productName.toLowerCase(Locale.ENGLISH).contains("as/400"); + return super.matchProductName(productName) || productName.toLowerCase(Locale.ENGLISH).contains("as/400"); } }, @@ -201,8 +190,7 @@ public enum DatabaseDriver { /** * Informix. */ - INFORMIX("Informix Dynamic Server", "com.informix.jdbc.IfxDriver", null, - "select count(*) from systables") { + INFORMIX("Informix Dynamic Server", "com.informix.jdbc.IfxDriver", null, "select count(*) from systables") { @Override protected Collection getUrlPrefixes() { @@ -223,13 +211,11 @@ public enum DatabaseDriver { this(productName, driverClassName, null); } - DatabaseDriver(String productName, String driverClassName, - String xaDataSourceClassName) { + DatabaseDriver(String productName, String driverClassName, String xaDataSourceClassName) { this(productName, driverClassName, xaDataSourceClassName, null); } - DatabaseDriver(String productName, String driverClassName, - String xaDataSourceClassName, String validationQuery) { + DatabaseDriver(String productName, String driverClassName, String xaDataSourceClassName, String validationQuery) { this.productName = productName; this.driverClassName = driverClassName; this.xaDataSourceClassName = xaDataSourceClassName; @@ -284,8 +270,7 @@ public enum DatabaseDriver { public static DatabaseDriver fromJdbcUrl(String url) { if (StringUtils.hasLength(url)) { Assert.isTrue(url.startsWith("jdbc"), "URL must start with 'jdbc'"); - String urlWithoutPrefix = url.substring("jdbc".length()) - .toLowerCase(Locale.ENGLISH); + String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH); for (DatabaseDriver driver : values()) { for (String urlPrefix : driver.getUrlPrefixes()) { String prefix = ":" + urlPrefix + ":"; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java index 62bcb86e3ce..ae6fd30e9f6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,14 +47,12 @@ public enum EmbeddedDatabaseConnection { /** * H2 Database Connection. */ - H2(EmbeddedDatabaseType.H2, "org.h2.Driver", - "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"), + H2(EmbeddedDatabaseType.H2, "org.h2.Driver", "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"), /** * Derby Database Connection. */ - DERBY(EmbeddedDatabaseType.DERBY, "org.apache.derby.jdbc.EmbeddedDriver", - "jdbc:derby:memory:%s;create=true"), + DERBY(EmbeddedDatabaseType.DERBY, "org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:%s;create=true"), /** * HSQL Database Connection. @@ -67,8 +65,7 @@ public enum EmbeddedDatabaseConnection { private final String url; - EmbeddedDatabaseConnection(EmbeddedDatabaseType type, String driverClass, - String url) { + EmbeddedDatabaseConnection(EmbeddedDatabaseType type, String driverClass, String url) { this.type = type; this.driverClass = driverClass; this.url = url; @@ -107,8 +104,7 @@ public enum EmbeddedDatabaseConnection { * @return true if the driver class is one of the embedded types */ public static boolean isEmbedded(String driverClass) { - return driverClass != null && (driverClass.equals(HSQL.driverClass) - || driverClass.equals(H2.driverClass) + return driverClass != null && (driverClass.equals(HSQL.driverClass) || driverClass.equals(H2.driverClass) || driverClass.equals(DERBY.driverClass)); } @@ -136,8 +132,7 @@ public enum EmbeddedDatabaseConnection { */ public static EmbeddedDatabaseConnection get(ClassLoader classLoader) { for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) { - if (candidate != NONE && ClassUtils.isPresent(candidate.getDriverClassName(), - classLoader)) { + if (candidate != NONE && ClassUtils.isPresent(candidate.getDriverClassName(), classLoader)) { return candidate; } } @@ -150,8 +145,7 @@ public enum EmbeddedDatabaseConnection { private static class IsEmbedded implements ConnectionCallback { @Override - public Boolean doInConnection(Connection connection) - throws SQLException, DataAccessException { + public Boolean doInConnection(Connection connection) throws SQLException, DataAccessException { String productName = connection.getMetaData().getDatabaseProductName(); if (productName == null) { return false; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadata.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadata.java index b27738b9d7e..a47b95dba91 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadata.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import javax.sql.DataSource; * @author Stephane Nicoll * @since 2.0.0 */ -public abstract class AbstractDataSourcePoolMetadata - implements DataSourcePoolMetadata { +public abstract class AbstractDataSourcePoolMetadata implements DataSourcePoolMetadata { private final T dataSource; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java index 37b3e9e89f7..ca1508fc8b9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import org.apache.commons.dbcp2.BasicDataSource; * @author Stephane Nicoll * @since 2.0.0 */ -public class CommonsDbcp2DataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class CommonsDbcp2DataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public CommonsDbcp2DataSourcePoolMetadata(BasicDataSource dataSource) { super(dataSource); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProvider.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProvider.java index 602c1a21ef4..47b360cf426 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProvider.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import javax.sql.DataSource; * @author Stephane Nicoll * @since 2.0.0 */ -public class CompositeDataSourcePoolMetadataProvider - implements DataSourcePoolMetadataProvider { +public class CompositeDataSourcePoolMetadataProvider implements DataSourcePoolMetadataProvider { private final List providers; @@ -40,18 +39,15 @@ public class CompositeDataSourcePoolMetadataProvider * collection of delegates to use. * @param providers the data source pool metadata providers */ - public CompositeDataSourcePoolMetadataProvider( - Collection providers) { - this.providers = (providers != null) - ? Collections.unmodifiableList(new ArrayList<>(providers)) + public CompositeDataSourcePoolMetadataProvider(Collection providers) { + this.providers = (providers != null) ? Collections.unmodifiableList(new ArrayList<>(providers)) : Collections.emptyList(); } @Override public DataSourcePoolMetadata getDataSourcePoolMetadata(DataSource dataSource) { for (DataSourcePoolMetadataProvider provider : this.providers) { - DataSourcePoolMetadata metadata = provider - .getDataSourcePoolMetadata(dataSource); + DataSourcePoolMetadata metadata = provider.getDataSourcePoolMetadata(dataSource); if (metadata != null) { return metadata; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadata.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadata.java index 0de8a2e2eb7..bd9b1f93f3c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadata.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import org.springframework.beans.DirectFieldAccessor; * @author Stephane Nicoll * @since 2.0.0 */ -public class HikariDataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class HikariDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public HikariDataSourcePoolMetadata(HikariDataSource dataSource) { super(dataSource); @@ -47,8 +46,7 @@ public class HikariDataSourcePoolMetadata } private HikariPool getHikariPool() { - return (HikariPool) new DirectFieldAccessor(getDataSource()) - .getPropertyValue("pool"); + return (HikariPool) new DirectFieldAccessor(getDataSource()).getPropertyValue("pool"); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadata.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadata.java index fdbaa656f49..4202315a5cb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadata.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.apache.tomcat.jdbc.pool.DataSource; * @author Stephane Nicoll * @since 2.0.0 */ -public class TomcatDataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class TomcatDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public TomcatDataSourcePoolMetadata(DataSource dataSource) { super(dataSource); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jms/XAConnectionFactoryWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jms/XAConnectionFactoryWrapper.java index 8339034f5e8..bfcd4019318 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jms/XAConnectionFactoryWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jms/XAConnectionFactoryWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,6 @@ public interface XAConnectionFactoryWrapper { * @return the wrapped connection factory * @throws Exception if the connection factory cannot be wrapped */ - ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) - throws Exception; + ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) throws Exception; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/AbstractJsonParser.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/AbstractJsonParser.java index df062615b6b..3f280059e84 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/AbstractJsonParser.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/AbstractJsonParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,18 +32,15 @@ import org.springframework.util.ReflectionUtils; */ public abstract class AbstractJsonParser implements JsonParser { - protected final Map parseMap(String json, - Function> parser) { + protected final Map parseMap(String json, Function> parser) { return trimParse(json, "{", parser); } - protected final List parseList(String json, - Function> parser) { + protected final List parseList(String json, Function> parser) { return trimParse(json, "[", parser); } - protected final T trimParse(String json, String prefix, - Function parser) { + protected final T trimParse(String json, String prefix, Function parser) { String trimmed = (json != null) ? json.trim() : ""; if (trimmed.startsWith(prefix)) { return parser.apply(trimmed); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/GsonJsonParser.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/GsonJsonParser.java index d0f55903441..9a20ede18f2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/GsonJsonParser.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/GsonJsonParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,14 +41,12 @@ public class GsonJsonParser extends AbstractJsonParser { @Override public Map parseMap(String json) { - return parseMap(json, - (trimmed) -> this.gson.fromJson(trimmed, MAP_TYPE.getType())); + return parseMap(json, (trimmed) -> this.gson.fromJson(trimmed, MAP_TYPE.getType())); } @Override public List parseList(String json) { - return parseList(json, - (trimmed) -> this.gson.fromJson(trimmed, LIST_TYPE.getType())); + return parseList(json, (trimmed) -> this.gson.fromJson(trimmed, LIST_TYPE.getType())); } private static final class MapTypeToken extends TypeToken> { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java index 1e07443be3b..3f1221af20e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,14 +52,12 @@ public class JacksonJsonParser extends AbstractJsonParser { @Override public Map parseMap(String json) { - return tryParse(() -> getObjectMapper().readValue(json, MAP_TYPE), - Exception.class); + return tryParse(() -> getObjectMapper().readValue(json, MAP_TYPE), Exception.class); } @Override public List parseList(String json) { - return tryParse(() -> getObjectMapper().readValue(json, LIST_TYPE), - Exception.class); + return tryParse(() -> getObjectMapper().readValue(json, LIST_TYPE), Exception.class); } private ObjectMapper getObjectMapper() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java index eff4c23172f..829f80687f0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.util.StringUtils; */ @SuppressWarnings("serial") @ConfigurationProperties(prefix = "spring.jta.atomikos.connectionfactory") -public class AtomikosConnectionFactoryBean - extends com.atomikos.jms.AtomikosConnectionFactoryBean +public class AtomikosConnectionFactoryBean extends com.atomikos.jms.AtomikosConnectionFactoryBean implements BeanNameAware, InitializingBean, DisposableBean { private String beanName; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java index 80098def442..996b50c1ba6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,26 +40,23 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @since 1.2.0 */ -public class AtomikosDependsOnBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public class AtomikosDependsOnBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private static final String[] NO_BEANS = {}; private int order = Ordered.LOWEST_PRECEDENCE; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] transactionManagers = beanFactory - .getBeanNamesForType(UserTransactionManager.class, true, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] transactionManagers = beanFactory.getBeanNamesForType(UserTransactionManager.class, true, false); for (String transactionManager : transactionManagers) { addTransactionManagerDependencies(beanFactory, transactionManager); } addMessageDrivenContainerDependencies(beanFactory, transactionManagers); } - private void addTransactionManagerDependencies( - ConfigurableListableBeanFactory beanFactory, String transactionManager) { + private void addTransactionManagerDependencies(ConfigurableListableBeanFactory beanFactory, + String transactionManager) { BeanDefinition bean = beanFactory.getBeanDefinition(transactionManager); Set dependsOn = new LinkedHashSet<>(asList(bean.getDependsOn())); int initialSize = dependsOn.size(); @@ -70,8 +67,8 @@ public class AtomikosDependsOnBeanFactoryPostProcessor } } - private void addMessageDrivenContainerDependencies( - ConfigurableListableBeanFactory beanFactory, String[] transactionManagers) { + private void addMessageDrivenContainerDependencies(ConfigurableListableBeanFactory beanFactory, + String[] transactionManagers) { String[] messageDrivenContainers = getBeanNamesForType(beanFactory, "com.atomikos.jms.extra.MessageDrivenContainer"); for (String messageDrivenContainer : messageDrivenContainers) { @@ -82,13 +79,11 @@ public class AtomikosDependsOnBeanFactoryPostProcessor } } - private void addDependencies(ConfigurableListableBeanFactory beanFactory, String type, - Set dependsOn) { + private void addDependencies(ConfigurableListableBeanFactory beanFactory, String type, Set dependsOn) { dependsOn.addAll(asList(getBeanNamesForType(beanFactory, type))); } - private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, - String type) { + private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, String type) { try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosProperties.java index ded4060c27b..82189beba53 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -335,15 +335,13 @@ public class AtomikosProperties { set(properties, "serial_jta_transactions", isSerialJtaTransactions()); set(properties, "allow_subtransactions", isAllowSubTransactions()); set(properties, "force_shutdown_on_vm_exit", isForceShutdownOnVmExit()); - set(properties, "default_max_wait_time_on_shutdown", - getDefaultMaxWaitTimeOnShutdown()); + set(properties, "default_max_wait_time_on_shutdown", getDefaultMaxWaitTimeOnShutdown()); set(properties, "log_base_name", getLogBaseName()); set(properties, "log_base_dir", getLogBaseDir()); set(properties, "checkpoint_interval", getCheckpointInterval()); set(properties, "threaded_2pc", isThreadedTwoPhaseCommit()); Recovery recovery = getRecovery(); - set(properties, "forget_orphaned_log_entries_delay", - recovery.getForgetOrphanedLogEntriesDelay()); + set(properties, "forget_orphaned_log_entries_delay", recovery.getForgetOrphanedLogEntriesDelay()); set(properties, "recovery_delay", recovery.getDelay()); set(properties, "oltp_max_retries", recovery.getMaxRetries()); set(properties, "oltp_retry_interval", recovery.getRetryInterval()); @@ -394,8 +392,7 @@ public class AtomikosProperties { return this.forgetOrphanedLogEntriesDelay; } - public void setForgetOrphanedLogEntriesDelay( - Duration forgetOrphanedLogEntriesDelay) { + public void setForgetOrphanedLogEntriesDelay(Duration forgetOrphanedLogEntriesDelay) { this.forgetOrphanedLogEntriesDelay = forgetOrphanedLogEntriesDelay; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java index dc48d4018fc..d0307e675c4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.boot.jms.XAConnectionFactoryWrapper; public class AtomikosXAConnectionFactoryWrapper implements XAConnectionFactoryWrapper { @Override - public ConnectionFactory wrapConnectionFactory( - XAConnectionFactory connectionFactory) { + public ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) { AtomikosConnectionFactoryBean bean = new AtomikosConnectionFactoryBean(); bean.setXaConnectionFactory(connectionFactory); return bean; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java index 14c8d7c10ba..3c5c5e3b13b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.boot.jdbc.XADataSourceWrapper; public class AtomikosXADataSourceWrapper implements XADataSourceWrapper { @Override - public AtomikosDataSourceBean wrapDataSource(XADataSource dataSource) - throws Exception { + public AtomikosDataSourceBean wrapDataSource(XADataSource dataSource) throws Exception { AtomikosDataSourceBean bean = new AtomikosDataSourceBean(); bean.setXaDataSource(dataSource); return bean; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java index e7e335728ee..85919850861 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,37 +33,31 @@ import org.springframework.core.Ordered; * @author Phillip Webb * @since 1.2.0 */ -public class BitronixDependentBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public class BitronixDependentBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private static final String[] NO_BEANS = {}; private int order = Ordered.LOWEST_PRECEDENCE; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] transactionManagers = beanFactory - .getBeanNamesForType(TransactionManager.class, true, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] transactionManagers = beanFactory.getBeanNamesForType(TransactionManager.class, true, false); for (String transactionManager : transactionManagers) { addTransactionManagerDependencies(beanFactory, transactionManager); } } - private void addTransactionManagerDependencies( - ConfigurableListableBeanFactory beanFactory, String transactionManager) { - for (String dependentBeanName : getBeanNamesForType(beanFactory, - "javax.jms.ConnectionFactory")) { + private void addTransactionManagerDependencies(ConfigurableListableBeanFactory beanFactory, + String transactionManager) { + for (String dependentBeanName : getBeanNamesForType(beanFactory, "javax.jms.ConnectionFactory")) { beanFactory.registerDependentBean(transactionManager, dependentBeanName); } - for (String dependentBeanName : getBeanNamesForType(beanFactory, - "javax.sql.DataSource")) { + for (String dependentBeanName : getBeanNamesForType(beanFactory, "javax.sql.DataSource")) { beanFactory.registerDependentBean(transactionManager, dependentBeanName); } } - private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, - String type) { + private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, String type) { try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java index 7dc4a945ad0..4a3749073a5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.boot.jms.XAConnectionFactoryWrapper; public class BitronixXAConnectionFactoryWrapper implements XAConnectionFactoryWrapper { @Override - public ConnectionFactory wrapConnectionFactory( - XAConnectionFactory connectionFactory) { + public ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) { PoolingConnectionFactoryBean pool = new PoolingConnectionFactoryBean(); pool.setConnectionFactory(connectionFactory); return pool; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java index d8104043113..c443f97004f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.boot.jdbc.XADataSourceWrapper; public class BitronixXADataSourceWrapper implements XADataSourceWrapper { @Override - public PoolingDataSourceBean wrapDataSource(XADataSource dataSource) - throws Exception { + public PoolingDataSourceBean wrapDataSource(XADataSource dataSource) throws Exception { PoolingDataSourceBean pool = new PoolingDataSourceBean(); pool.setDataSource(dataSource); return pool; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java index f090c9c8e4f..0de3e82c672 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,8 +105,7 @@ public class PoolingConnectionFactoryBean extends PoolingConnectionFactory } @Override - public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) - throws Exception { + public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) throws Exception { if (xaFactory instanceof DirectXAConnectionFactory) { xaFactory = ((DirectXAConnectionFactory) xaFactory).getConnectionFactory(); } @@ -133,8 +132,7 @@ public class PoolingConnectionFactoryBean extends PoolingConnectionFactory } @Override - public XAConnection createXAConnection(String userName, String password) - throws JMSException { + public XAConnection createXAConnection(String userName, String password) throws JMSException { return this.connectionFactory.createXAConnection(userName, password); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java index 8d42a183e1a..9431d66ebae 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,7 @@ import org.springframework.util.StringUtils; */ @SuppressWarnings("serial") @ConfigurationProperties(prefix = "spring.jta.bitronix.datasource") -public class PoolingDataSourceBean extends PoolingDataSource - implements BeanNameAware, InitializingBean { +public class PoolingDataSourceBean extends PoolingDataSource implements BeanNameAware, InitializingBean { private static final ThreadLocal source = new ThreadLocal<>(); @@ -99,8 +98,7 @@ public class PoolingDataSourceBean extends PoolingDataSource } @Override - public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) - throws Exception { + public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) throws Exception { if (xaFactory instanceof DirectXADataSource) { xaFactory = ((DirectXADataSource) xaFactory).getDataSource(); } @@ -143,8 +141,7 @@ public class PoolingDataSourceBean extends PoolingDataSource } @Override - public XAConnection getXAConnection(String user, String password) - throws SQLException { + public XAConnection getXAConnection(String user, String password) throws SQLException { return this.dataSource.getXAConnection(user, password); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java index a9a0c5ef182..a746df332c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,11 +32,9 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @author Dave Syer */ -public class LiquibaseServiceLocatorApplicationListener - implements ApplicationListener { +public class LiquibaseServiceLocatorApplicationListener implements ApplicationListener { - private static final Log logger = LogFactory - .getLog(LiquibaseServiceLocatorApplicationListener.class); + private static final Log logger = LogFactory.getLog(LiquibaseServiceLocatorApplicationListener.class); @Override public void onApplicationEvent(ApplicationStartingEvent event) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java index 0a460cc9b06..dd0b8b7e4d2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol @Override protected void findAllClasses(String packageName, ClassLoader loader) { - MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory( - loader); + MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(loader); try { Resource[] resources = scan(loader, packageName); for (Resource resource : resources) { @@ -64,15 +63,13 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol } private Resource[] scan(ClassLoader loader, String packageName) throws IOException { - ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( - loader); + ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader); String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(packageName) + "/**/*.class"; return resolver.getResources(pattern); } - private Class loadClass(ClassLoader loader, MetadataReaderFactory readerFactory, - Resource resource) { + private Class loadClass(ClassLoader loader, MetadataReaderFactory readerFactory, Resource resource) { try { MetadataReader reader = readerFactory.getMetadataReader(resource); return ClassUtils.forName(reader.getClassMetadata().getClassName(), loader); @@ -83,8 +80,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol } catch (Throwable ex) { if (this.logger.isWarnEnabled()) { - this.logger.warn( - "Unexpected failure when loading class resource " + resource, ex); + this.logger.warn("Unexpected failure when loading class resource " + resource, ex); } return null; } @@ -92,8 +88,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol private void handleFailure(Resource resource, Throwable ex) { if (this.logger.isDebugEnabled()) { - this.logger.debug( - "Ignoring candidate class resource " + resource + " due to " + ex); + this.logger.debug("Ignoring candidate class resource " + resource + " due to " + ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java index c8534f53c65..5a62c3a2021 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { } @Override - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { if (StringUtils.hasLength(configLocation)) { initializeWithSpecificConfig(initializationContext, configLocation, logFile); return; @@ -60,15 +59,13 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { initializeWithConventions(initializationContext, logFile); } - private void initializeWithSpecificConfig( - LoggingInitializationContext initializationContext, String configLocation, + private void initializeWithSpecificConfig(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { configLocation = SystemPropertyUtils.resolvePlaceholders(configLocation); loadConfiguration(initializationContext, configLocation, logFile); } - private void initializeWithConventions( - LoggingInitializationContext initializationContext, LogFile logFile) { + private void initializeWithConventions(LoggingInitializationContext initializationContext, LogFile logFile) { String config = getSelfInitializationConfig(); if (config != null && logFile == null) { // self initialization has occurred, reinitialize in case of property changes @@ -106,8 +103,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { private String findConfig(String[] locations) { for (String location : locations) { - ClassPathResource resource = new ClassPathResource(location, - this.classLoader); + ClassPathResource resource = new ClassPathResource(location, this.classLoader); if (resource.exists()) { return "classpath:" + location; } @@ -132,8 +128,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { String[] locations = getStandardConfigLocations(); for (int i = 0; i < locations.length; i++) { String extension = StringUtils.getFilenameExtension(locations[i]); - locations[i] = locations[i].substring(0, - locations[i].length() - extension.length() - 1) + "-spring." + locations[i] = locations[i].substring(0, locations[i].length() - extension.length() - 1) + "-spring." + extension; } return locations; @@ -144,8 +139,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { * @param initializationContext the logging initialization context * @param logFile the file to load or {@code null} if no log file is to be written */ - protected abstract void loadDefaults( - LoggingInitializationContext initializationContext, LogFile logFile); + protected abstract void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile); /** * Load a specific configuration. @@ -153,8 +147,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { * @param location the location of the configuration to load (never {@code null}) * @param logFile the file to load or {@code null} if no log file is to be written */ - protected abstract void loadConfiguration( - LoggingInitializationContext initializationContext, String location, + protected abstract void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile); /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java index a686da7ee3e..1cf715b0568 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -184,8 +184,7 @@ public class DeferredLog implements Log { public void replayTo(Log destination) { synchronized (this.lines) { for (Line line : this.lines) { - logTo(destination, line.getLevel(), line.getMessage(), - line.getThrowable()); + logTo(destination, line.getLevel(), line.getMessage(), line.getThrowable()); } this.lines.clear(); } @@ -214,8 +213,7 @@ public class DeferredLog implements Log { return destination; } - private static void logTo(Log log, LogLevel level, Object message, - Throwable throwable) { + private static void logTo(Log log, LogLevel level, Object message, Throwable throwable) { switch (level) { case TRACE: log.trace(message, throwable); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java index 6fb2df4c648..3ef1078bb9b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,7 @@ public class LogFile { * @param path a reference to the logging path to use if {@code file} is not specified */ LogFile(String file, String path) { - Assert.isTrue(StringUtils.hasLength(file) || StringUtils.hasLength(path), - "File or Path must not be empty"); + Assert.isTrue(StringUtils.hasLength(file) || StringUtils.hasLength(path), "File or Path must not be empty"); this.file = file; this.path = path; } @@ -129,18 +128,16 @@ public class LogFile { * suitable properties */ public static LogFile get(PropertyResolver propertyResolver) { - String file = getLogFileProperty(propertyResolver, FILE_NAME_PROPERTY, - FILE_PROPERTY); - String path = getLogFileProperty(propertyResolver, FILE_PATH_PROPERTY, - PATH_PROPERTY); + String file = getLogFileProperty(propertyResolver, FILE_NAME_PROPERTY, FILE_PROPERTY); + String path = getLogFileProperty(propertyResolver, FILE_PATH_PROPERTY, PATH_PROPERTY); if (StringUtils.hasLength(file) || StringUtils.hasLength(path)) { return new LogFile(file, path); } return null; } - private static String getLogFileProperty(PropertyResolver propertyResolver, - String propertyName, String deprecatedPropertyName) { + private static String getLogFileProperty(PropertyResolver propertyResolver, String propertyName, + String deprecatedPropertyName) { String property = propertyResolver.getProperty(propertyName); if (property != null) { return property; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java index 19ae24a51e9..ba2a6142f24 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ public final class LoggerConfiguration { * @param configuredLevel the configured level of the logger * @param effectiveLevel the effective level of the logger */ - public LoggerConfiguration(String name, LogLevel configuredLevel, - LogLevel effectiveLevel) { + public LoggerConfiguration(String name, LogLevel configuredLevel, LogLevel effectiveLevel) { Assert.notNull(name, "Name must not be null"); Assert.notNull(effectiveLevel, "EffectiveLevel must not be null"); this.name = name; @@ -84,10 +83,8 @@ public final class LoggerConfiguration { LoggerConfiguration other = (LoggerConfiguration) obj; boolean rtn = true; rtn = rtn && ObjectUtils.nullSafeEquals(this.name, other.name); - rtn = rtn && ObjectUtils.nullSafeEquals(this.configuredLevel, - other.configuredLevel); - rtn = rtn && ObjectUtils.nullSafeEquals(this.effectiveLevel, - other.effectiveLevel); + rtn = rtn && ObjectUtils.nullSafeEquals(this.configuredLevel, other.configuredLevel); + rtn = rtn && ObjectUtils.nullSafeEquals(this.effectiveLevel, other.effectiveLevel); return rtn; } return super.equals(obj); @@ -105,8 +102,8 @@ public final class LoggerConfiguration { @Override public String toString() { - return "LoggerConfiguration [name=" + this.name + ", configuredLevel=" - + this.configuredLevel + ", effectiveLevel=" + this.effectiveLevel + "]"; + return "LoggerConfiguration [name=" + this.name + ", configuredLevel=" + this.configuredLevel + + ", effectiveLevel=" + this.effectiveLevel + "]"; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java index 7fc5ef50f7b..14233a9c5ed 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,12 +58,10 @@ public abstract class LoggingSystem { static { Map systems = new LinkedHashMap<>(); - systems.put("ch.qos.logback.core.Appender", - "org.springframework.boot.logging.logback.LogbackLoggingSystem"); + systems.put("ch.qos.logback.core.Appender", "org.springframework.boot.logging.logback.LogbackLoggingSystem"); systems.put("org.apache.logging.log4j.core.impl.Log4jContextFactory", "org.springframework.boot.logging.log4j2.Log4J2LoggingSystem"); - systems.put("java.util.logging.LogManager", - "org.springframework.boot.logging.java.JavaLoggingSystem"); + systems.put("java.util.logging.LogManager", "org.springframework.boot.logging.java.JavaLoggingSystem"); SYSTEMS = Collections.unmodifiableMap(systems); } @@ -82,8 +80,7 @@ public abstract class LoggingSystem { * @param logFile the log output file that should be written or {@code null} for * console only output */ - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { } /** @@ -156,18 +153,15 @@ public abstract class LoggingSystem { } return get(classLoader, loggingSystem); } - return SYSTEMS.entrySet().stream() - .filter((entry) -> ClassUtils.isPresent(entry.getKey(), classLoader)) + return SYSTEMS.entrySet().stream().filter((entry) -> ClassUtils.isPresent(entry.getKey(), classLoader)) .map((entry) -> get(classLoader, entry.getValue())).findFirst() - .orElseThrow(() -> new IllegalStateException( - "No suitable logging system located")); + .orElseThrow(() -> new IllegalStateException("No suitable logging system located")); } private static LoggingSystem get(ClassLoader classLoader, String loggingSystemClass) { try { Class systemClass = ClassUtils.forName(loggingSystemClass, classLoader); - return (LoggingSystem) systemClass.getConstructor(ClassLoader.class) - .newInstance(classLoader); + return (LoggingSystem) systemClass.getConstructor(ClassLoader.class).newInstance(classLoader); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java index d99842f3d5f..54fcc6ee5aa 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java @@ -112,13 +112,11 @@ public class LoggingSystemProperties { public void apply(LogFile logFile) { PropertyResolver resolver = getPropertyResolver(); - setSystemProperty(resolver, EXCEPTION_CONVERSION_WORD, - "exception-conversion-word"); + setSystemProperty(resolver, EXCEPTION_CONVERSION_WORD, "exception-conversion-word"); setSystemProperty(PID_KEY, new ApplicationPid().toString()); setSystemProperty(resolver, CONSOLE_LOG_PATTERN, "pattern.console"); setSystemProperty(resolver, FILE_LOG_PATTERN, "pattern.file"); - setSystemProperty(resolver, FILE_CLEAN_HISTORY_ON_START, - "file.clean-history-on-start"); + setSystemProperty(resolver, FILE_CLEAN_HISTORY_ON_START, "file.clean-history-on-start"); setSystemProperty(resolver, FILE_MAX_HISTORY, "file.max-history"); setSystemProperty(resolver, FILE_MAX_SIZE, "file.max-size"); setSystemProperty(resolver, FILE_TOTAL_SIZE_CAP, "file.total-size-cap"); @@ -139,10 +137,8 @@ public class LoggingSystemProperties { return this.environment; } - private void setSystemProperty(PropertyResolver resolver, String systemPropertyName, - String propertyName) { - setSystemProperty(systemPropertyName, - resolver.getProperty("logging." + propertyName)); + private void setSystemProperty(PropertyResolver resolver, String systemPropertyName, String propertyName) { + setSystemProperty(systemPropertyName, resolver.getProperty("logging." + propertyName)); } private void setSystemProperty(String name, String value) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java index b217ec050b6..f153f0281ed 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ public abstract class Slf4JLoggingSystem extends AbstractLoggingSystem { } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { Assert.notNull(location, "Location must not be null"); if (initializationContext != null) { applySystemProperties(initializationContext.getEnvironment(), logFile); @@ -90,8 +90,7 @@ public abstract class Slf4JLoggingSystem extends AbstractLoggingSystem { private boolean isJulUsingASingleConsoleHandlerAtMost() { Logger rootLogger = LogManager.getLogManager().getLogger(""); Handler[] handlers = rootLogger.getHandlers(); - return handlers.length == 0 - || (handlers.length == 1 && handlers[0] instanceof ConsoleHandler); + return handlers.length == 0 || (handlers.length == 1 && handlers[0] instanceof ConsoleHandler); } private void removeJdkLoggingBridgeHandler() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java index 24a929a531c..abc155fff11 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { if (logFile != null) { loadConfiguration(getPackagedConfigFile("logging-file.properties"), logFile); } @@ -87,26 +86,23 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { loadConfiguration(location, logFile); } protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); try { - String configuration = FileCopyUtils.copyToString( - new InputStreamReader(ResourceUtils.getURL(location).openStream())); + String configuration = FileCopyUtils + .copyToString(new InputStreamReader(ResourceUtils.getURL(location).openStream())); if (logFile != null) { - configuration = configuration.replace("${LOG_FILE}", - StringUtils.cleanPath(logFile.toString())); + configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString())); } - LogManager.getLogManager().readConfiguration( - new ByteArrayInputStream(configuration.getBytes())); + LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(configuration.getBytes())); } catch (Exception ex) { - throw new IllegalStateException( - "Could not initialize Java logging from " + location, ex); + throw new IllegalStateException("Could not initialize Java logging from " + location, ex); } } @@ -145,8 +141,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { } LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel()); LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger)); - String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() - : ROOT_LOGGER_NAME); + String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME); return new LoggerConfiguration(name, level, effectiveLevel); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java index d8f2a180f3d..3d47b1c357d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ public class SimpleFormatter extends Formatter { String throwable = getThrowable(record); String thread = getThreadName(); return String.format(this.format, this.date, source, record.getLoggerName(), - record.getLevel().getLocalizedName(), message, throwable, thread, - this.pid); + record.getLevel().getLocalizedName(), message, throwable, thread, this.pid); } private String getThrowable(LogRecord record) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java index 480521a1142..960b5bbbe8f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,8 +91,7 @@ public final class ColorConverter extends LogEventPatternConverter { */ public static ColorConverter newInstance(Configuration config, String[] options) { if (options.length < 1) { - LOGGER.error("Incorrect number of options on style. " - + "Expected at least 1, received {}", options.length); + LOGGER.error("Incorrect number of options on style. " + "Expected at least 1, received {}", options.length); return null; } if (options[0] == null) { @@ -132,8 +131,7 @@ public final class ColorConverter extends LogEventPatternConverter { } } - protected void appendAnsiString(StringBuilder toAppendTo, String in, - AnsiElement element) { + protected void appendAnsiString(StringBuilder toAppendTo, String in, AnsiElement element) { toAppendTo.append(AnsiOutput.toString(element, in)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java index 929d14a66ed..fa6c9b1891c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java @@ -32,19 +32,15 @@ import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; * @author Phillip Webb * @since 1.3.0 */ -@Plugin(name = "ExtendedWhitespaceThrowablePatternConverter", - category = PatternConverter.CATEGORY) +@Plugin(name = "ExtendedWhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY) @ConverterKeys({ "xwEx", "xwThrowable", "xwException" }) -public final class ExtendedWhitespaceThrowablePatternConverter - extends ThrowablePatternConverter { +public final class ExtendedWhitespaceThrowablePatternConverter extends ThrowablePatternConverter { private final ExtendedThrowablePatternConverter delegate; - private ExtendedWhitespaceThrowablePatternConverter(Configuration configuration, - String[] options) { + private ExtendedWhitespaceThrowablePatternConverter(Configuration configuration, String[] options) { super("WhitespaceExtendedThrowable", "throwable", options, configuration); - this.delegate = ExtendedThrowablePatternConverter.newInstance(configuration, - options); + this.delegate = ExtendedThrowablePatternConverter.newInstance(configuration, options); } @Override @@ -63,8 +59,8 @@ public final class ExtendedWhitespaceThrowablePatternConverter * first line of the throwable will be formatted. * @return a new {@code WhitespaceThrowablePatternConverter} */ - public static ExtendedWhitespaceThrowablePatternConverter newInstance( - Configuration configuration, String[] options) { + public static ExtendedWhitespaceThrowablePatternConverter newInstance(Configuration configuration, + String[] options) { return new ExtendedWhitespaceThrowablePatternConverter(configuration, options); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java index 2a81ededb87..29ffb469fc2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java @@ -82,20 +82,17 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - public Result filter(Logger logger, Level level, Marker marker, Message msg, - Throwable t) { + public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { return Result.DENY; } @Override - public Result filter(Logger logger, Level level, Marker marker, Object msg, - Throwable t) { + public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { return Result.DENY; } @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, - Object... params) { + public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) { return Result.DENY; } @@ -138,8 +135,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { LoggerContext loggerContext = getLoggerContext(); if (isAlreadyInitialized(loggerContext)) { return; @@ -150,8 +146,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { if (logFile != null) { loadConfiguration(getPackagedConfigFile("log4j2-file.xml"), logFile); } @@ -161,8 +156,8 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { super.loadConfiguration(initializationContext, location, logFile); loadConfiguration(location, logFile); } @@ -176,8 +171,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { ctx.start(ConfigurationFactory.getInstance().getConfiguration(ctx, source)); } catch (Exception ex) { - throw new IllegalStateException( - "Could not initialize Log4J2 logging from " + location, ex); + throw new IllegalStateException("Could not initialize Log4J2 logging from " + location, ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java index cb6104bcdd3..824b59ffe14 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,7 @@ public class SpringBootConfigurationFactory extends ConfigurationFactory { } @Override - public Configuration getConfiguration(LoggerContext loggerContext, - ConfigurationSource source) { + public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { if (source != null && source != ConfigurationSource.NULL_SOURCE && LoggingSystem.get(loggerContext.getClass().getClassLoader()) != null) { return new SpringBootConfiguration(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java index 16bccd27b00..23104ec886f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java @@ -30,13 +30,11 @@ import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; * @author Vladimir Tsanev * @since 1.3.0 */ -@Plugin(name = "WhitespaceThrowablePatternConverter", - category = PatternConverter.CATEGORY) +@Plugin(name = "WhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY) @ConverterKeys({ "wEx", "wThrowable", "wException" }) public final class WhitespaceThrowablePatternConverter extends ThrowablePatternConverter { - private WhitespaceThrowablePatternConverter(Configuration configuration, - String[] options) { + private WhitespaceThrowablePatternConverter(Configuration configuration, String[] options) { super("WhitespaceThrowable", "throwable", options, configuration); } @@ -56,8 +54,7 @@ public final class WhitespaceThrowablePatternConverter extends ThrowablePatternC * first line of the throwable will be formatted. * @return a new {@code WhitespaceThrowablePatternConverter} */ - public static WhitespaceThrowablePatternConverter newInstance( - Configuration configuration, String[] options) { + public static WhitespaceThrowablePatternConverter newInstance(Configuration configuration, String[] options) { return new WhitespaceThrowablePatternConverter(configuration, options); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java index 0838a7357a9..b7c193d5fc9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java @@ -67,8 +67,7 @@ class DefaultLogbackConfiguration { private final LogFile logFile; - DefaultLogbackConfiguration(LoggingInitializationContext initializationContext, - LogFile logFile) { + DefaultLogbackConfiguration(LoggingInitializationContext initializationContext, LogFile logFile) { this.patterns = getPatternsResolver(initializationContext.getEnvironment()); this.logFile = logFile; } @@ -91,8 +90,7 @@ class DefaultLogbackConfiguration { base(config); Appender consoleAppender = consoleAppender(config); if (this.logFile != null) { - Appender fileAppender = fileAppender(config, - this.logFile.toString()); + Appender fileAppender = fileAppender(config, this.logFile.toString()); config.root(Level.INFO, consoleAppender, fileAppender); } else { @@ -117,8 +115,7 @@ class DefaultLogbackConfiguration { private Appender consoleAppender(LogbackConfigurator config) { ConsoleAppender appender = new ConsoleAppender<>(); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - String logPattern = this.patterns.getProperty("logging.pattern.console", - CONSOLE_LOG_PATTERN); + String logPattern = this.patterns.getProperty("logging.pattern.console", CONSOLE_LOG_PATTERN); encoder.setPattern(OptionHelper.substVars(logPattern, config.getContext())); config.start(encoder); appender.setEncoder(encoder); @@ -126,12 +123,10 @@ class DefaultLogbackConfiguration { return appender; } - private Appender fileAppender(LogbackConfigurator config, - String logFile) { + private Appender fileAppender(LogbackConfigurator config, String logFile) { RollingFileAppender appender = new RollingFileAppender<>(); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - String logPattern = this.patterns.getProperty("logging.pattern.file", - FILE_LOG_PATTERN); + String logPattern = this.patterns.getProperty("logging.pattern.file", FILE_LOG_PATTERN); encoder.setPattern(OptionHelper.substVars(logPattern, config.getContext())); appender.setEncoder(encoder); config.start(encoder); @@ -141,16 +136,15 @@ class DefaultLogbackConfiguration { return appender; } - private void setRollingPolicy(RollingFileAppender appender, - LogbackConfigurator config, String logFile) { + private void setRollingPolicy(RollingFileAppender appender, LogbackConfigurator config, + String logFile) { SizeAndTimeBasedRollingPolicy rollingPolicy = new SizeAndTimeBasedRollingPolicy<>(); - rollingPolicy.setCleanHistoryOnStart(this.patterns.getProperty( - "logging.file.clean-history-on-start", Boolean.class, false)); + rollingPolicy.setCleanHistoryOnStart( + this.patterns.getProperty("logging.file.clean-history-on-start", Boolean.class, false)); rollingPolicy.setFileNamePattern(logFile + ".%d{yyyy-MM-dd}.%i.gz"); - setMaxFileSize(rollingPolicy, - getDataSize("logging.file.max-size", MAX_FILE_SIZE)); - rollingPolicy.setMaxHistory(this.patterns.getProperty("logging.file.max-history", - Integer.class, MAX_FILE_HISTORY)); + setMaxFileSize(rollingPolicy, getDataSize("logging.file.max-size", MAX_FILE_SIZE)); + rollingPolicy + .setMaxHistory(this.patterns.getProperty("logging.file.max-history", Integer.class, MAX_FILE_HISTORY)); DataSize totalSizeCap = getDataSize("logging.file.total-size-cap", DataSize.ofBytes(CoreConstants.UNBOUNDED_TOTAL_SIZE_CAP)); rollingPolicy.setTotalSizeCap(new FileSize(totalSizeCap.toBytes())); @@ -159,18 +153,15 @@ class DefaultLogbackConfiguration { config.start(rollingPolicy); } - private void setMaxFileSize( - SizeAndTimeBasedRollingPolicy rollingPolicy, - DataSize maxFileSize) { + private void setMaxFileSize(SizeAndTimeBasedRollingPolicy rollingPolicy, DataSize maxFileSize) { try { rollingPolicy.setMaxFileSize(new FileSize(maxFileSize.toBytes())); } catch (NoSuchMethodError ex) { // Logback < 1.1.8 used String configuration - Method method = ReflectionUtils.findMethod( - SizeAndTimeBasedRollingPolicy.class, "setMaxFileSize", String.class); - ReflectionUtils.invokeMethod(method, rollingPolicy, - String.valueOf(maxFileSize.toBytes())); + Method method = ReflectionUtils.findMethod(SizeAndTimeBasedRollingPolicy.class, "setMaxFileSize", + String.class); + ReflectionUtils.invokeMethod(method, rollingPolicy, String.valueOf(maxFileSize.toBytes())); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java index 8353b2d94d7..db52481b662 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,11 @@ import ch.qos.logback.core.CoreConstants; * @author Phillip Webb * @since 1.3.0 */ -public class ExtendedWhitespaceThrowableProxyConverter - extends ExtendedThrowableProxyConverter { +public class ExtendedWhitespaceThrowableProxyConverter extends ExtendedThrowableProxyConverter { @Override protected String throwableProxyToString(IThrowableProxy tp) { - return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) - + CoreConstants.LINE_SEPARATOR; + return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) + CoreConstants.LINE_SEPARATOR; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java index 4a884a01464..b8564b8a9a1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ class LogbackConfigurator { } @SuppressWarnings({ "rawtypes", "unchecked" }) - public void conversionRule(String conversionWord, - Class converterClass) { + public void conversionRule(String conversionWord, Class converterClass) { Assert.hasLength(conversionWord, "Conversion word must not be empty"); Assert.notNull(converterClass, "Converter class must not be null"); Map registry = (Map) this.context @@ -82,8 +81,7 @@ class LogbackConfigurator { logger(name, level, additive, null); } - public void logger(String name, Level level, boolean additive, - Appender appender) { + public void logger(String name, Level level, boolean additive, Appender appender) { Logger logger = this.context.getLogger(name); if (level != null) { logger.setLevel(level); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java index 6f612680ad0..ca44e6ac378 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,8 +80,8 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { private static final TurboFilter FILTER = new TurboFilter() { @Override - public FilterReply decide(Marker marker, ch.qos.logback.classic.Logger logger, - Level level, String format, Object[] params, Throwable t) { + public FilterReply decide(Marker marker, ch.qos.logback.classic.Logger logger, Level level, String format, + Object[] params, Throwable t) { return FilterReply.DENY; } @@ -93,8 +93,7 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { @Override protected String[] getStandardConfigLocations() { - return new String[] { "logback-test.groovy", "logback-test.xml", "logback.groovy", - "logback.xml" }; + return new String[] { "logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml" }; } @Override @@ -108,8 +107,7 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { } @Override - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { LoggerContext loggerContext = getLoggerContext(); if (isAlreadyInitialized(loggerContext)) { return; @@ -118,43 +116,36 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { loggerContext.getTurboFilterList().remove(FILTER); markAsInitialized(loggerContext); if (StringUtils.hasText(System.getProperty(CONFIGURATION_FILE_PROPERTY))) { - getLogger(LogbackLoggingSystem.class.getName()).warn( - "Ignoring '" + CONFIGURATION_FILE_PROPERTY + "' system property. " - + "Please use 'logging.config' instead."); + getLogger(LogbackLoggingSystem.class.getName()).warn("Ignoring '" + CONFIGURATION_FILE_PROPERTY + + "' system property. " + "Please use 'logging.config' instead."); } } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { LoggerContext context = getLoggerContext(); stopAndReset(context); LogbackConfigurator configurator = new LogbackConfigurator(context); Environment environment = initializationContext.getEnvironment(); context.putProperty(LoggingSystemProperties.LOG_LEVEL_PATTERN, - environment.resolvePlaceholders( - "${logging.pattern.level:${LOG_LEVEL_PATTERN:%5p}}")); - context.putProperty(LoggingSystemProperties.LOG_DATEFORMAT_PATTERN, - environment.resolvePlaceholders( - "${logging.pattern.dateformat:${LOG_DATEFORMAT_PATTERN:yyyy-MM-dd HH:mm:ss.SSS}}")); - new DefaultLogbackConfiguration(initializationContext, logFile) - .apply(configurator); + environment.resolvePlaceholders("${logging.pattern.level:${LOG_LEVEL_PATTERN:%5p}}")); + context.putProperty(LoggingSystemProperties.LOG_DATEFORMAT_PATTERN, environment.resolvePlaceholders( + "${logging.pattern.dateformat:${LOG_DATEFORMAT_PATTERN:yyyy-MM-dd HH:mm:ss.SSS}}")); + new DefaultLogbackConfiguration(initializationContext, logFile).apply(configurator); context.setPackagingDataEnabled(true); } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { super.loadConfiguration(initializationContext, location, logFile); LoggerContext loggerContext = getLoggerContext(); stopAndReset(loggerContext); try { - configureByResourceUrl(initializationContext, loggerContext, - ResourceUtils.getURL(location)); + configureByResourceUrl(initializationContext, loggerContext, ResourceUtils.getURL(location)); } catch (Exception ex) { - throw new IllegalStateException( - "Could not initialize Logback logging from " + location, ex); + throw new IllegalStateException("Could not initialize Logback logging from " + location, ex); } List statuses = loggerContext.getStatusManager().getCopyOfStatusList(); StringBuilder errors = new StringBuilder(); @@ -165,17 +156,14 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { } } if (errors.length() > 0) { - throw new IllegalStateException( - String.format("Logback configuration error detected: %n%s", errors)); + throw new IllegalStateException(String.format("Logback configuration error detected: %n%s", errors)); } } - private void configureByResourceUrl( - LoggingInitializationContext initializationContext, - LoggerContext loggerContext, URL url) throws JoranException { + private void configureByResourceUrl(LoggingInitializationContext initializationContext, LoggerContext loggerContext, + URL url) throws JoranException { if (url.toString().endsWith("xml")) { - JoranConfigurator configurator = new SpringBootJoranConfigurator( - initializationContext); + JoranConfigurator configurator = new SpringBootJoranConfigurator(initializationContext); configurator.setContext(loggerContext); configurator.doConfigure(url); } @@ -239,14 +227,12 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { return getLoggerConfiguration(getLogger(loggerName)); } - private LoggerConfiguration getLoggerConfiguration( - ch.qos.logback.classic.Logger logger) { + private LoggerConfiguration getLoggerConfiguration(ch.qos.logback.classic.Logger logger) { if (logger == null) { return null; } LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel()); - LogLevel effectiveLevel = LEVELS - .convertNativeToSystem(logger.getEffectiveLevel()); + LogLevel effectiveLevel = LEVELS.convertNativeToSystem(logger.getEffectiveLevel()); String name = logger.getName(); if (!StringUtils.hasLength(name) || Logger.ROOT_LOGGER_NAME.equals(name)) { name = ROOT_LOGGER_NAME; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java index 0f78bce7d91..b101191f04f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,10 +42,8 @@ class SpringBootJoranConfigurator extends JoranConfigurator { public void addInstanceRules(RuleStore rs) { super.addInstanceRules(rs); Environment environment = this.initializationContext.getEnvironment(); - rs.addRule(new ElementSelector("configuration/springProperty"), - new SpringPropertyAction(environment)); - rs.addRule(new ElementSelector("*/springProfile"), - new SpringProfileAction(environment)); + rs.addRule(new ElementSelector("configuration/springProperty"), new SpringPropertyAction(environment)); + rs.addRule(new ElementSelector("*/springProfile"), new SpringProfileAction(environment)); rs.addRule(new ElementSelector("*/springProfile/*"), new NOPAction()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java index c7d1a579daa..a9a1e0a51bf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,7 @@ class SpringProfileAction extends Action implements InPlayListener { } @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) - throws ActionException { + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { this.depth++; if (this.depth != 1) { return; @@ -71,8 +70,8 @@ class SpringProfileAction extends Action implements InPlayListener { if (this.environment == null) { return false; } - String[] profileNames = StringUtils.trimArrayElements(StringUtils - .commaDelimitedListToStringArray(attributes.getValue(NAME_ATTRIBUTE))); + String[] profileNames = StringUtils + .trimArrayElements(StringUtils.commaDelimitedListToStringArray(attributes.getValue(NAME_ATTRIBUTE))); if (profileNames.length == 0) { return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java index afcb2927aed..5100922f1e6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java @@ -47,15 +47,13 @@ class SpringPropertyAction extends Action { } @Override - public void begin(InterpretationContext context, String elementName, - Attributes attributes) throws ActionException { + public void begin(InterpretationContext context, String elementName, Attributes attributes) throws ActionException { String name = attributes.getValue(NAME_ATTRIBUTE); String source = attributes.getValue(SOURCE_ATTRIBUTE); Scope scope = ActionUtil.stringToScope(attributes.getValue(SCOPE_ATTRIBUTE)); String defaultValue = attributes.getValue(DEFAULT_VALUE_ATTRIBUTE); if (OptionHelper.isEmpty(name) || OptionHelper.isEmpty(source)) { - addError( - "The \"name\" and \"source\" attributes of must be set"); + addError("The \"name\" and \"source\" attributes of must be set"); } ActionUtil.setProperty(context, name, getValue(source, defaultValue), scope); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java index 43d33f5a02f..2f2032468ec 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ public class WhitespaceThrowableProxyConverter extends ThrowableProxyConverter { @Override protected String throwableProxyToString(IThrowableProxy tp) { - return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) - + CoreConstants.LINE_SEPARATOR; + return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) + CoreConstants.LINE_SEPARATOR; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java index d13713419e9..5f5d6dd63ab 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,8 +95,7 @@ public class OriginTrackedValue implements OriginProvider { /** * {@link OriginTrackedValue} for a {@link CharSequence}. */ - private static class OriginTrackedCharSequence extends OriginTrackedValue - implements CharSequence { + private static class OriginTrackedCharSequence extends OriginTrackedValue implements CharSequence { OriginTrackedCharSequence(CharSequence value, Origin origin) { super(value, origin); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/PropertySourceOrigin.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/PropertySourceOrigin.java index 890d1b0cc5a..48c7f4e16c2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/PropertySourceOrigin.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/PropertySourceOrigin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ public class PropertySourceOrigin implements Origin { @Override public String toString() { - return "\"" + this.propertyName + "\" from property source \"" - + this.propertySource.getName() + "\""; + return "\"" + this.propertyName + "\" from property source \"" + this.propertySource.getName() + "\""; } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java index 9d4aa737828..c478d87d880 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,8 +83,7 @@ public class TextResourceOrigin implements Origin { @Override public String toString() { StringBuilder result = new StringBuilder(); - result.append((this.resource != null) ? this.resource.getDescription() - : "unknown resource [?]"); + result.append((this.resource != null) ? this.resource.getDescription() : "unknown resource [?]"); if (this.location != null) { result.append(":").append(this.location); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java index 6a7d7c6ba05..84aa4d979f1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,8 @@ public class EntityManagerFactoryBuilder { * @param persistenceUnitManager optional source of persistence unit information (can * be null) */ - public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, - Map jpaProperties, PersistenceUnitManager persistenceUnitManager) { + public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map jpaProperties, + PersistenceUnitManager persistenceUnitManager) { this(jpaVendorAdapter, jpaProperties, persistenceUnitManager, null); } @@ -82,9 +82,8 @@ public class EntityManagerFactoryBuilder { * fallback (can be null) * @since 1.4.1 */ - public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, - Map jpaProperties, PersistenceUnitManager persistenceUnitManager, - URL persistenceUnitRootLocation) { + public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map jpaProperties, + PersistenceUnitManager persistenceUnitManager, URL persistenceUnitRootLocation) { this.jpaVendorAdapter = jpaVendorAdapter; this.persistenceUnitManager = persistenceUnitManager; this.jpaProperties = new LinkedHashMap<>(jpaProperties); @@ -206,14 +205,13 @@ public class EntityManagerFactoryBuilder { public LocalContainerEntityManagerFactoryBean build() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); if (EntityManagerFactoryBuilder.this.persistenceUnitManager != null) { - entityManagerFactoryBean.setPersistenceUnitManager( - EntityManagerFactoryBuilder.this.persistenceUnitManager); + entityManagerFactoryBean + .setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager); } if (this.persistenceUnit != null) { entityManagerFactoryBean.setPersistenceUnitName(this.persistenceUnit); } - entityManagerFactoryBean.setJpaVendorAdapter( - EntityManagerFactoryBuilder.this.jpaVendorAdapter); + entityManagerFactoryBean.setJpaVendorAdapter(EntityManagerFactoryBuilder.this.jpaVendorAdapter); if (this.jta) { entityManagerFactoryBean.setJtaDataSource(this.dataSource); @@ -222,20 +220,17 @@ public class EntityManagerFactoryBuilder { entityManagerFactoryBean.setDataSource(this.dataSource); } entityManagerFactoryBean.setPackagesToScan(this.packagesToScan); - entityManagerFactoryBean.getJpaPropertyMap() - .putAll(EntityManagerFactoryBuilder.this.jpaProperties); + entityManagerFactoryBean.getJpaPropertyMap().putAll(EntityManagerFactoryBuilder.this.jpaProperties); entityManagerFactoryBean.getJpaPropertyMap().putAll(this.properties); if (!ObjectUtils.isEmpty(this.mappingResources)) { entityManagerFactoryBean.setMappingResources(this.mappingResources); } URL rootLocation = EntityManagerFactoryBuilder.this.persistenceUnitRootLocation; if (rootLocation != null) { - entityManagerFactoryBean - .setPersistenceUnitRootLocation(rootLocation.toString()); + entityManagerFactoryBean.setPersistenceUnitRootLocation(rootLocation.toString()); } if (EntityManagerFactoryBuilder.this.bootstrapExecutor != null) { - entityManagerFactoryBean.setBootstrapExecutor( - EntityManagerFactoryBuilder.this.bootstrapExecutor); + entityManagerFactoryBean.setBootstrapExecutor(EntityManagerFactoryBuilder.this.bootstrapExecutor); } return entityManagerFactoryBean; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java index 33c321f93b2..fcbf3cce6cb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,32 +33,27 @@ import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { @Override - public Identifier toPhysicalCatalogName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalSchemaName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalTableName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalSequenceName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalColumnName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @@ -68,8 +63,7 @@ public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { } StringBuilder builder = new StringBuilder(name.getText().replace('.', '_')); for (int i = 1; i < builder.length() - 1; i++) { - if (isUnderscoreRequired(builder.charAt(i - 1), builder.charAt(i), - builder.charAt(i + 1))) { + if (isUnderscoreRequired(builder.charAt(i - 1), builder.charAt(i), builder.charAt(i + 1))) { builder.insert(i++, '_'); } } @@ -85,8 +79,7 @@ public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { * @param jdbcEnvironment the JDBC environment * @return an identifier instance */ - protected Identifier getIdentifier(String name, boolean quoted, - JdbcEnvironment jdbcEnvironment) { + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { if (isCaseInsensitive(jdbcEnvironment)) { name = name.toLowerCase(Locale.ROOT); } @@ -103,8 +96,7 @@ public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { } private boolean isUnderscoreRequired(char before, char current, char after) { - return Character.isLowerCase(before) && Character.isUpperCase(current) - && Character.isLowerCase(after); + return Character.isLowerCase(before) && Character.isUpperCase(current) && Character.isLowerCase(after); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactory.java index f559e5aa1c8..b6cf5669853 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactory.java @@ -48,8 +48,7 @@ import org.springframework.util.Assert; * @author Brian Clozel * @since 2.2.0 */ -public class NettyRSocketServerFactory - implements RSocketServerFactory, ConfigurableRSocketServerFactory { +public class NettyRSocketServerFactory implements RSocketServerFactory, ConfigurableRSocketServerFactory { private int port = 9898; @@ -91,8 +90,7 @@ public class NettyRSocketServerFactory * server builder. Calling this method will replace any existing customizers. * @param serverCustomizers the customizers to set */ - public void setServerCustomizers( - Collection serverCustomizers) { + public void setServerCustomizers(Collection serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizers must not be null"); this.serverCustomizers = new ArrayList<>(serverCustomizers); } @@ -102,8 +100,7 @@ public class NettyRSocketServerFactory * server. * @param serverCustomizers the customizers to add */ - public void addServerCustomizers( - ServerRSocketFactoryCustomizer... serverCustomizers) { + public void addServerCustomizers(ServerRSocketFactoryCustomizer... serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizer must not be null"); this.serverCustomizers.addAll(Arrays.asList(serverCustomizers)); } @@ -124,8 +121,7 @@ public class NettyRSocketServerFactory for (ServerRSocketFactoryCustomizer customizer : this.serverCustomizers) { factory = customizer.apply(factory); } - Mono starter = factory.acceptor(socketAcceptor) - .transport(transport).start(); + Mono starter = factory.acceptor(socketAcceptor).transport(transport).start(); return new NettyRSocketServer(starter, this.lifecycleTimeout); } @@ -133,8 +129,7 @@ public class NettyRSocketServerFactory if (this.transport == RSocketServer.TRANSPORT.WEBSOCKET) { if (this.resourceFactory != null) { HttpServer httpServer = HttpServer.create() - .tcpConfiguration((tcpServer) -> tcpServer - .runOn(this.resourceFactory.getLoopResources())); + .tcpConfiguration((tcpServer) -> tcpServer.runOn(this.resourceFactory.getLoopResources())); return WebsocketServerTransport.create(httpServer); } else { @@ -143,8 +138,7 @@ public class NettyRSocketServerFactory } else { if (this.resourceFactory != null) { - TcpServer tcpServer = TcpServer.create() - .runOn(this.resourceFactory.getLoopResources()) + TcpServer tcpServer = TcpServer.create().runOn(this.resourceFactory.getLoopResources()) .addressSupplier(this::getListenAddress); return TcpServerTransport.create(tcpServer); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/RSocketServerBootstrap.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/RSocketServerBootstrap.java index a9cb747a80c..484c32b17df 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/RSocketServerBootstrap.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/RSocketServerBootstrap.java @@ -29,29 +29,25 @@ import org.springframework.context.SmartLifecycle; * @author Brian Clozel * @since 2.2.0 */ -public class RSocketServerBootstrap - implements ApplicationEventPublisherAware, SmartLifecycle { +public class RSocketServerBootstrap implements ApplicationEventPublisherAware, SmartLifecycle { private final RSocketServer rSocketServer; private ApplicationEventPublisher applicationEventPublisher; - public RSocketServerBootstrap(RSocketServerFactory serverFactoryProvider, - SocketAcceptor socketAcceptor) { + public RSocketServerBootstrap(RSocketServerFactory serverFactoryProvider, SocketAcceptor socketAcceptor) { this.rSocketServer = serverFactoryProvider.create(socketAcceptor); } @Override - public void setApplicationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } @Override public void start() { this.rSocketServer.start(); - this.applicationEventPublisher - .publishEvent(new RSocketServerInitializedEvent(this.rSocketServer)); + this.applicationEventPublisher.publishEvent(new RSocketServerInitializedEvent(this.rSocketServer)); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/ServerRSocketFactoryCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/ServerRSocketFactoryCustomizer.java index bf40e2a8393..26ebeb35c02 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/ServerRSocketFactoryCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/server/ServerRSocketFactoryCustomizer.java @@ -28,7 +28,7 @@ import io.rsocket.RSocketFactory; * @since 2.2.0 */ @FunctionalInterface -public interface ServerRSocketFactoryCustomizer extends - Function { +public interface ServerRSocketFactoryCustomizer + extends Function { } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcher.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcher.java index c541d26bf6f..599ac4ae103 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcher.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import org.springframework.web.server.ServerWebExchange; * @author Madhura Bhave * @since 2.0.0 */ -public abstract class ApplicationContextServerWebExchangeMatcher - implements ServerWebExchangeMatcher { +public abstract class ApplicationContextServerWebExchangeMatcher implements ServerWebExchangeMatcher { private final Class contextClass; @@ -63,8 +62,7 @@ public abstract class ApplicationContextServerWebExchangeMatcher * @param context a supplier for the initialized context (may throw an exception) * @return if the exchange matches */ - protected abstract Mono matches(ServerWebExchange exchange, - Supplier context); + protected abstract Mono matches(ServerWebExchange exchange, Supplier context); protected Supplier getContext(ServerWebExchange exchange) { if (this.context == null) { @@ -89,8 +87,7 @@ public abstract class ApplicationContextServerWebExchangeMatcher @SuppressWarnings("unchecked") private Supplier createContext(ServerWebExchange exchange) { ApplicationContext context = exchange.getApplicationContext(); - Assert.state(context != null, - "No ApplicationContext found on ServerWebExchange."); + Assert.state(context != null, "No ApplicationContext found on ServerWebExchange."); if (this.contextClass.isInstance(context)) { return () -> (C) context; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java index 2816aa41ec6..15e508df868 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,8 +88,7 @@ public class ApplicationHome { private File findSource(Class sourceClass) { try { - ProtectionDomain domain = (sourceClass != null) - ? sourceClass.getProtectionDomain() : null; + ProtectionDomain domain = (sourceClass != null) ? sourceClass.getProtectionDomain() : null; CodeSource codeSource = (domain != null) ? domain.getCodeSource() : null; URL location = (codeSource != null) ? codeSource.getLocation() : null; File source = (location != null) ? findSource(location) : null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java index 1c0a4a72222..8ffcd04a19b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,9 +36,8 @@ import org.springframework.util.ObjectUtils; */ public class ApplicationPid { - private static final PosixFilePermission[] WRITE_PERMISSIONS = { - PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_WRITE, - PosixFilePermission.OTHERS_WRITE }; + private static final PosixFilePermission[] WRITE_PERMISSIONS = { PosixFilePermission.OWNER_WRITE, + PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_WRITE }; private final String pid; @@ -113,8 +112,7 @@ public class ApplicationPid { private boolean canWritePosixFile(File file) throws IOException { try { - Set permissions = Files - .getPosixFilePermissions(file.toPath()); + Set permissions = Files.getPosixFilePermissions(file.toPath()); for (PosixFilePermission permission : WRITE_PERMISSIONS) { if (permissions.contains(permission)) { return true; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java index f8fa6e3baa7..65171a6dc1a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,7 @@ public class ApplicationTemp { byte[] hash = generateHash(this.sourceClass); this.dir = new File(getTempDirectory(), toHexString(hash)); this.dir.mkdirs(); - Assert.state(this.dir.exists(), - () -> "Unable to create temp directory " + this.dir); + Assert.state(this.dir.exists(), () -> "Unable to create temp directory " + this.dir); } } return this.dir; @@ -91,8 +90,7 @@ public class ApplicationTemp { Assert.state(StringUtils.hasLength(property), "No 'java.io.tmpdir' property set"); File file = new File(property); Assert.state(file.exists(), () -> "Temp directory " + file + " does not exist"); - Assert.state(file.isDirectory(), - () -> "Temp location " + file + " is not a directory"); + Assert.state(file.isDirectory(), () -> "Temp location " + file + " is not a directory"); return file; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java index 1b133cc1550..fb32a305346 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public final class SystemProperties { } } catch (Throwable ex) { - System.err.println( - "Could not resolve '" + property + "' as system property: " + ex); + System.err.println("Could not resolve '" + property + "' as system property: " + ex); } } return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskExecutorBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskExecutorBuilder.java index 16600543ad2..7a5313a6607 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskExecutorBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskExecutorBuilder.java @@ -78,10 +78,9 @@ public class TaskExecutorBuilder { this.customizers = null; } - private TaskExecutorBuilder(Integer queueCapacity, Integer corePoolSize, - Integer maxPoolSize, Boolean allowCoreThreadTimeOut, Duration keepAlive, - Boolean awaitTermination, Duration awaitTerminationPeriod, - String threadNamePrefix, TaskDecorator taskDecorator, + private TaskExecutorBuilder(Integer queueCapacity, Integer corePoolSize, Integer maxPoolSize, + Boolean allowCoreThreadTimeOut, Duration keepAlive, Boolean awaitTermination, + Duration awaitTerminationPeriod, String threadNamePrefix, TaskDecorator taskDecorator, Set customizers) { this.queueCapacity = queueCapacity; this.corePoolSize = corePoolSize; @@ -102,10 +101,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder queueCapacity(int queueCapacity) { - return new TaskExecutorBuilder(queueCapacity, this.corePoolSize, this.maxPoolSize, - this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, - this.customizers); + return new TaskExecutorBuilder(queueCapacity, this.corePoolSize, this.maxPoolSize, this.allowCoreThreadTimeOut, + this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, + this.taskDecorator, this.customizers); } /** @@ -118,10 +116,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder corePoolSize(int corePoolSize) { - return new TaskExecutorBuilder(this.queueCapacity, corePoolSize, this.maxPoolSize, - this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, - this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, corePoolSize, this.maxPoolSize, this.allowCoreThreadTimeOut, + this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, + this.taskDecorator, this.customizers); } /** @@ -134,10 +131,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder maxPoolSize(int maxPoolSize) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, maxPoolSize, - this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, - this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, maxPoolSize, this.allowCoreThreadTimeOut, + this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, + this.taskDecorator, this.customizers); } /** @@ -147,9 +143,8 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder allowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, allowCoreThreadTimeOut, this.keepAlive, - this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, allowCoreThreadTimeOut, + this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, this.customizers); } @@ -159,10 +154,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder keepAlive(Duration keepAlive) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, keepAlive, - this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, - this.taskDecorator, this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, keepAlive, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, this.taskDecorator, this.customizers); } /** @@ -174,10 +168,9 @@ public class TaskExecutorBuilder { * @see #awaitTerminationPeriod(Duration) */ public TaskExecutorBuilder awaitTermination(boolean awaitTermination) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, this.keepAlive, - awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, - this.taskDecorator, this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, this.keepAlive, awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, this.taskDecorator, this.customizers); } /** @@ -190,10 +183,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder awaitTerminationPeriod(Duration awaitTerminationPeriod) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, this.keepAlive, - this.awaitTermination, awaitTerminationPeriod, this.threadNamePrefix, - this.taskDecorator, this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, awaitTerminationPeriod, + this.threadNamePrefix, this.taskDecorator, this.customizers); } /** @@ -202,10 +194,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder threadNamePrefix(String threadNamePrefix) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, this.keepAlive, - this.awaitTermination, this.awaitTerminationPeriod, threadNamePrefix, - this.taskDecorator, this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, + threadNamePrefix, this.taskDecorator, this.customizers); } /** @@ -214,10 +205,9 @@ public class TaskExecutorBuilder { * @return a new builder instance */ public TaskExecutorBuilder taskDecorator(TaskDecorator taskDecorator) { - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, this.keepAlive, - this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, - taskDecorator, this.customizers); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, taskDecorator, this.customizers); } /** @@ -245,10 +235,9 @@ public class TaskExecutorBuilder { */ public TaskExecutorBuilder customizers(Iterable customizers) { Assert.notNull(customizers, "Customizers must not be null"); - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, this.keepAlive, - this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, - this.taskDecorator, append(null, customizers)); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, this.taskDecorator, append(null, customizers)); } /** @@ -259,8 +248,7 @@ public class TaskExecutorBuilder { * @return a new builder instance * @see #customizers(TaskExecutorCustomizer...) */ - public TaskExecutorBuilder additionalCustomizers( - TaskExecutorCustomizer... customizers) { + public TaskExecutorBuilder additionalCustomizers(TaskExecutorCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); return additionalCustomizers(Arrays.asList(customizers)); } @@ -273,13 +261,11 @@ public class TaskExecutorBuilder { * @return a new builder instance * @see #customizers(TaskExecutorCustomizer...) */ - public TaskExecutorBuilder additionalCustomizers( - Iterable customizers) { + public TaskExecutorBuilder additionalCustomizers(Iterable customizers) { Assert.notNull(customizers, "Customizers must not be null"); - return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, - this.maxPoolSize, this.allowCoreThreadTimeOut, this.keepAlive, - this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, - this.taskDecorator, append(this.customizers, customizers)); + return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, + this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, this.taskDecorator, append(this.customizers, customizers)); } /** @@ -319,15 +305,11 @@ public class TaskExecutorBuilder { map.from(this.queueCapacity).to(taskExecutor::setQueueCapacity); map.from(this.corePoolSize).to(taskExecutor::setCorePoolSize); map.from(this.maxPoolSize).to(taskExecutor::setMaxPoolSize); - map.from(this.keepAlive).asInt(Duration::getSeconds) - .to(taskExecutor::setKeepAliveSeconds); + map.from(this.keepAlive).asInt(Duration::getSeconds).to(taskExecutor::setKeepAliveSeconds); map.from(this.allowCoreThreadTimeOut).to(taskExecutor::setAllowCoreThreadTimeOut); - map.from(this.awaitTermination) - .to(taskExecutor::setWaitForTasksToCompleteOnShutdown); - map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds) - .to(taskExecutor::setAwaitTerminationSeconds); - map.from(this.threadNamePrefix).whenHasText() - .to(taskExecutor::setThreadNamePrefix); + map.from(this.awaitTermination).to(taskExecutor::setWaitForTasksToCompleteOnShutdown); + map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds).to(taskExecutor::setAwaitTerminationSeconds); + map.from(this.threadNamePrefix).whenHasText().to(taskExecutor::setThreadNamePrefix); map.from(this.taskDecorator).to(taskExecutor::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskExecutor)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskSchedulerBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskSchedulerBuilder.java index 0dba3ee9f2b..9ec2c3e6aee 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskSchedulerBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/TaskSchedulerBuilder.java @@ -59,9 +59,8 @@ public class TaskSchedulerBuilder { this.customizers = null; } - public TaskSchedulerBuilder(Integer poolSize, Boolean awaitTermination, - Duration awaitTerminationPeriod, String threadNamePrefix, - Set taskSchedulerCustomizers) { + public TaskSchedulerBuilder(Integer poolSize, Boolean awaitTermination, Duration awaitTerminationPeriod, + String threadNamePrefix, Set taskSchedulerCustomizers) { this.poolSize = poolSize; this.awaitTermination = awaitTermination; this.awaitTerminationPeriod = awaitTerminationPeriod; @@ -75,8 +74,8 @@ public class TaskSchedulerBuilder { * @return a new builder instance */ public TaskSchedulerBuilder poolSize(int poolSize) { - return new TaskSchedulerBuilder(poolSize, this.awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, this.customizers); + return new TaskSchedulerBuilder(poolSize, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, this.customizers); } /** @@ -88,8 +87,8 @@ public class TaskSchedulerBuilder { * @see #awaitTerminationPeriod(Duration) */ public TaskSchedulerBuilder awaitTermination(boolean awaitTermination) { - return new TaskSchedulerBuilder(this.poolSize, awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, this.customizers); + return new TaskSchedulerBuilder(this.poolSize, awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, this.customizers); } /** @@ -102,8 +101,8 @@ public class TaskSchedulerBuilder { * @return a new builder instance */ public TaskSchedulerBuilder awaitTerminationPeriod(Duration awaitTerminationPeriod) { - return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, - awaitTerminationPeriod, this.threadNamePrefix, this.customizers); + return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, awaitTerminationPeriod, + this.threadNamePrefix, this.customizers); } /** @@ -112,8 +111,8 @@ public class TaskSchedulerBuilder { * @return a new builder instance */ public TaskSchedulerBuilder threadNamePrefix(String threadNamePrefix) { - return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, - this.awaitTerminationPeriod, threadNamePrefix, this.customizers); + return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, this.awaitTerminationPeriod, + threadNamePrefix, this.customizers); } /** @@ -139,12 +138,10 @@ public class TaskSchedulerBuilder { * @return a new builder instance * @see #additionalCustomizers(TaskSchedulerCustomizer...) */ - public TaskSchedulerBuilder customizers( - Iterable customizers) { + public TaskSchedulerBuilder customizers(Iterable customizers) { Assert.notNull(customizers, "Customizers must not be null"); - return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, - append(null, customizers)); + return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, append(null, customizers)); } /** @@ -155,8 +152,7 @@ public class TaskSchedulerBuilder { * @return a new builder instance * @see #customizers(TaskSchedulerCustomizer...) */ - public TaskSchedulerBuilder additionalCustomizers( - TaskSchedulerCustomizer... customizers) { + public TaskSchedulerBuilder additionalCustomizers(TaskSchedulerCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); return additionalCustomizers(Arrays.asList(customizers)); } @@ -169,12 +165,10 @@ public class TaskSchedulerBuilder { * @return a new builder instance * @see #customizers(TaskSchedulerCustomizer...) */ - public TaskSchedulerBuilder additionalCustomizers( - Iterable customizers) { + public TaskSchedulerBuilder additionalCustomizers(Iterable customizers) { Assert.notNull(customizers, "Customizers must not be null"); - return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, - this.awaitTerminationPeriod, this.threadNamePrefix, - append(this.customizers, customizers)); + return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, this.awaitTerminationPeriod, + this.threadNamePrefix, append(this.customizers, customizers)); } /** @@ -197,10 +191,8 @@ public class TaskSchedulerBuilder { public T configure(T taskScheduler) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this.poolSize).to(taskScheduler::setPoolSize); - map.from(this.awaitTermination) - .to(taskScheduler::setWaitForTasksToCompleteOnShutdown); - map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds) - .to(taskScheduler::setAwaitTerminationSeconds); + map.from(this.awaitTermination).to(taskScheduler::setWaitForTasksToCompleteOnShutdown); + map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds).to(taskScheduler::setAwaitTerminationSeconds); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java index 837835c90b8..48ac8c176f5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.springframework.util.ConcurrentReferenceHashMap; * @since 1.4.0 * @see CachingMetadataReaderFactory */ -public class ConcurrentReferenceCachingMetadataReaderFactory - extends SimpleMetadataReaderFactory { +public class ConcurrentReferenceCachingMetadataReaderFactory extends SimpleMetadataReaderFactory { private final Map cache = new ConcurrentReferenceHashMap<>(); @@ -54,8 +53,7 @@ public class ConcurrentReferenceCachingMetadataReaderFactory * @param resourceLoader the Spring ResourceLoader to use (also determines the * ClassLoader to use) */ - public ConcurrentReferenceCachingMetadataReaderFactory( - ResourceLoader resourceLoader) { + public ConcurrentReferenceCachingMetadataReaderFactory(ResourceLoader resourceLoader) { super(resourceLoader); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java index 07670837945..cf7de8cd5ac 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public final class LambdaSafe { static { CLASS_GET_MODULE = ReflectionUtils.findMethod(Class.class, "getModule"); MODULE_GET_NAME = (CLASS_GET_MODULE != null) - ? ReflectionUtils.findMethod(CLASS_GET_MODULE.getReturnType(), "getName") - : null; + ? ReflectionUtils.findMethod(CLASS_GET_MODULE.getReturnType(), "getName") : null; } private LambdaSafe() { @@ -69,12 +68,11 @@ public final class LambdaSafe { * @param the primary argument type * @return a {@link Callback} instance that can be invoked. */ - public static Callback callback(Class callbackType, - C callbackInstance, A argument, Object... additionalArguments) { + public static Callback callback(Class callbackType, C callbackInstance, A argument, + Object... additionalArguments) { Assert.notNull(callbackType, "CallbackType must not be null"); Assert.notNull(callbackInstance, "CallbackInstance must not be null"); - return new Callback<>(callbackType, callbackInstance, argument, - additionalArguments); + return new Callback<>(callbackType, callbackInstance, argument, additionalArguments); } /** @@ -89,13 +87,11 @@ public final class LambdaSafe { * @param the primary argument type * @return a {@link Callbacks} instance that can be invoked. */ - public static Callbacks callbacks(Class callbackType, - Collection callbackInstances, A argument, - Object... additionalArguments) { + public static Callbacks callbacks(Class callbackType, Collection callbackInstances, + A argument, Object... additionalArguments) { Assert.notNull(callbackType, "CallbackType must not be null"); Assert.notNull(callbackInstances, "CallbackInstances must not be null"); - return new Callbacks<>(callbackType, callbackInstances, argument, - additionalArguments); + return new Callbacks<>(callbackType, callbackInstances, argument, additionalArguments); } /** @@ -113,8 +109,7 @@ public final class LambdaSafe { private Filter filter = new GenericTypeFilter<>(); - protected LambdaSafeCallback(Class callbackType, A argument, - Object[] additionalArguments) { + protected LambdaSafeCallback(Class callbackType, A argument, Object[] additionalArguments) { this.callbackType = callbackType; this.argument = argument; this.additionalArguments = additionalArguments; @@ -154,10 +149,8 @@ public final class LambdaSafe { return self(); } - protected final InvocationResult invoke(C callbackInstance, - Supplier supplier) { - if (this.filter.match(this.callbackType, callbackInstance, this.argument, - this.additionalArguments)) { + protected final InvocationResult invoke(C callbackInstance, Supplier supplier) { + if (this.filter.match(this.callbackType, callbackInstance, this.argument, this.additionalArguments)) { try { return InvocationResult.of(supplier.get()); } @@ -172,15 +165,12 @@ public final class LambdaSafe { } private boolean isLambdaGenericProblem(ClassCastException ex) { - return (ex.getMessage() == null - || startsWithArgumentClassName(ex.getMessage())); + return (ex.getMessage() == null || startsWithArgumentClassName(ex.getMessage())); } private boolean startsWithArgumentClassName(String message) { - Predicate startsWith = (argument) -> startsWithArgumentClassName( - message, argument); - return startsWith.test(this.argument) - || Stream.of(this.additionalArguments).anyMatch(startsWith); + Predicate startsWith = (argument) -> startsWithArgumentClassName(message, argument); + return startsWith.test(this.argument) || Stream.of(this.additionalArguments).anyMatch(startsWith); } private boolean startsWithArgumentClassName(String message, Object argument) { @@ -200,13 +190,11 @@ public final class LambdaSafe { // On Java 9, the message used to contain the module name: // "java.base/java.lang.String cannot be cast..." int moduleSeparatorIndex = message.indexOf('/'); - if (moduleSeparatorIndex != -1 && message.startsWith(argumentType.getName(), - moduleSeparatorIndex + 1)) { + if (moduleSeparatorIndex != -1 && message.startsWith(argumentType.getName(), moduleSeparatorIndex + 1)) { return true; } if (CLASS_GET_MODULE != null) { - Object module = ReflectionUtils.invokeMethod(CLASS_GET_MODULE, - argumentType); + Object module = ReflectionUtils.invokeMethod(CLASS_GET_MODULE, argumentType); Object moduleName = ReflectionUtils.invokeMethod(MODULE_GET_NAME, module); return message.startsWith(moduleName + "/" + argumentType.getName()); } @@ -215,10 +203,9 @@ public final class LambdaSafe { private void logNonMatchingType(C callback, ClassCastException ex) { if (this.logger.isDebugEnabled()) { - Class expectedType = ResolvableType.forClass(this.callbackType) - .resolveGeneric(); - String expectedTypeName = (expectedType != null) - ? ClassUtils.getShortName(expectedType) + " type" : "type"; + Class expectedType = ResolvableType.forClass(this.callbackType).resolveGeneric(); + String expectedTypeName = (expectedType != null) ? ClassUtils.getShortName(expectedType) + " type" + : "type"; String message = "Non-matching " + expectedTypeName + " for callback " + ClassUtils.getShortName(this.callbackType) + ": " + callback; this.logger.debug(message, ex); @@ -238,13 +225,11 @@ public final class LambdaSafe { * @param the callback type * @param the primary argument type */ - public static final class Callback - extends LambdaSafeCallback> { + public static final class Callback extends LambdaSafeCallback> { private final C callbackInstance; - private Callback(Class callbackType, C callbackInstance, A argument, - Object[] additionalArguments) { + private Callback(Class callbackType, C callbackInstance, A argument, Object[] additionalArguments) { super(callbackType, argument, additionalArguments); this.callbackInstance = callbackInstance; } @@ -268,8 +253,7 @@ public final class LambdaSafe { * if the callback was not invoked) */ public InvocationResult invokeAnd(Function invoker) { - return invoke(this.callbackInstance, - () -> invoker.apply(this.callbackInstance)); + return invoke(this.callbackInstance, () -> invoker.apply(this.callbackInstance)); } } @@ -280,13 +264,11 @@ public final class LambdaSafe { * @param the callback type * @param the primary argument type */ - public static final class Callbacks - extends LambdaSafeCallback> { + public static final class Callbacks extends LambdaSafeCallback> { private final Collection callbackInstances; - private Callbacks(Class callbackType, - Collection callbackInstances, A argument, + private Callbacks(Class callbackType, Collection callbackInstances, A argument, Object[] additionalArguments) { super(callbackType, argument, additionalArguments); this.callbackInstances = callbackInstances; @@ -313,10 +295,10 @@ public final class LambdaSafe { * could be called) */ public Stream invokeAnd(Function invoker) { - Function> mapper = (callbackInstance) -> invoke( - callbackInstance, () -> invoker.apply(callbackInstance)); - return this.callbackInstances.stream().map(mapper) - .filter(InvocationResult::hasResult).map(InvocationResult::get); + Function> mapper = (callbackInstance) -> invoke(callbackInstance, + () -> invoker.apply(callbackInstance)); + return this.callbackInstances.stream().map(mapper).filter(InvocationResult::hasResult) + .map(InvocationResult::get); } } @@ -338,8 +320,7 @@ public final class LambdaSafe { * @param additionalArguments any additional arguments * @return if the callback matches and should be invoked */ - boolean match(Class callbackType, C callbackInstance, A argument, - Object[] additionalArguments); + boolean match(Class callbackType, C callbackInstance, A argument, Object[] additionalArguments); /** * Return a {@link Filter} that allows all callbacks to be invoked. @@ -348,8 +329,7 @@ public final class LambdaSafe { * @return an "allow all" filter */ static Filter allowAll() { - return (callbackType, callbackInstance, argument, - additionalArguments) -> true; + return (callbackType, callbackInstance, argument, additionalArguments) -> true; } } @@ -361,10 +341,8 @@ public final class LambdaSafe { private static class GenericTypeFilter implements Filter { @Override - public boolean match(Class callbackType, C callbackInstance, A argument, - Object[] additionalArguments) { - ResolvableType type = ResolvableType.forClass(callbackType, - callbackInstance.getClass()); + public boolean match(Class callbackType, C callbackInstance, A argument, Object[] additionalArguments) { + ResolvableType type = ResolvableType.forClass(callbackType, callbackInstance.getClass()); if (type.getGenerics().length == 1 && type.resolveGeneric() != null) { return type.resolveGeneric().isInstance(argument); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java index d0e75e4a028..2a214a58f94 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,16 +42,14 @@ public class MessageInterpolatorFactory implements ObjectFactory fallbacks = new LinkedHashSet<>(); - fallbacks.add("org.hibernate.validator.messageinterpolation" - + ".ParameterMessageInterpolator"); + fallbacks.add("org.hibernate.validator.messageinterpolation" + ".ParameterMessageInterpolator"); FALLBACKS = Collections.unmodifiableSet(fallbacks); } @Override public MessageInterpolator getObject() throws BeansException { try { - return Validation.byDefaultProvider().configure() - .getDefaultMessageInterpolator(); + return Validation.byDefaultProvider().configure().getDefaultMessageInterpolator(); } catch (ValidationException ex) { MessageInterpolator fallback = getFallback(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactory.java index 016a2cb0fab..8e58a9ad083 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactory.java @@ -31,8 +31,7 @@ import org.springframework.util.Assert; * * @author Dmytro Nosan */ -class BasicAuthenticationClientHttpRequestFactory - extends AbstractClientHttpRequestFactoryWrapper { +class BasicAuthenticationClientHttpRequestFactory extends AbstractClientHttpRequestFactoryWrapper { private final BasicAuthentication authentication; @@ -44,8 +43,8 @@ class BasicAuthenticationClientHttpRequestFactory } @Override - protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, - ClientHttpRequestFactory requestFactory) throws IOException { + protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory) + throws IOException { ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod); this.authentication.applyTo(request); return request; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySupplier.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySupplier.java index c2b9756cf31..c87fd521d30 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySupplier.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySupplier.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.util.ClassUtils; * @author Stephane Nicoll * @since 2.1.0 */ -public class ClientHttpRequestFactorySupplier - implements Supplier { +public class ClientHttpRequestFactorySupplier implements Supplier { private static final Map REQUEST_FACTORY_CANDIDATES; @@ -42,21 +41,17 @@ public class ClientHttpRequestFactorySupplier Map candidates = new LinkedHashMap<>(); candidates.put("org.apache.http.client.HttpClient", "org.springframework.http.client.HttpComponentsClientHttpRequestFactory"); - candidates.put("okhttp3.OkHttpClient", - "org.springframework.http.client.OkHttp3ClientHttpRequestFactory"); + candidates.put("okhttp3.OkHttpClient", "org.springframework.http.client.OkHttp3ClientHttpRequestFactory"); REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates); } @Override public ClientHttpRequestFactory get() { - for (Map.Entry candidate : REQUEST_FACTORY_CANDIDATES - .entrySet()) { + for (Map.Entry candidate : REQUEST_FACTORY_CANDIDATES.entrySet()) { ClassLoader classLoader = getClass().getClassLoader(); if (ClassUtils.isPresent(candidate.getKey(), classLoader)) { - Class factoryClass = ClassUtils.resolveClassName(candidate.getValue(), - classLoader); - return (ClientHttpRequestFactory) BeanUtils - .instantiateClass(factoryClass); + Class factoryClass = ClassUtils.resolveClassName(candidate.getValue(), classLoader); + return (ClientHttpRequestFactory) BeanUtils.instantiateClass(factoryClass); } } return new SimpleClientHttpRequestFactory(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java index a387722833d..75bca79ff90 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java @@ -102,20 +102,16 @@ public class RestTemplateBuilder { this.uriTemplateHandler = null; this.errorHandler = null; this.basicAuthentication = null; - this.restTemplateCustomizers = Collections - .unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); + this.restTemplateCustomizers = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); this.requestFactoryCustomizer = new RequestFactoryCustomizer(); this.interceptors = Collections.emptySet(); } private RestTemplateBuilder(boolean detectRequestFactory, String rootUri, - Set> messageConverters, - Supplier requestFactorySupplier, + Set> messageConverters, Supplier requestFactorySupplier, UriTemplateHandler uriTemplateHandler, ResponseErrorHandler errorHandler, - BasicAuthentication basicAuthentication, - Set restTemplateCustomizers, - RequestFactoryCustomizer requestFactoryCustomizer, - Set interceptors) { + BasicAuthentication basicAuthentication, Set restTemplateCustomizers, + RequestFactoryCustomizer requestFactoryCustomizer, Set interceptors) { this.detectRequestFactory = detectRequestFactory; this.rootUri = rootUri; this.messageConverters = messageConverters; @@ -136,11 +132,9 @@ public class RestTemplateBuilder { * @return a new builder instance */ public RestTemplateBuilder detectRequestFactory(boolean detectRequestFactory) { - return new RestTemplateBuilder(detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, this.requestFactoryCustomizer, - this.interceptors); + return new RestTemplateBuilder(detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -150,11 +144,9 @@ public class RestTemplateBuilder { * @return a new builder instance */ public RestTemplateBuilder rootUri(String rootUri) { - return new RestTemplateBuilder(this.detectRequestFactory, rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, this.requestFactoryCustomizer, - this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -166,8 +158,7 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalMessageConverters(HttpMessageConverter...) */ - public RestTemplateBuilder messageConverters( - HttpMessageConverter... messageConverters) { + public RestTemplateBuilder messageConverters(HttpMessageConverter... messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return messageConverters(Arrays.asList(messageConverters)); } @@ -181,15 +172,12 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalMessageConverters(HttpMessageConverter...) */ - public RestTemplateBuilder messageConverters( - Collection> messageConverters) { + public RestTemplateBuilder messageConverters(Collection> messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - Collections.unmodifiableSet( - new LinkedHashSet>(messageConverters)), - this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, - this.basicAuthentication, this.restTemplateCustomizers, - this.requestFactoryCustomizer, this.interceptors); + Collections.unmodifiableSet(new LinkedHashSet>(messageConverters)), + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -200,8 +188,7 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #messageConverters(HttpMessageConverter...) */ - public RestTemplateBuilder additionalMessageConverters( - HttpMessageConverter... messageConverters) { + public RestTemplateBuilder additionalMessageConverters(HttpMessageConverter... messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return additionalMessageConverters(Arrays.asList(messageConverters)); } @@ -218,9 +205,8 @@ public class RestTemplateBuilder { Collection> messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - append(this.messageConverters, messageConverters), - this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, - this.basicAuthentication, this.restTemplateCustomizers, + append(this.messageConverters, messageConverters), this.requestFactorySupplier, this.uriTemplateHandler, + this.errorHandler, this.basicAuthentication, this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } @@ -233,11 +219,9 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder defaultMessageConverters() { return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - Collections.unmodifiableSet( - new LinkedHashSet<>(new RestTemplate().getMessageConverters())), - this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, - this.basicAuthentication, this.restTemplateCustomizers, - this.requestFactoryCustomizer, this.interceptors); + Collections.unmodifiableSet(new LinkedHashSet<>(new RestTemplate().getMessageConverters())), + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -249,8 +233,7 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #additionalInterceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder interceptors( - ClientHttpRequestInterceptor... interceptors) { + public RestTemplateBuilder interceptors(ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return interceptors(Arrays.asList(interceptors)); } @@ -264,12 +247,10 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #additionalInterceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder interceptors( - Collection interceptors) { + public RestTemplateBuilder interceptors(Collection interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.restTemplateCustomizers, this.requestFactoryCustomizer, Collections.unmodifiableSet(new LinkedHashSet<>(interceptors))); } @@ -282,8 +263,7 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #interceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder additionalInterceptors( - ClientHttpRequestInterceptor... interceptors) { + public RestTemplateBuilder additionalInterceptors(ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return additionalInterceptors(Arrays.asList(interceptors)); } @@ -296,14 +276,11 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #interceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder additionalInterceptors( - Collection interceptors) { + public RestTemplateBuilder additionalInterceptors(Collection interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, this.requestFactoryCustomizer, - append(this.interceptors, interceptors)); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, append(this.interceptors, interceptors)); } /** @@ -312,14 +289,12 @@ public class RestTemplateBuilder { * @param requestFactory the request factory to use * @return a new builder instance */ - public RestTemplateBuilder requestFactory( - Class requestFactory) { + public RestTemplateBuilder requestFactory(Class requestFactory) { Assert.notNull(requestFactory, "RequestFactory must not be null"); return requestFactory(() -> createRequestFactory(requestFactory)); } - private ClientHttpRequestFactory createRequestFactory( - Class requestFactory) { + private ClientHttpRequestFactory createRequestFactory(Class requestFactory) { try { Constructor constructor = requestFactory.getDeclaredConstructor(); constructor.setAccessible(true); @@ -337,14 +312,11 @@ public class RestTemplateBuilder { * @return a new builder instance * @since 2.0.0 */ - public RestTemplateBuilder requestFactory( - Supplier requestFactorySupplier) { - Assert.notNull(requestFactorySupplier, - "RequestFactory Supplier must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, requestFactorySupplier, this.uriTemplateHandler, - this.errorHandler, this.basicAuthentication, this.restTemplateCustomizers, - this.requestFactoryCustomizer, this.interceptors); + public RestTemplateBuilder requestFactory(Supplier requestFactorySupplier) { + Assert.notNull(requestFactorySupplier, "RequestFactory Supplier must not be null"); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -355,10 +327,9 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder uriTemplateHandler(UriTemplateHandler uriTemplateHandler) { Assert.notNull(uriTemplateHandler, "UriTemplateHandler must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, uriTemplateHandler, - this.errorHandler, this.basicAuthentication, this.restTemplateCustomizers, - this.requestFactoryCustomizer, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -369,11 +340,9 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder errorHandler(ResponseErrorHandler errorHandler) { Assert.notNull(errorHandler, "ErrorHandler must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, this.requestFactoryCustomizer, - this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -399,15 +368,11 @@ public class RestTemplateBuilder { * @since 2.2.0 * @see #basicAuthentication(String, String) */ - public RestTemplateBuilder basicAuthentication(String username, String password, - Charset charset) { - BasicAuthentication basicAuthentication = new BasicAuthentication(username, - password, charset); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, basicAuthentication, - this.restTemplateCustomizers, this.requestFactoryCustomizer, - this.interceptors); + public RestTemplateBuilder basicAuthentication(String username, String password, Charset charset) { + BasicAuthentication basicAuthentication = new BasicAuthentication(username, password, charset); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer, this.interceptors); } /** @@ -419,10 +384,8 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder customizers( - RestTemplateCustomizer... restTemplateCustomizers) { - Assert.notNull(restTemplateCustomizers, - "RestTemplateCustomizers must not be null"); + public RestTemplateBuilder customizers(RestTemplateCustomizer... restTemplateCustomizers) { + Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return customizers(Arrays.asList(restTemplateCustomizers)); } @@ -435,15 +398,11 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder customizers( - Collection restTemplateCustomizers) { - Assert.notNull(restTemplateCustomizers, - "RestTemplateCustomizers must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - Collections.unmodifiableSet(new LinkedHashSet( - restTemplateCustomizers)), + public RestTemplateBuilder customizers(Collection restTemplateCustomizers) { + Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + Collections.unmodifiableSet(new LinkedHashSet(restTemplateCustomizers)), this.requestFactoryCustomizer, this.interceptors); } @@ -455,10 +414,8 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder additionalCustomizers( - RestTemplateCustomizer... restTemplateCustomizers) { - Assert.notNull(restTemplateCustomizers, - "RestTemplateCustomizers must not be null"); + public RestTemplateBuilder additionalCustomizers(RestTemplateCustomizer... restTemplateCustomizers) { + Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return additionalCustomizers(Arrays.asList(restTemplateCustomizers)); } @@ -470,14 +427,11 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder additionalCustomizers( - Collection customizers) { + public RestTemplateBuilder additionalCustomizers(Collection customizers) { Assert.notNull(customizers, "RestTemplateCustomizers must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - append(this.restTemplateCustomizers, customizers), - this.requestFactoryCustomizer, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + append(this.restTemplateCustomizers, customizers), this.requestFactoryCustomizer, this.interceptors); } /** @@ -487,11 +441,9 @@ public class RestTemplateBuilder { * @since 2.1.0 */ public RestTemplateBuilder setConnectTimeout(Duration connectTimeout) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, - this.requestFactoryCustomizer.connectTimeout(connectTimeout), + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer.connectTimeout(connectTimeout), this.interceptors); } @@ -502,11 +454,9 @@ public class RestTemplateBuilder { * @since 2.1.0 */ public RestTemplateBuilder setReadTimeout(Duration readTimeout) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, - this.requestFactoryCustomizer.readTimeout(readTimeout), + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer.readTimeout(readTimeout), this.interceptors); } @@ -520,11 +470,9 @@ public class RestTemplateBuilder { * @see HttpComponentsClientHttpRequestFactory#setBufferRequestBody(boolean) */ public RestTemplateBuilder setBufferRequestBody(boolean bufferRequestBody) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, - this.restTemplateCustomizers, - this.requestFactoryCustomizer.bufferRequestBody(bufferRequestBody), + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, + this.restTemplateCustomizers, this.requestFactoryCustomizer.bufferRequestBody(bufferRequestBody), this.interceptors); } @@ -618,8 +566,8 @@ public class RestTemplateBuilder { restTemplate.getInterceptors().clear(); } ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory(); - restTemplate.setRequestFactory(new BasicAuthenticationClientHttpRequestFactory( - this.basicAuthentication, requestFactory)); + restTemplate.setRequestFactory( + new BasicAuthenticationClientHttpRequestFactory(this.basicAuthentication, requestFactory)); // Restore the original interceptors if (interceptors != null) { restTemplate.getInterceptors().addAll(interceptors); @@ -632,8 +580,7 @@ public class RestTemplateBuilder { return Collections.unmodifiableSet(result); } - private static class RequestFactoryCustomizer - implements Consumer { + private static class RequestFactoryCustomizer implements Consumer { private final Duration connectTimeout; @@ -645,32 +592,27 @@ public class RestTemplateBuilder { this(null, null, null); } - private RequestFactoryCustomizer(Duration connectTimeout, Duration readTimeout, - Boolean bufferRequestBody) { + private RequestFactoryCustomizer(Duration connectTimeout, Duration readTimeout, Boolean bufferRequestBody) { this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; this.bufferRequestBody = bufferRequestBody; } public RequestFactoryCustomizer connectTimeout(Duration connectTimeout) { - return new RequestFactoryCustomizer(connectTimeout, this.readTimeout, - this.bufferRequestBody); + return new RequestFactoryCustomizer(connectTimeout, this.readTimeout, this.bufferRequestBody); } public RequestFactoryCustomizer readTimeout(Duration readTimeout) { - return new RequestFactoryCustomizer(this.connectTimeout, readTimeout, - this.bufferRequestBody); + return new RequestFactoryCustomizer(this.connectTimeout, readTimeout, this.bufferRequestBody); } public RequestFactoryCustomizer bufferRequestBody(boolean bufferRequestBody) { - return new RequestFactoryCustomizer(this.connectTimeout, this.readTimeout, - bufferRequestBody); + return new RequestFactoryCustomizer(this.connectTimeout, this.readTimeout, bufferRequestBody); } @Override public void accept(ClientHttpRequestFactory requestFactory) { - ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary( - requestFactory); + ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary(requestFactory); if (this.connectTimeout != null) { setConnectTimeout(unwrappedRequestFactory); } @@ -682,18 +624,16 @@ public class RestTemplateBuilder { } } - private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary( - ClientHttpRequestFactory requestFactory) { + private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary(ClientHttpRequestFactory requestFactory) { if (!(requestFactory instanceof AbstractClientHttpRequestFactoryWrapper)) { return requestFactory; } - Field field = ReflectionUtils.findField( - AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); + Field field = ReflectionUtils.findField(AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); ReflectionUtils.makeAccessible(field); ClientHttpRequestFactory unwrappedRequestFactory = requestFactory; while (unwrappedRequestFactory instanceof AbstractClientHttpRequestFactoryWrapper) { - unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils - .getField(field, unwrappedRequestFactory); + unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils.getField(field, + unwrappedRequestFactory); } return unwrappedRequestFactory; } @@ -715,10 +655,8 @@ public class RestTemplateBuilder { invoke(factory, method, this.bufferRequestBody); } - private Method findMethod(ClientHttpRequestFactory requestFactory, - String methodName, Class... parameters) { - Method method = ReflectionUtils.findMethod(requestFactory.getClass(), - methodName, parameters); + private Method findMethod(ClientHttpRequestFactory requestFactory, String methodName, Class... parameters) { + Method method = ReflectionUtils.findMethod(requestFactory.getClass(), methodName, parameters); if (method != null) { return method; } @@ -726,8 +664,7 @@ public class RestTemplateBuilder { + " does not have a suitable " + methodName + " method"); } - private void invoke(ClientHttpRequestFactory requestFactory, Method method, - Object... parameters) { + private void invoke(ClientHttpRequestFactory requestFactory, Method method, Object... parameters) { ReflectionUtils.invokeMethod(method, requestFactory, parameters); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java index 79066a74fa3..ac684b828e5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,11 +90,9 @@ public class RootUriTemplateHandler implements UriTemplateHandler { * @param rootUri the root URI * @return the added {@link RootUriTemplateHandler}. */ - public static RootUriTemplateHandler addTo(RestTemplate restTemplate, - String rootUri) { + public static RootUriTemplateHandler addTo(RestTemplate restTemplate, String rootUri) { Assert.notNull(restTemplate, "RestTemplate must not be null"); - RootUriTemplateHandler handler = new RootUriTemplateHandler(rootUri, - restTemplate.getUriTemplateHandler()); + RootUriTemplateHandler handler = new RootUriTemplateHandler(rootUri, restTemplate.getUriTemplateHandler()); restTemplate.setUriTemplateHandler(handler); return handler; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java index ec45645f393..3914964b25f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,8 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @since 2.0.0 */ -public class ServerPortInfoApplicationContextInitializer - implements ApplicationContextInitializer, - ApplicationListener { +public class ServerPortInfoApplicationContextInitializer implements + ApplicationContextInitializer, ApplicationListener { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -61,8 +60,7 @@ public class ServerPortInfoApplicationContextInitializer @Override public void onApplicationEvent(WebServerInitializedEvent event) { String propertyName = "local." + getName(event.getApplicationContext()) + ".port"; - setPortProperty(event.getApplicationContext(), propertyName, - event.getWebServer().getPort()); + setPortProperty(event.getApplicationContext(), propertyName, event.getWebServer().getPort()); } private String getName(WebServerApplicationContext context) { @@ -70,11 +68,9 @@ public class ServerPortInfoApplicationContextInitializer return StringUtils.hasText(name) ? name : "server"; } - private void setPortProperty(ApplicationContext context, String propertyName, - int port) { + private void setPortProperty(ApplicationContext context, String propertyName, int port) { if (context instanceof ConfigurableApplicationContext) { - setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(), - propertyName, port); + setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(), propertyName, port); } if (context.getParent() != null) { setPortProperty(context.getParent(), propertyName, port); @@ -82,8 +78,7 @@ public class ServerPortInfoApplicationContextInitializer } @SuppressWarnings("unchecked") - private void setPortProperty(ConfigurableEnvironment environment, String propertyName, - int port) { + private void setPortProperty(ConfigurableEnvironment environment, String propertyName, int port) { MutablePropertySources sources = environment.getPropertySources(); PropertySource source = sources.get("server.ports"); if (source == null) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java index b24292fcc7e..14b1c529712 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ import org.springframework.util.StringUtils; * @author Andy Wilkinson * @since 2.0.0 */ -public class WebServerPortFileWriter - implements ApplicationListener { +public class WebServerPortFileWriter implements ApplicationListener { private static final String DEFAULT_FILE_NAME = "application.port"; @@ -125,16 +124,14 @@ public class WebServerPortFileWriter private String getServerNamespace(ApplicationContext applicationContext) { if (applicationContext instanceof WebServerApplicationContext) { - return ((WebServerApplicationContext) applicationContext) - .getServerNamespace(); + return ((WebServerApplicationContext) applicationContext).getServerNamespace(); } return null; } private boolean isUpperCase(String name) { for (int i = 0; i < name.length(); i++) { - if (Character.isLetter(name.charAt(i)) - && !Character.isUpperCase(name.charAt(i))) { + if (Character.isLetter(name.charAt(i)) && !Character.isUpperCase(name.charAt(i))) { return false; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java index c7d05ac1910..a3c60ba856a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,11 +33,10 @@ class ForwardHeadersCustomizer implements JettyServerCustomizer { public void customize(Server server) { ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer(); for (Connector connector : server.getConnectors()) { - for (ConnectionFactory connectionFactory : connector - .getConnectionFactories()) { + for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - ((HttpConfiguration.ConnectionFactory) connectionFactory) - .getHttpConfiguration().addCustomizer(customizer); + ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() + .addCustomizer(customizer); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JasperInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JasperInitializer.java index 5b72d49812d..3d2cd8e60ee 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JasperInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JasperInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.util.ClassUtils; */ class JasperInitializer extends AbstractLifeCycle { - private static final String[] INITIALIZER_CLASSES = { - "org.eclipse.jetty.apache.jsp.JettyJasperInitializer", + private static final String[] INITIALIZER_CLASSES = { "org.eclipse.jetty.apache.jsp.JettyJasperInitializer", "org.apache.jasper.servlet.JasperInitializer" }; private final WebAppContext context; @@ -70,8 +69,7 @@ class JasperInitializer extends AbstractLifeCycle { if (this.initializer == null) { return; } - if (ClassUtils.isPresent( - "org.apache.catalina.webresources.TomcatURLStreamHandlerFactory", + if (ClassUtils.isPresent("org.apache.catalina.webresources.TomcatURLStreamHandlerFactory", getClass().getClassLoader())) { TomcatURLStreamHandlerFactory.register(); } @@ -135,8 +133,7 @@ class JasperInitializer extends AbstractLifeCycle { String path = "jar:" + spec.substring("war:".length()); int separator = path.indexOf("*/"); if (separator >= 0) { - path = path.substring(0, separator) + "!/" - + path.substring(separator + 2); + path = path.substring(0, separator) + "!/" + path.substring(separator + 2); } setURL(u, u.getProtocol(), "", -1, null, null, path, null, null); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyEmbeddedErrorHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyEmbeddedErrorHandler.java index b859a1d834c..1a96431bad3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyEmbeddedErrorHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyEmbeddedErrorHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,11 +45,10 @@ class JettyEmbeddedErrorHandler extends ErrorHandler { } @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException { String method = request.getMethod(); - if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) - && !HttpMethod.HEAD.is(method)) { + if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method)) { request = new ErrorHttpServletRequest(request); } this.delegate.handle(target, baseRequest, request, response); @@ -65,8 +64,7 @@ class JettyEmbeddedErrorHandler extends ErrorHandler { @Override public String getMethod() { - return (this.simulateGetMethod ? HttpMethod.GET.toString() - : super.getMethod()); + return (this.simulateGetMethod ? HttpMethod.GET.toString() : super.getMethod()); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyHandlerWrappers.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyHandlerWrappers.java index f12c241d6d9..9f705b535f7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyHandlerWrappers.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyHandlerWrappers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,8 @@ final class JettyHandlerWrappers { } @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { if (!response.getHeaderNames().contains(SERVER_HEADER)) { response.setHeader(SERVER_HEADER, this.value); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java index 7bd6befd5de..53bf14dcdc3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ import org.springframework.util.StringUtils; public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFactory implements ConfigurableJettyWebServerFactory { - private static final Log logger = LogFactory - .getLog(JettyReactiveWebServerFactory.class); + private static final Log logger = LogFactory.getLog(JettyReactiveWebServerFactory.class); /** * The number of acceptor threads to use. @@ -118,8 +117,7 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact * before it is started. Calling this method will replace any existing customizers. * @param customizers the Jetty customizers to apply */ - public void setServerCustomizers( - Collection customizers) { + public void setServerCustomizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.jettyServerCustomizers = new ArrayList<>(customizers); } @@ -175,12 +173,10 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); - ServletContextHandler contextHandler = new ServletContextHandler(server, "", - false, false); + ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); - JettyReactiveWebServerFactory.logger - .info("Server initialized with port: " + port); + JettyReactiveWebServerFactory.logger.info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } @@ -197,9 +193,8 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact ServerConnector connector; JettyResourceFactory resourceFactory = getResourceFactory(); if (resourceFactory != null) { - connector = new ServerConnector(server, resourceFactory.getExecutor(), - resourceFactory.getScheduler(), resourceFactory.getByteBufferPool(), - this.acceptors, this.selectors, new HttpConnectionFactory()); + connector = new ServerConnector(server, resourceFactory.getExecutor(), resourceFactory.getScheduler(), + resourceFactory.getByteBufferPool(), this.acceptors, this.selectors, new HttpConnectionFactory()); } else { connector = new ServerConnector(server, this.acceptors, this.selectors); @@ -208,8 +203,8 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact connector.setPort(address.getPort()); for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - ((HttpConfiguration.ConnectionFactory) connectionFactory) - .getHttpConfiguration().setSendServerVersion(false); + ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() + .setSendServerVersion(false); } } return connector; @@ -217,12 +212,10 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact private Handler addHandlerWrappers(Handler handler) { if (getCompression() != null && getCompression().getEnabled()) { - handler = applyWrapper(handler, - JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); + handler = applyWrapper(handler, JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); } if (StringUtils.hasText(getServerHeader())) { - handler = applyWrapper(handler, JettyHandlerWrappers - .createServerHeaderHandlerWrapper(getServerHeader())); + handler = applyWrapper(handler, JettyHandlerWrappers.createServerHeaderHandlerWrapper(getServerHeader())); } return handler; } @@ -233,8 +226,7 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact } private void customizeSsl(Server server, InetSocketAddress address) { - new SslServerCustomizer(address, getSsl(), getSslStoreProvider(), getHttp2()) - .customize(server); + new SslServerCustomizer(address, getSsl(), getSslStoreProvider(), getHttp2()).customize(server); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java index 434740feac1..8f7b2ca1246 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -160,14 +160,13 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor } private AbstractConnector createConnector(InetSocketAddress address, Server server) { - ServerConnector connector = new ServerConnector(server, this.acceptors, - this.selectors); + ServerConnector connector = new ServerConnector(server, this.acceptors, this.selectors); connector.setHost(address.getHostString()); connector.setPort(address.getPort()); for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - ((HttpConfiguration.ConnectionFactory) connectionFactory) - .getHttpConfiguration().setSendServerVersion(false); + ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() + .setSendServerVersion(false); } } return connector; @@ -175,12 +174,10 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor private Handler addHandlerWrappers(Handler handler) { if (getCompression() != null && getCompression().getEnabled()) { - handler = applyWrapper(handler, - JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); + handler = applyWrapper(handler, JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); } if (StringUtils.hasText(getServerHeader())) { - handler = applyWrapper(handler, JettyHandlerWrappers - .createServerHeaderHandlerWrapper(getServerHeader())); + handler = applyWrapper(handler, JettyHandlerWrappers.createServerHeaderHandlerWrapper(getServerHeader())); } return handler; } @@ -191,8 +188,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor } private void customizeSsl(Server server, InetSocketAddress address) { - new SslServerCustomizer(address, getSsl(), getSslStoreProvider(), getHttp2()) - .customize(server); + new SslServerCustomizer(address, getSsl(), getSslStoreProvider(), getHttp2()).customize(server); } /** @@ -200,8 +196,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor * @param context the context to configure * @param initializers the set of initializers to apply */ - protected final void configureWebAppContext(WebAppContext context, - ServletContextInitializer... initializers) { + protected final void configureWebAppContext(WebAppContext context, ServletContextInitializer... initializers) { Assert.notNull(context, "Context must not be null"); context.setTempDirectory(getTempDirectory()); if (this.resourceLoader != null) { @@ -220,8 +215,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor } addLocaleMappings(context); ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); - Configuration[] configurations = getWebAppContextConfigurations(context, - initializersToUse); + Configuration[] configurations = getWebAppContextConfigurations(context, initializersToUse); context.setConfigurations(configurations); context.setThrowUnavailableOnStartupException(true); configureSession(context); @@ -231,8 +225,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor private void configureSession(WebAppContext context) { SessionHandler handler = context.getSessionHandler(); Duration sessionTimeout = getSession().getTimeout(); - handler.setMaxInactiveInterval( - isNegative(sessionTimeout) ? -1 : (int) sessionTimeout.getSeconds()); + handler.setMaxInactiveInterval(isNegative(sessionTimeout) ? -1 : (int) sessionTimeout.getSeconds()); if (getSession().isPersistent()) { DefaultSessionCache cache = new DefaultSessionCache(handler); FileSessionDataStore store = new FileSessionDataStore(); @@ -247,8 +240,8 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor } private void addLocaleMappings(WebAppContext context) { - getLocaleCharsetMappings().forEach((locale, charset) -> context - .addLocaleEncoding(locale.toString(), charset.toString())); + getLocaleCharsetMappings() + .forEach((locale, charset) -> context.addLocaleEncoding(locale.toString(), charset.toString())); } private File getTempDirectory() { @@ -261,19 +254,16 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor File docBase = (root != null) ? root : createTempDir("jetty-docbase"); try { List resources = new ArrayList<>(); - Resource rootResource = (docBase.isDirectory() - ? Resource.newResource(docBase.getCanonicalFile()) + Resource rootResource = (docBase.isDirectory() ? Resource.newResource(docBase.getCanonicalFile()) : JarResource.newJarResource(Resource.newResource(docBase))); - resources.add((root != null) ? new LoaderHidingResource(rootResource) - : rootResource); + resources.add((root != null) ? new LoaderHidingResource(rootResource) : rootResource); for (URL resourceJarUrl : this.getUrlsOfJarsWithMetaInfResources()) { Resource resource = createResource(resourceJarUrl); if (resource.exists() && resource.isDirectory()) { resources.add(resource); } } - handler.setBaseResource( - new ResourceCollection(resources.toArray(new Resource[0]))); + handler.setBaseResource(new ResourceCollection(resources.toArray(new Resource[0]))); } catch (Exception ex) { throw new IllegalStateException(ex); @@ -333,8 +323,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor protected Configuration[] getWebAppContextConfigurations(WebAppContext webAppContext, ServletContextInitializer... initializers) { List configurations = new ArrayList<>(); - configurations.add( - getServletContextInitializerConfiguration(webAppContext, initializers)); + configurations.add(getServletContextInitializerConfiguration(webAppContext, initializers)); configurations.addAll(getConfigurations()); configurations.add(getErrorPageConfiguration()); configurations.add(getMimeTypeConfiguration()); @@ -369,8 +358,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor public void configure(WebAppContext context) throws Exception { MimeTypes mimeTypes = context.getMimeTypes(); for (MimeMappings.Mapping mapping : getMimeMappings()) { - mimeTypes.addMimeMapping(mapping.getExtension(), - mapping.getMimeType()); + mimeTypes.addMimeMapping(mapping.getExtension(), mapping.getMimeType()); } } @@ -385,8 +373,8 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor * @param initializers the {@link ServletContextInitializer}s to apply * @return the {@link Configuration} instance */ - protected Configuration getServletContextInitializerConfiguration( - WebAppContext webAppContext, ServletContextInitializer... initializers) { + protected Configuration getServletContextInitializerConfiguration(WebAppContext webAppContext, + ServletContextInitializer... initializers) { return new ServletContextInitializerConfiguration(initializers); } @@ -435,8 +423,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor * before it is started. Calling this method will replace any existing customizers. * @param customizers the Jetty customizers to apply */ - public void setServerCustomizers( - Collection customizers) { + public void setServerCustomizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.jettyServerCustomizers = new ArrayList<>(customizers); } @@ -503,23 +490,19 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor this.threadPool = threadPool; } - private void addJettyErrorPages(ErrorHandler errorHandler, - Collection errorPages) { + private void addJettyErrorPages(ErrorHandler errorHandler, Collection errorPages) { if (errorHandler instanceof ErrorPageErrorHandler) { ErrorPageErrorHandler handler = (ErrorPageErrorHandler) errorHandler; for (ErrorPage errorPage : errorPages) { if (errorPage.isGlobal()) { - handler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, - errorPage.getPath()); + handler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, errorPage.getPath()); } else { if (errorPage.getExceptionName() != null) { - handler.addErrorPage(errorPage.getExceptionName(), - errorPage.getPath()); + handler.addErrorPage(errorPage.getExceptionName(), errorPage.getPath()); } else { - handler.addErrorPage(errorPage.getStatusCode(), - errorPage.getPath()); + handler.addErrorPage(errorPage.getStatusCode(), errorPage.getPath()); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java index 2f878492a55..e27fffd04dd 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,8 +97,8 @@ public class JettyWebServer implements WebServer { @Override protected void doStart() throws Exception { for (Connector connector : JettyWebServer.this.connectors) { - Assert.state(connector.isStopped(), () -> "Connector " - + connector + " has been started prematurely"); + Assert.state(connector.isStopped(), + () -> "Connector " + connector + " has been started prematurely"); } JettyWebServer.this.server.setConnectors(null); } @@ -111,8 +111,7 @@ public class JettyWebServer implements WebServer { catch (Throwable ex) { // Ensure process isn't left running stopSilently(); - throw new WebServerException("Unable to start embedded Jetty web server", - ex); + throw new WebServerException("Unable to start embedded Jetty web server", ex); } } } @@ -147,17 +146,15 @@ public class JettyWebServer implements WebServer { connector.start(); } catch (IOException ex) { - if (connector instanceof NetworkConnector - && findBindException(ex) != null) { - throw new PortInUseException( - ((NetworkConnector) connector).getPort()); + if (connector instanceof NetworkConnector && findBindException(ex) != null) { + throw new PortInUseException(((NetworkConnector) connector).getPort()); } throw ex; } } this.started = true; - logger.info("Jetty started on port(s) " + getActualPortsDescription() - + " with context path '" + getContextPath() + "'"); + logger.info("Jetty started on port(s) " + getActualPortsDescription() + " with context path '" + + getContextPath() + "'"); } catch (WebServerException ex) { stopSilently(); @@ -194,9 +191,8 @@ public class JettyWebServer implements WebServer { private Integer getLocalPort(Connector connector) { try { // Jetty 9 internals are different, but the method name is the same - return (Integer) ReflectionUtils.invokeMethod( - ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), - connector); + return (Integer) ReflectionUtils + .invokeMethod(ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), connector); } catch (Exception ex) { logger.info("could not determine port ( " + ex.getMessage() + ")"); @@ -210,9 +206,8 @@ public class JettyWebServer implements WebServer { } private String getContextPath() { - return Arrays.stream(this.server.getHandlers()) - .filter(ContextHandler.class::isInstance).map(ContextHandler.class::cast) - .map(ContextHandler::getContextPath).collect(Collectors.joining(" ")); + return Arrays.stream(this.server.getHandlers()).filter(ContextHandler.class::isInstance) + .map(ContextHandler.class::cast).map(ContextHandler::getContextPath).collect(Collectors.joining(" ")); } private void handleDeferredInitialize(Handler... handlers) throws Exception { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ServletContextInitializerConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ServletContextInitializerConfiguration.java index e7f232089f3..a3a1a714c2a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ServletContextInitializerConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ServletContextInitializerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class ServletContextInitializerConfiguration extends AbstractConfiguratio * @param initializers the initializers that should be invoked * @since 1.2.1 */ - public ServletContextInitializerConfiguration( - ServletContextInitializer... initializers) { + public ServletContextInitializerConfiguration(ServletContextInitializer... initializers) { Assert.notNull(initializers, "Initializers must not be null"); this.initializers = initializers; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java index 41ffd8d416a..24b789ff5b4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java @@ -59,8 +59,7 @@ class SslServerCustomizer implements JettyServerCustomizer { private final Http2 http2; - SslServerCustomizer(InetSocketAddress address, Ssl ssl, - SslStoreProvider sslStoreProvider, Http2 http2) { + SslServerCustomizer(InetSocketAddress address, Ssl ssl, SslStoreProvider sslStoreProvider, Http2 http2) { this.address = address; this.ssl = ssl; this.sslStoreProvider = sslStoreProvider; @@ -71,65 +70,59 @@ class SslServerCustomizer implements JettyServerCustomizer { public void customize(Server server) { SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); configureSsl(sslContextFactory, this.ssl, this.sslStoreProvider); - ServerConnector connector = createConnector(server, sslContextFactory, - this.address); + ServerConnector connector = createConnector(server, sslContextFactory, this.address); server.setConnectors(new Connector[] { connector }); } - private ServerConnector createConnector(Server server, - SslContextFactory.Server sslContextFactory, InetSocketAddress address) { + private ServerConnector createConnector(Server server, SslContextFactory.Server sslContextFactory, + InetSocketAddress address) { HttpConfiguration config = new HttpConfiguration(); config.setSendServerVersion(false); config.setSecureScheme("https"); config.setSecurePort(address.getPort()); config.addCustomizer(new SecureRequestCustomizer()); - ServerConnector connector = createServerConnector(server, sslContextFactory, - config); + ServerConnector connector = createServerConnector(server, sslContextFactory, config); connector.setPort(address.getPort()); connector.setHost(address.getHostString()); return connector; } - private ServerConnector createServerConnector(Server server, - SslContextFactory.Server sslContextFactory, HttpConfiguration config) { + private ServerConnector createServerConnector(Server server, SslContextFactory.Server sslContextFactory, + HttpConfiguration config) { if (this.http2 == null || !this.http2.isEnabled()) { return createHttp11ServerConnector(server, config, sslContextFactory); } - Assert.state(isAlpnPresent(), () -> "The 'org.eclipse.jetty:jetty-alpn-server' " - + "dependency is required for HTTP/2 support."); - Assert.state(isConscryptPresent(), - () -> "The 'org.eclipse.jetty.http2:http2-server' and Conscrypt " - + "dependencies are required for HTTP/2 support."); + Assert.state(isAlpnPresent(), + () -> "The 'org.eclipse.jetty:jetty-alpn-server' " + "dependency is required for HTTP/2 support."); + Assert.state(isConscryptPresent(), () -> "The 'org.eclipse.jetty.http2:http2-server' and Conscrypt " + + "dependencies are required for HTTP/2 support."); return createHttp2ServerConnector(server, config, sslContextFactory); } - private ServerConnector createHttp11ServerConnector(Server server, - HttpConfiguration config, SslContextFactory.Server sslContextFactory) { + private ServerConnector createHttp11ServerConnector(Server server, HttpConfiguration config, + SslContextFactory.Server sslContextFactory) { HttpConnectionFactory connectionFactory = new HttpConnectionFactory(config); - SslConnectionFactory sslConnectionFactory = new SslConnectionFactory( - sslContextFactory, HttpVersion.HTTP_1_1.asString()); + SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, + HttpVersion.HTTP_1_1.asString()); return new ServerConnector(server, sslConnectionFactory, connectionFactory); } private boolean isAlpnPresent() { - return ClassUtils.isPresent( - "org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory", null); + return ClassUtils.isPresent("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory", null); } private boolean isConscryptPresent() { return ClassUtils.isPresent("org.conscrypt.Conscrypt", null); } - private ServerConnector createHttp2ServerConnector(Server server, - HttpConfiguration config, SslContextFactory.Server sslContextFactory) { + private ServerConnector createHttp2ServerConnector(Server server, HttpConfiguration config, + SslContextFactory.Server sslContextFactory) { HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(config); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); sslContextFactory.setProvider("Conscrypt"); - SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, - alpn.getProtocol()); - return new ServerConnector(server, ssl, alpn, h2, - new HttpConnectionFactory(config)); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); + return new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(config)); } /** @@ -138,8 +131,7 @@ class SslServerCustomizer implements JettyServerCustomizer { * @param ssl the ssl details. * @param sslStoreProvider the ssl store provider */ - protected void configureSsl(SslContextFactory.Server factory, Ssl ssl, - SslStoreProvider sslStoreProvider) { + protected void configureSsl(SslContextFactory.Server factory, Ssl ssl, SslStoreProvider sslStoreProvider) { factory.setProtocol(ssl.getProtocol()); configureSslClientAuth(factory, ssl); configureSslPasswords(factory, ssl); @@ -191,8 +183,7 @@ class SslServerCustomizer implements JettyServerCustomizer { factory.setKeyStoreResource(Resource.newResource(url)); } catch (Exception ex) { - throw new WebServerException( - "Could not load key store '" + ssl.getKeyStore() + "'", ex); + throw new WebServerException("Could not load key store '" + ssl.getKeyStore() + "'", ex); } if (ssl.getKeyStoreType() != null) { factory.setKeyStoreType(ssl.getKeyStoreType()); @@ -212,8 +203,7 @@ class SslServerCustomizer implements JettyServerCustomizer { factory.setTrustStoreResource(Resource.newResource(url)); } catch (IOException ex) { - throw new WebServerException( - "Could not find trust store '" + ssl.getTrustStore() + "'", ex); + throw new WebServerException("Could not find trust store '" + ssl.getTrustStore() + "'", ex); } } if (ssl.getTrustStoreType() != null) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java index 2563be716ee..b3e5015b059 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java @@ -42,8 +42,7 @@ import org.springframework.util.StringUtils; */ final class CompressionCustomizer implements NettyServerCustomizer { - private static final CompressionPredicate ALWAYS_COMPRESS = (request, - response) -> true; + private static final CompressionPredicate ALWAYS_COMPRESS = (request, response) -> true; private final Compression compression; @@ -54,11 +53,9 @@ final class CompressionCustomizer implements NettyServerCustomizer { @Override public HttpServer apply(HttpServer server) { if (!this.compression.getMinResponseSize().isNegative()) { - server = server - .compress((int) this.compression.getMinResponseSize().toBytes()); + server = server.compress((int) this.compression.getMinResponseSize().toBytes()); } - CompressionPredicate mimeTypes = getMimeTypesPredicate( - this.compression.getMimeTypes()); + CompressionPredicate mimeTypes = getMimeTypesPredicate(this.compression.getMimeTypes()); CompressionPredicate excludedUserAgents = getExcludedUserAgentsPredicate( this.compression.getExcludedUserAgents()); server = server.compress(mimeTypes.and(excludedUserAgents)); @@ -69,34 +66,30 @@ final class CompressionCustomizer implements NettyServerCustomizer { if (ObjectUtils.isEmpty(mimeTypeValues)) { return ALWAYS_COMPRESS; } - List mimeTypes = Arrays.stream(mimeTypeValues) - .map(MimeTypeUtils::parseMimeType).collect(Collectors.toList()); + List mimeTypes = Arrays.stream(mimeTypeValues).map(MimeTypeUtils::parseMimeType) + .collect(Collectors.toList()); return (request, response) -> { - String contentType = response.responseHeaders() - .get(HttpHeaderNames.CONTENT_TYPE); + String contentType = response.responseHeaders().get(HttpHeaderNames.CONTENT_TYPE); if (StringUtils.isEmpty(contentType)) { return false; } MimeType contentMimeType = MimeTypeUtils.parseMimeType(contentType); - return mimeTypes.stream() - .anyMatch((candidate) -> candidate.isCompatibleWith(contentMimeType)); + return mimeTypes.stream().anyMatch((candidate) -> candidate.isCompatibleWith(contentMimeType)); }; } - private CompressionPredicate getExcludedUserAgentsPredicate( - String[] excludedUserAgents) { + private CompressionPredicate getExcludedUserAgentsPredicate(String[] excludedUserAgents) { if (ObjectUtils.isEmpty(excludedUserAgents)) { return ALWAYS_COMPRESS; } return (request, response) -> { HttpHeaders headers = request.requestHeaders(); - return Arrays.stream(excludedUserAgents).noneMatch((candidate) -> headers - .contains(HttpHeaderNames.USER_AGENT, candidate, true)); + return Arrays.stream(excludedUserAgents) + .noneMatch((candidate) -> headers.contains(HttpHeaderNames.USER_AGENT, candidate, true)); }; } - private interface CompressionPredicate - extends BiPredicate { + private interface CompressionPredicate extends BiPredicate { } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactory.java index 860a92c62f2..127a9013b89 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactory.java @@ -63,10 +63,8 @@ public class NettyReactiveWebServerFactory extends AbstractReactiveWebServerFact @Override public WebServer getWebServer(HttpHandler httpHandler) { HttpServer httpServer = createHttpServer(); - ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter( - httpHandler); - NettyWebServer webServer = new NettyWebServer(httpServer, handlerAdapter, - this.lifecycleTimeout); + ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler); + NettyWebServer webServer = new NettyWebServer(httpServer, handlerAdapter, this.lifecycleTimeout); webServer.setRouteProviders(this.routeProviders); return webServer; } @@ -85,8 +83,7 @@ public class NettyReactiveWebServerFactory extends AbstractReactiveWebServerFact * builder. Calling this method will replace any existing customizers. * @param serverCustomizers the customizers to set */ - public void setServerCustomizers( - Collection serverCustomizers) { + public void setServerCustomizers(Collection serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizers must not be null"); this.serverCustomizers = new ArrayList<>(serverCustomizers); } @@ -141,23 +138,20 @@ public class NettyReactiveWebServerFactory extends AbstractReactiveWebServerFact HttpServer server = HttpServer.create(); if (this.resourceFactory != null) { LoopResources resources = this.resourceFactory.getLoopResources(); - Assert.notNull(resources, - "No LoopResources: is ReactorResourceFactory not initialized yet?"); - server = server.tcpConfiguration((tcpServer) -> tcpServer.runOn(resources) - .addressSupplier(this::getListenAddress)); + Assert.notNull(resources, "No LoopResources: is ReactorResourceFactory not initialized yet?"); + server = server.tcpConfiguration( + (tcpServer) -> tcpServer.runOn(resources).addressSupplier(this::getListenAddress)); } else { - server = server.tcpConfiguration( - (tcpServer) -> tcpServer.addressSupplier(this::getListenAddress)); + server = server.tcpConfiguration((tcpServer) -> tcpServer.addressSupplier(this::getListenAddress)); } if (getSsl() != null && getSsl().isEnabled()) { - SslServerCustomizer sslServerCustomizer = new SslServerCustomizer(getSsl(), - getHttp2(), getSslStoreProvider()); + SslServerCustomizer sslServerCustomizer = new SslServerCustomizer(getSsl(), getHttp2(), + getSslStoreProvider()); server = sslServerCustomizer.apply(server); } if (getCompression() != null && getCompression().getEnabled()) { - CompressionCustomizer compressionCustomizer = new CompressionCustomizer( - getCompression()); + CompressionCustomizer compressionCustomizer = new CompressionCustomizer(getCompression()); server = compressionCustomizer.apply(server); } server = server.protocol(listProtocols()).forwarded(this.useForwardHeaders); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java index ac345ef6527..f1b7a2c969a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java @@ -61,8 +61,7 @@ public class NettyWebServer implements WebServer { private DisposableServer disposableServer; - public NettyWebServer(HttpServer httpServer, ReactorHttpHandlerAdapter handlerAdapter, - Duration lifecycleTimeout) { + public NettyWebServer(HttpServer httpServer, ReactorHttpHandlerAdapter handlerAdapter, Duration lifecycleTimeout) { Assert.notNull(httpServer, "HttpServer must not be null"); Assert.notNull(handlerAdapter, "HandlerAdapter must not be null"); this.httpServer = httpServer; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java index d220fa889f6..431b198d680 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java @@ -59,8 +59,7 @@ public class SslServerCustomizer implements NettyServerCustomizer { public HttpServer apply(HttpServer server) { try { return server.secure((contextSpec) -> { - SslProvider.DefaultConfigurationSpec spec = contextSpec - .sslContext(getContextBuilder()); + SslProvider.DefaultConfigurationSpec spec = contextSpec.sslContext(getContextBuilder()); if (this.http2 != null && this.http2.isEnabled()) { spec.defaultConfiguration(SslProvider.DefaultConfigurationType.H2); } @@ -72,8 +71,7 @@ public class SslServerCustomizer implements NettyServerCustomizer { } protected SslContextBuilder getContextBuilder() { - SslContextBuilder builder = SslContextBuilder - .forServer(getKeyManagerFactory(this.ssl, this.sslStoreProvider)) + SslContextBuilder builder = SslContextBuilder.forServer(getKeyManagerFactory(this.ssl, this.sslStoreProvider)) .trustManager(getTrustManagerFactory(this.ssl, this.sslStoreProvider)); if (this.ssl.getEnabledProtocols() != null) { builder.protocols(this.ssl.getEnabledProtocols()); @@ -90,14 +88,12 @@ public class SslServerCustomizer implements NettyServerCustomizer { return builder; } - protected KeyManagerFactory getKeyManagerFactory(Ssl ssl, - SslStoreProvider sslStoreProvider) { + protected KeyManagerFactory getKeyManagerFactory(Ssl ssl, SslStoreProvider sslStoreProvider) { try { KeyStore keyStore = getKeyStore(ssl, sslStoreProvider); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); - char[] keyPassword = (ssl.getKeyPassword() != null) - ? ssl.getKeyPassword().toCharArray() : null; + char[] keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword().toCharArray() : null; if (keyPassword == null && ssl.getKeyStorePassword() != null) { keyPassword = ssl.getKeyStorePassword().toCharArray(); } @@ -109,17 +105,15 @@ public class SslServerCustomizer implements NettyServerCustomizer { } } - private KeyStore getKeyStore(Ssl ssl, SslStoreProvider sslStoreProvider) - throws Exception { + private KeyStore getKeyStore(Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception { if (sslStoreProvider != null) { return sslStoreProvider.getKeyStore(); } - return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), - ssl.getKeyStore(), ssl.getKeyStorePassword()); + return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), ssl.getKeyStore(), + ssl.getKeyStorePassword()); } - protected TrustManagerFactory getTrustManagerFactory(Ssl ssl, - SslStoreProvider sslStoreProvider) { + protected TrustManagerFactory getTrustManagerFactory(Ssl ssl, SslStoreProvider sslStoreProvider) { try { KeyStore store = getTrustStore(ssl, sslStoreProvider); TrustManagerFactory trustManagerFactory = TrustManagerFactory @@ -132,43 +126,36 @@ public class SslServerCustomizer implements NettyServerCustomizer { } } - private KeyStore getTrustStore(Ssl ssl, SslStoreProvider sslStoreProvider) - throws Exception { + private KeyStore getTrustStore(Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception { if (sslStoreProvider != null) { return sslStoreProvider.getTrustStore(); } - return loadTrustStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), - ssl.getTrustStore(), ssl.getTrustStorePassword()); + return loadTrustStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), ssl.getTrustStore(), + ssl.getTrustStorePassword()); } - private KeyStore loadKeyStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadKeyStore(String type, String provider, String resource, String password) throws Exception { return loadStore(type, provider, resource, password); } - private KeyStore loadTrustStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadTrustStore(String type, String provider, String resource, String password) throws Exception { if (resource == null) { return null; } return loadStore(type, provider, resource, password); } - private KeyStore loadStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadStore(String type, String provider, String resource, String password) throws Exception { type = (type != null) ? type : "JKS"; - KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) - : KeyStore.getInstance(type); + KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type); try { URL url = ResourceUtils.getURL(resource); - store.load(url.openStream(), - (password != null) ? password.toCharArray() : null); + store.load(url.openStream(), (password != null) ? password.toCharArray() : null); return store; } catch (Exception ex) { - throw new WebServerException("Could not load key store '" + resource + "'", - ex); + throw new WebServerException("Could not load key store '" + resource + "'", ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizer.java index a0e92578c3d..77eb0e09c2e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizer.java @@ -83,8 +83,7 @@ class CompressionConnectorCustomizer implements TomcatConnectorCustomizer { } private String getExcludedUserAgents() { - return StringUtils - .arrayToCommaDelimitedString(this.compression.getExcludedUserAgents()); + return StringUtils.arrayToCommaDelimitedString(this.compression.getExcludedUserAgents()); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConfigurableTomcatWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConfigurableTomcatWebServerFactory.java index 2b20daaab52..7f4853b2f3a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConfigurableTomcatWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConfigurableTomcatWebServerFactory.java @@ -74,8 +74,7 @@ public interface ConfigurableTomcatWebServerFactory extends ConfigurableWebServe * @param tomcatProtocolHandlerCustomizers the customizers to add * @since 2.2.0 */ - void addProtocolHandlerCustomizers( - TomcatProtocolHandlerCustomizer... tomcatProtocolHandlerCustomizers); + void addProtocolHandlerCustomizers(TomcatProtocolHandlerCustomizer... tomcatProtocolHandlerCustomizers); /** * Set the character encoding to use for URL decoding. If not specified 'UTF-8' will diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConnectorStartFailedException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConnectorStartFailedException.java index 9b81a6bf8a2..3a25c3bfe76 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConnectorStartFailedException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/ConnectorStartFailedException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class ConnectorStartFailedException extends WebServerException { * @param port the port */ public ConnectorStartFailedException(int port) { - super("Connector configured to listen on port " + port + " failed to start", - null); + super("Connector configured to listen on port " + port + " failed to start", null); this.port = port; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java index 40772805907..ee4a379fe85 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java @@ -53,10 +53,8 @@ class SslConnectorCustomizer implements TomcatConnectorCustomizer { public void customize(Connector connector) { ProtocolHandler handler = connector.getProtocolHandler(); Assert.state(handler instanceof AbstractHttp11JsseProtocol, - "To use SSL, the connector's protocol handler must be an " - + "AbstractHttp11JsseProtocol subclass"); - configureSsl((AbstractHttp11JsseProtocol) handler, this.ssl, - this.sslStoreProvider); + "To use SSL, the connector's protocol handler must be an " + "AbstractHttp11JsseProtocol subclass"); + configureSsl((AbstractHttp11JsseProtocol) handler, this.ssl, this.sslStoreProvider); connector.setScheme("https"); connector.setSecure(true); } @@ -67,8 +65,7 @@ class SslConnectorCustomizer implements TomcatConnectorCustomizer { * @param ssl the ssl details * @param sslStoreProvider the ssl store provider */ - protected void configureSsl(AbstractHttp11JsseProtocol protocol, Ssl ssl, - SslStoreProvider sslStoreProvider) { + protected void configureSsl(AbstractHttp11JsseProtocol protocol, Ssl ssl, SslStoreProvider sslStoreProvider) { protocol.setSSLEnabled(true); protocol.setSslProtocol(ssl.getProtocol()); configureSslClientAuth(protocol, ssl); @@ -81,8 +78,7 @@ class SslConnectorCustomizer implements TomcatConnectorCustomizer { } if (ssl.getEnabledProtocols() != null) { for (SSLHostConfig sslHostConfig : protocol.findSslHostConfigs()) { - sslHostConfig.setProtocols(StringUtils - .arrayToCommaDelimitedString(ssl.getEnabledProtocols())); + sslHostConfig.setProtocols(StringUtils.arrayToCommaDelimitedString(ssl.getEnabledProtocols())); } } if (sslStoreProvider != null) { @@ -107,20 +103,16 @@ class SslConnectorCustomizer implements TomcatConnectorCustomizer { SslStoreProvider sslStoreProvider) { Assert.isInstanceOf(Http11NioProtocol.class, protocol, "SslStoreProvider can only be used with Http11NioProtocol"); - TomcatURLStreamHandlerFactory instance = TomcatURLStreamHandlerFactory - .getInstance(); - instance.addUserFactory( - new SslStoreProviderUrlStreamHandlerFactory(sslStoreProvider)); + TomcatURLStreamHandlerFactory instance = TomcatURLStreamHandlerFactory.getInstance(); + instance.addUserFactory(new SslStoreProviderUrlStreamHandlerFactory(sslStoreProvider)); try { if (sslStoreProvider.getKeyStore() != null) { protocol.setKeystorePass(""); - protocol.setKeystoreFile( - SslStoreProviderUrlStreamHandlerFactory.KEY_STORE_URL); + protocol.setKeystoreFile(SslStoreProviderUrlStreamHandlerFactory.KEY_STORE_URL); } if (sslStoreProvider.getTrustStore() != null) { protocol.setTruststorePass(""); - protocol.setTruststoreFile( - SslStoreProviderUrlStreamHandlerFactory.TRUST_STORE_URL); + protocol.setTruststoreFile(SslStoreProviderUrlStreamHandlerFactory.TRUST_STORE_URL); } } catch (Exception ex) { @@ -133,8 +125,7 @@ class SslConnectorCustomizer implements TomcatConnectorCustomizer { protocol.setKeystoreFile(ResourceUtils.getURL(ssl.getKeyStore()).toString()); } catch (Exception ex) { - throw new WebServerException( - "Could not load key store '" + ssl.getKeyStore() + "'", ex); + throw new WebServerException("Could not load key store '" + ssl.getKeyStore() + "'", ex); } if (ssl.getKeyStoreType() != null) { protocol.setKeystoreType(ssl.getKeyStoreType()); @@ -147,12 +138,10 @@ class SslConnectorCustomizer implements TomcatConnectorCustomizer { private void configureSslTrustStore(AbstractHttp11JsseProtocol protocol, Ssl ssl) { if (ssl.getTrustStore() != null) { try { - protocol.setTruststoreFile( - ResourceUtils.getURL(ssl.getTrustStore()).toString()); + protocol.setTruststoreFile(ResourceUtils.getURL(ssl.getTrustStore()).toString()); } catch (FileNotFoundException ex) { - throw new WebServerException( - "Could not load trust store: " + ex.getMessage(), ex); + throw new WebServerException("Could not load trust store: " + ex.getMessage(), ex); } } protocol.setTruststorePass(ssl.getTrustStorePassword()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java index c04f6105aa0..be27b210958 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,13 +62,11 @@ class SslStoreProviderUrlStreamHandlerFactory implements URLStreamHandlerFactory try { if (KEY_STORE_PATH.equals(url.getPath())) { return new KeyStoreUrlConnection(url, - SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider - .getKeyStore()); + SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider.getKeyStore()); } if (TRUST_STORE_PATH.equals(url.getPath())) { return new KeyStoreUrlConnection(url, - SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider - .getTrustStore()); + SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider.getTrustStore()); } } catch (Exception ex) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedContext.java index 39d022932a2..f321462a5bc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedContext.java @@ -83,8 +83,7 @@ class TomcatEmbeddedContext extends StandardContext { wrapper.load(); } catch (ServletException ex) { - String message = sm.getString("standardContext.loadOnStartup.loadException", - getName(), wrapper.getName()); + String message = sm.getString("standardContext.loadOnStartup.loadException", getName(), wrapper.getName()); if (getComputedFailCtxIfServletStartFails()) { throw new WebServerException(message, ex); } @@ -102,8 +101,8 @@ class TomcatEmbeddedContext extends StandardContext { * @param code the code to run */ private void doWithThreadContextClassLoader(ClassLoader classLoader, Runnable code) { - ClassLoader existingLoader = (classLoader != null) - ? ClassUtils.overrideThreadContextClassLoader(classLoader) : null; + ClassLoader existingLoader = (classLoader != null) ? ClassUtils.overrideThreadContextClassLoader(classLoader) + : null; try { code.run(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java index 3640edcff7b..a67ec055413 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ import org.apache.commons.logging.LogFactory; */ public class TomcatEmbeddedWebappClassLoader extends ParallelWebappClassLoader { - private static final Log logger = LogFactory - .getLog(TomcatEmbeddedWebappClassLoader.class); + private static final Log logger = LogFactory.getLog(TomcatEmbeddedWebappClassLoader.class); static { ClassLoader.registerAsParallelCapable(); @@ -61,8 +60,7 @@ public class TomcatEmbeddedWebappClassLoader extends ParallelWebappClassLoader { } @Override - public Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class result = findExistingLoadedClass(name); result = (result != null) ? result : doLoadClass(name); @@ -128,12 +126,11 @@ public class TomcatEmbeddedWebappClassLoader extends ParallelWebappClassLoader { private void checkPackageAccess(String name) throws ClassNotFoundException { if (this.securityManager != null && name.lastIndexOf('.') >= 0) { try { - this.securityManager - .checkPackageAccess(name.substring(0, name.lastIndexOf('.'))); + this.securityManager.checkPackageAccess(name.substring(0, name.lastIndexOf('.'))); } catch (SecurityException ex) { - throw new ClassNotFoundException("Security Violation, attempt to use " - + "Restricted Class: " + name, ex); + throw new ClassNotFoundException("Security Violation, attempt to use " + "Restricted Class: " + name, + ex); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java index d721f992c4c..29a469e3123 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ class TomcatErrorPage { private Object createNativePage() { try { if (ClassUtils.isPresent(ERROR_PAGE_CLASS, null)) { - return BeanUtils - .instantiateClass(ClassUtils.forName(ERROR_PAGE_CLASS, null)); + return BeanUtils.instantiateClass(ClassUtils.forName(ERROR_PAGE_CLASS, null)); } } catch (ClassNotFoundException | LinkageError ex) { @@ -65,8 +64,7 @@ class TomcatErrorPage { } public void addToContext(Context context) { - Assert.state(this.nativePage != null, - "No Tomcat 8 detected so no native error page exists"); + Assert.state(this.nativePage != null, "No Tomcat 8 detected so no native error page exists"); if (ClassUtils.isPresent(ERROR_PAGE_CLASS, null)) { org.apache.tomcat.util.descriptor.web.ErrorPage errorPage = (org.apache.tomcat.util.descriptor.web.ErrorPage) this.nativePage; errorPage.setLocation(this.location); @@ -77,10 +75,8 @@ class TomcatErrorPage { else { callMethod(this.nativePage, "setLocation", this.location, String.class); callMethod(this.nativePage, "setErrorCode", this.errorCode, int.class); - callMethod(this.nativePage, "setExceptionType", this.exceptionType, - String.class); - callMethod(context, "addErrorPage", this.nativePage, - this.nativePage.getClass()); + callMethod(this.nativePage, "setExceptionType", this.exceptionType, String.class); + callMethod(context, "addErrorPage", this.nativePage, this.nativePage.getClass()); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java index cdd7b48ace9..1c31379bc76 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java @@ -102,8 +102,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac private static List getDefaultLifecycleListeners() { AprLifecycleListener aprLifecycleListener = new AprLifecycleListener(); - return AprLifecycleListener.isAprAvailable() - ? new ArrayList<>(Arrays.asList(aprLifecycleListener)) + return AprLifecycleListener.isAprAvailable() ? new ArrayList<>(Arrays.asList(aprLifecycleListener)) : new ArrayList<>(); } @@ -113,8 +112,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac Registry.disableRegistry(); } Tomcat tomcat = new Tomcat(); - File baseDir = (this.baseDirectory != null) ? this.baseDirectory - : createTempDir("tomcat"); + File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); @@ -165,8 +163,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac protected void configureContext(Context context) { this.contextLifecycleListeners.forEach(context::addLifecycleListener); new DisableReferenceClearingContextCustomizer().customize(context); - this.tomcatContextCustomizers - .forEach((customizer) -> customizer.customize(context)); + this.tomcatContextCustomizers.forEach((customizer) -> customizer.customize(context)); } protected void customizeConnector(Connector connector) { @@ -187,8 +184,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(connector); } - TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer( - getCompression()); + TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer(getCompression()); compression.customize(connector); for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) { customizer.customize(connector); @@ -197,10 +193,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac @SuppressWarnings("unchecked") private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) { - LambdaSafe - .callbacks(TomcatProtocolHandlerCustomizer.class, - this.tomcatProtocolHandlerCustomizers, protocolHandler) - .invoke((customizer) -> customizer.customize(protocolHandler)); + LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, + protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler)); } private void customizeProtocol(AbstractProtocol protocol) { @@ -231,10 +225,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac * {@link Context}. Calling this method will replace any existing customizers. * @param tomcatContextCustomizers the customizers to set */ - public void setTomcatContextCustomizers( - Collection tomcatContextCustomizers) { - Assert.notNull(tomcatContextCustomizers, - "TomcatContextCustomizers must not be null"); + public void setTomcatContextCustomizers(Collection tomcatContextCustomizers) { + Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null"); this.tomcatContextCustomizers = new ArrayList<>(tomcatContextCustomizers); } @@ -253,10 +245,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac * @param tomcatContextCustomizers the customizers to add */ @Override - public void addContextCustomizers( - TomcatContextCustomizer... tomcatContextCustomizers) { - Assert.notNull(tomcatContextCustomizers, - "TomcatContextCustomizers must not be null"); + public void addContextCustomizers(TomcatContextCustomizer... tomcatContextCustomizers) { + Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null"); this.tomcatContextCustomizers.addAll(Arrays.asList(tomcatContextCustomizers)); } @@ -267,8 +257,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac */ public void setTomcatConnectorCustomizers( Collection tomcatConnectorCustomizers) { - Assert.notNull(tomcatConnectorCustomizers, - "TomcatConnectorCustomizers must not be null"); + Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null"); this.tomcatConnectorCustomizers = new ArrayList<>(tomcatConnectorCustomizers); } @@ -278,10 +267,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac * @param tomcatConnectorCustomizers the customizers to add */ @Override - public void addConnectorCustomizers( - TomcatConnectorCustomizer... tomcatConnectorCustomizers) { - Assert.notNull(tomcatConnectorCustomizers, - "TomcatConnectorCustomizers must not be null"); + public void addConnectorCustomizers(TomcatConnectorCustomizer... tomcatConnectorCustomizers) { + Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null"); this.tomcatConnectorCustomizers.addAll(Arrays.asList(tomcatConnectorCustomizers)); } @@ -302,10 +289,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac */ public void setTomcatProtocolHandlerCustomizers( Collection> tomcatProtocolHandlerCustomizers) { - Assert.notNull(tomcatProtocolHandlerCustomizers, - "TomcatProtocolHandlerCustomizers must not be null"); - this.tomcatProtocolHandlerCustomizers = new ArrayList<>( - tomcatProtocolHandlerCustomizers); + Assert.notNull(tomcatProtocolHandlerCustomizers, "TomcatProtocolHandlerCustomizers must not be null"); + this.tomcatProtocolHandlerCustomizers = new ArrayList<>(tomcatProtocolHandlerCustomizers); } /** @@ -315,12 +300,9 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac * @since 2.2.0 */ @Override - public void addProtocolHandlerCustomizers( - TomcatProtocolHandlerCustomizer... tomcatProtocolHandlerCustomizers) { - Assert.notNull(tomcatProtocolHandlerCustomizers, - "TomcatProtocolHandlerCustomizers must not be null"); - this.tomcatProtocolHandlerCustomizers - .addAll(Arrays.asList(tomcatProtocolHandlerCustomizers)); + public void addProtocolHandlerCustomizers(TomcatProtocolHandlerCustomizer... tomcatProtocolHandlerCustomizers) { + Assert.notNull(tomcatProtocolHandlerCustomizers, "TomcatProtocolHandlerCustomizers must not be null"); + this.tomcatProtocolHandlerCustomizers.addAll(Arrays.asList(tomcatProtocolHandlerCustomizers)); } /** @@ -371,10 +353,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac * {@link Context}. Calling this method will replace any existing listeners. * @param contextLifecycleListeners the listeners to set */ - public void setContextLifecycleListeners( - Collection contextLifecycleListeners) { - Assert.notNull(contextLifecycleListeners, - "ContextLifecycleListeners must not be null"); + public void setContextLifecycleListeners(Collection contextLifecycleListeners) { + Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null"); this.contextLifecycleListeners = new ArrayList<>(contextLifecycleListeners); } @@ -391,10 +371,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac * Add {@link LifecycleListener}s that should be added to the Tomcat {@link Context}. * @param contextLifecycleListeners the listeners to add */ - public void addContextLifecycleListeners( - LifecycleListener... contextLifecycleListeners) { - Assert.notNull(contextLifecycleListeners, - "ContextLifecycleListeners must not be null"); + public void addContextLifecycleListeners(LifecycleListener... contextLifecycleListeners) { + Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null"); this.contextLifecycleListeners.addAll(Arrays.asList(contextLifecycleListeners)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java index 01bc47be1e8..5a3b3528f22 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java @@ -163,8 +163,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto private static List getDefaultLifecycleListeners() { AprLifecycleListener aprLifecycleListener = new AprLifecycleListener(); - return AprLifecycleListener.isAprAvailable() - ? new ArrayList<>(Arrays.asList(aprLifecycleListener)) + return AprLifecycleListener.isAprAvailable() ? new ArrayList<>(Arrays.asList(aprLifecycleListener)) : new ArrayList<>(); } @@ -174,8 +173,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto Registry.disableRegistry(); } Tomcat tomcat = new Tomcat(); - File baseDir = (this.baseDirectory != null) ? this.baseDirectory - : createTempDir("tomcat"); + File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); @@ -206,13 +204,11 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto context.setName(getContextPath()); context.setDisplayName(getDisplayName()); context.setPath(getContextPath()); - File docBase = (documentRoot != null) ? documentRoot - : createTempDir("tomcat-docbase"); + File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase"); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); - context.setParentClassLoader( - (this.resourceLoader != null) ? this.resourceLoader.getClassLoader() - : ClassUtils.getDefaultClassLoader()); + context.setParentClassLoader((this.resourceLoader != null) ? this.resourceLoader.getClassLoader() + : ClassUtils.getDefaultClassLoader()); resetDefaultLocaleMapping(context); addLocaleMappings(context); context.setUseRelativeRedirects(false); @@ -247,22 +243,18 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto * @param context the context to reset */ private void resetDefaultLocaleMapping(TomcatEmbeddedContext context) { - context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), - DEFAULT_CHARSET.displayName()); - context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), - DEFAULT_CHARSET.displayName()); + context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), DEFAULT_CHARSET.displayName()); + context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), DEFAULT_CHARSET.displayName()); } private void addLocaleMappings(TomcatEmbeddedContext context) { - getLocaleCharsetMappings() - .forEach((locale, charset) -> context.addLocaleEncodingMappingParameter( - locale.toString(), charset.toString())); + getLocaleCharsetMappings().forEach( + (locale, charset) -> context.addLocaleEncodingMappingParameter(locale.toString(), charset.toString())); } private void configureTldSkipPatterns(TomcatEmbeddedContext context) { StandardJarScanFilter filter = new StandardJarScanFilter(); - filter.setTldSkip( - StringUtils.collectionToCommaDelimitedString(this.tldSkipPatterns)); + filter.setTldSkip(StringUtils.collectionToCommaDelimitedString(this.tldSkipPatterns)); context.getJarScanner().setJarScanFilter(filter); } @@ -294,8 +286,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto private void addJasperInitializer(TomcatEmbeddedContext context) { try { ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils - .forName("org.apache.jasper.servlet.JasperInitializer", null) - .newInstance(); + .forName("org.apache.jasper.servlet.JasperInitializer", null).newInstance(); context.addServletContainerInitializer(initializer, null); } catch (Exception ex) { @@ -322,8 +313,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(connector); } - TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer( - getCompression()); + TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer(getCompression()); compression.customize(connector); for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) { customizer.customize(connector); @@ -338,10 +328,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto @SuppressWarnings("unchecked") private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) { - LambdaSafe - .callbacks(TomcatProtocolHandlerCustomizer.class, - this.tomcatProtocolHandlerCustomizers, protocolHandler) - .invoke((customizer) -> customizer.customize(protocolHandler)); + LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, + protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler)); } private void customizeSsl(Connector connector) { @@ -356,8 +344,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto * @param context the Tomcat context * @param initializers initializers to apply */ - protected void configureContext(Context context, - ServletContextInitializer[] initializers) { + protected void configureContext(Context context, ServletContextInitializer[] initializers) { TomcatStarter starter = new TomcatStarter(initializers); if (context instanceof TomcatEmbeddedContext) { TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context; @@ -406,8 +393,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto private void configurePersistSession(Manager manager) { Assert.state(manager instanceof StandardManager, - () -> "Unable to persist HTTP session state using manager type " - + manager.getClass().getName()); + () -> "Unable to persist HTTP session state using manager type " + manager.getClass().getName()); File dir = getValidSessionStoreDir(); File file = new File(dir, "SESSIONS.ser"); ((StandardManager) manager).setPathname(file.getAbsolutePath()); @@ -422,8 +408,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto } private boolean isZeroOrLess(Duration sessionTimeout) { - return sessionTimeout == null || sessionTimeout.isNegative() - || sessionTimeout.isZero(); + return sessionTimeout == null || sessionTimeout.isNegative() || sessionTimeout.isZero(); } /** @@ -553,10 +538,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto * {@link Context}. Calling this method will replace any existing listeners. * @param contextLifecycleListeners the listeners to set */ - public void setContextLifecycleListeners( - Collection contextLifecycleListeners) { - Assert.notNull(contextLifecycleListeners, - "ContextLifecycleListeners must not be null"); + public void setContextLifecycleListeners(Collection contextLifecycleListeners) { + Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null"); this.contextLifecycleListeners = new ArrayList<>(contextLifecycleListeners); } @@ -573,10 +556,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto * Add {@link LifecycleListener}s that should be added to the Tomcat {@link Context}. * @param contextLifecycleListeners the listeners to add */ - public void addContextLifecycleListeners( - LifecycleListener... contextLifecycleListeners) { - Assert.notNull(contextLifecycleListeners, - "ContextLifecycleListeners must not be null"); + public void addContextLifecycleListeners(LifecycleListener... contextLifecycleListeners) { + Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null"); this.contextLifecycleListeners.addAll(Arrays.asList(contextLifecycleListeners)); } @@ -585,10 +566,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto * {@link Context}. Calling this method will replace any existing customizers. * @param tomcatContextCustomizers the customizers to set */ - public void setTomcatContextCustomizers( - Collection tomcatContextCustomizers) { - Assert.notNull(tomcatContextCustomizers, - "TomcatContextCustomizers must not be null"); + public void setTomcatContextCustomizers(Collection tomcatContextCustomizers) { + Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null"); this.tomcatContextCustomizers = new ArrayList<>(tomcatContextCustomizers); } @@ -602,10 +581,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto } @Override - public void addContextCustomizers( - TomcatContextCustomizer... tomcatContextCustomizers) { - Assert.notNull(tomcatContextCustomizers, - "TomcatContextCustomizers must not be null"); + public void addContextCustomizers(TomcatContextCustomizer... tomcatContextCustomizers) { + Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null"); this.tomcatContextCustomizers.addAll(Arrays.asList(tomcatContextCustomizers)); } @@ -616,16 +593,13 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto */ public void setTomcatConnectorCustomizers( Collection tomcatConnectorCustomizers) { - Assert.notNull(tomcatConnectorCustomizers, - "TomcatConnectorCustomizers must not be null"); + Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null"); this.tomcatConnectorCustomizers = new ArrayList<>(tomcatConnectorCustomizers); } @Override - public void addConnectorCustomizers( - TomcatConnectorCustomizer... tomcatConnectorCustomizers) { - Assert.notNull(tomcatConnectorCustomizers, - "TomcatConnectorCustomizers must not be null"); + public void addConnectorCustomizers(TomcatConnectorCustomizer... tomcatConnectorCustomizers) { + Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null"); this.tomcatConnectorCustomizers.addAll(Arrays.asList(tomcatConnectorCustomizers)); } @@ -646,10 +620,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto */ public void setTomcatProtocolHandlerCustomizers( Collection> tomcatProtocolHandlerCustomizer) { - Assert.notNull(tomcatProtocolHandlerCustomizer, - "TomcatProtocolHandlerCustomizers must not be null"); - this.tomcatProtocolHandlerCustomizers = new ArrayList<>( - tomcatProtocolHandlerCustomizer); + Assert.notNull(tomcatProtocolHandlerCustomizer, "TomcatProtocolHandlerCustomizers must not be null"); + this.tomcatProtocolHandlerCustomizers = new ArrayList<>(tomcatProtocolHandlerCustomizer); } /** @@ -659,12 +631,9 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto * @since 2.2.0 */ @Override - public void addProtocolHandlerCustomizers( - TomcatProtocolHandlerCustomizer... tomcatProtocolHandlerCustomizers) { - Assert.notNull(tomcatProtocolHandlerCustomizers, - "TomcatProtocolHandlerCustomizers must not be null"); - this.tomcatProtocolHandlerCustomizers - .addAll(Arrays.asList(tomcatProtocolHandlerCustomizers)); + public void addProtocolHandlerCustomizers(TomcatProtocolHandlerCustomizer... tomcatProtocolHandlerCustomizers) { + Assert.notNull(tomcatProtocolHandlerCustomizers, "TomcatProtocolHandlerCustomizers must not be null"); + this.tomcatProtocolHandlerCustomizers.addAll(Arrays.asList(tomcatProtocolHandlerCustomizers)); } /** @@ -785,8 +754,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto } URL url = new URL(resource); String path = "/META-INF/resources"; - this.context.getResources().createWebResourceSet( - ResourceSetType.RESOURCE_JAR, "/", url, path); + this.context.getResources().createWebResourceSet(ResourceSetType.RESOURCE_JAR, "/", url, path); } catch (Exception ex) { // Ignore (probably not a directory) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatStarter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatStarter.java index 702493b0f7f..1e250096597 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatStarter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatStarter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ class TomcatStarter implements ServletContainerInitializer { } @Override - public void onStartup(Set> classes, ServletContext servletContext) - throws ServletException { + public void onStartup(Set> classes, ServletContext servletContext) throws ServletException { try { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); @@ -59,8 +58,8 @@ class TomcatStarter implements ServletContainerInitializer { // Prevent Tomcat from logging and re-throwing when we know we can // deal with it in the main thread, but log for information here. if (logger.isErrorEnabled()) { - logger.error("Error starting Tomcat context. Exception: " - + ex.getClass().getName() + ". Message: " + ex.getMessage()); + logger.error("Error starting Tomcat context. Exception: " + ex.getClass().getName() + ". Message: " + + ex.getMessage()); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java index d9d699235b8..d87de6211d4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java @@ -94,8 +94,7 @@ public class TomcatWebServer implements WebServer { Context context = findContext(); context.addLifecycleListener((event) -> { - if (context.equals(event.getSource()) - && Lifecycle.START_EVENT.equals(event.getType())) { + if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) { // Remove service connectors so that protocol binding doesn't // happen when the service is started. removeServiceConnectors(); @@ -109,8 +108,7 @@ public class TomcatWebServer implements WebServer { rethrowDeferredStartupExceptions(); try { - ContextBindings.bindClassLoader(context, context.getNamingToken(), - getClass().getClassLoader()); + ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader()); } catch (NamingException ex) { // Naming is not enabled. Continue @@ -159,8 +157,7 @@ public class TomcatWebServer implements WebServer { Container[] children = this.tomcat.getHost().findChildren(); for (Container container : children) { if (container instanceof TomcatEmbeddedContext) { - TomcatStarter tomcatStarter = ((TomcatEmbeddedContext) container) - .getStarter(); + TomcatStarter tomcatStarter = ((TomcatEmbeddedContext) container).getStarter(); if (tomcatStarter != null) { Exception exception = tomcatStarter.getStartUpException(); if (exception != null) { @@ -202,21 +199,19 @@ public class TomcatWebServer implements WebServer { } checkThatConnectorsHaveStarted(); this.started = true; - logger.info("Tomcat started on port(s): " + getPortsDescription(true) - + " with context path '" + getContextPath() + "'"); + logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '" + + getContextPath() + "'"); } catch (ConnectorStartFailedException ex) { stopSilently(); throw ex; } catch (Exception ex) { - throw new WebServerException("Unable to start embedded Tomcat server", - ex); + throw new WebServerException("Unable to start embedded Tomcat server", ex); } finally { Context context = findContext(); - ContextBindings.unbindClassLoader(context, context.getNamingToken(), - getClass().getClassLoader()); + ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader()); } } } @@ -253,8 +248,7 @@ public class TomcatWebServer implements WebServer { } private void stopTomcat() throws LifecycleException { - if (Thread.currentThread() - .getContextClassLoader() instanceof TomcatEmbeddedWebappClassLoader) { + if (Thread.currentThread().getContextClassLoader() instanceof TomcatEmbeddedWebappClassLoader) { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } this.tomcat.stop(); @@ -297,8 +291,7 @@ public class TomcatWebServer implements WebServer { if (ex instanceof WebServerException) { throw (WebServerException) ex; } - throw new WebServerException("Unable to start embedded Tomcat connectors", - ex); + throw new WebServerException("Unable to start embedded Tomcat connectors", ex); } } @@ -353,10 +346,9 @@ public class TomcatWebServer implements WebServer { } private String getContextPath() { - return Arrays.stream(this.tomcat.getHost().findChildren()) - .filter(TomcatEmbeddedContext.class::isInstance) - .map(TomcatEmbeddedContext.class::cast) - .map(TomcatEmbeddedContext::getPath).collect(Collectors.joining(" ")); + return Arrays.stream(this.tomcat.getHost().findChildren()).filter(TomcatEmbeddedContext.class::isInstance) + .map(TomcatEmbeddedContext.class::cast).map(TomcatEmbeddedContext::getPath) + .collect(Collectors.joining(" ")); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/ConfigurableUndertowWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/ConfigurableUndertowWebServerFactory.java index 996d33d1403..324bc41f02b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/ConfigurableUndertowWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/ConfigurableUndertowWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import org.springframework.boot.web.server.ConfigurableWebServerFactory; * @see UndertowServletWebServerFactory * @see UndertowReactiveWebServerFactory */ -public interface ConfigurableUndertowWebServerFactory - extends ConfigurableWebServerFactory { +public interface ConfigurableUndertowWebServerFactory extends ConfigurableWebServerFactory { /** * Add {@link UndertowBuilderCustomizer}s that should be used to customize the diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java index 28dabe6d036..67ff673cf2b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ class FileSessionPersistence implements SessionPersistenceManager { } @Override - public void persistSessions(String deploymentName, - Map sessionData) { + public void persistSessions(String deploymentName, Map sessionData) { try { save(sessionData, getSessionFile(deploymentName)); } @@ -58,25 +57,20 @@ class FileSessionPersistence implements SessionPersistenceManager { } } - private void save(Map sessionData, File file) - throws IOException { - try (ObjectOutputStream stream = new ObjectOutputStream( - new FileOutputStream(file))) { + private void save(Map sessionData, File file) throws IOException { + try (ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file))) { save(sessionData, stream); } } - private void save(Map sessionData, - ObjectOutputStream stream) throws IOException { + private void save(Map sessionData, ObjectOutputStream stream) throws IOException { Map session = new LinkedHashMap<>(); - sessionData.forEach((key, value) -> session.put(key, - new SerializablePersistentSession(value))); + sessionData.forEach((key, value) -> session.put(key, new SerializablePersistentSession(value))); stream.writeObject(session); } @Override - public Map loadSessionAttributes(String deploymentName, - final ClassLoader classLoader) { + public Map loadSessionAttributes(String deploymentName, final ClassLoader classLoader) { try { File file = getSessionFile(deploymentName); if (file.exists()) { @@ -91,14 +85,12 @@ class FileSessionPersistence implements SessionPersistenceManager { private Map load(File file, ClassLoader classLoader) throws IOException, ClassNotFoundException { - try (ObjectInputStream stream = new ConfigurableObjectInputStream( - new FileInputStream(file), classLoader)) { + try (ObjectInputStream stream = new ConfigurableObjectInputStream(new FileInputStream(file), classLoader)) { return load(stream); } } - private Map load(ObjectInputStream stream) - throws ClassNotFoundException, IOException { + private Map load(ObjectInputStream stream) throws ClassNotFoundException, IOException { Map session = readSession(stream); long time = System.currentTimeMillis(); Map result = new LinkedHashMap<>(); @@ -112,8 +104,8 @@ class FileSessionPersistence implements SessionPersistenceManager { } @SuppressWarnings("unchecked") - private Map readSession( - ObjectInputStream stream) throws ClassNotFoundException, IOException { + private Map readSession(ObjectInputStream stream) + throws ClassNotFoundException, IOException { return ((Map) stream.readObject()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/JarResourceManager.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/JarResourceManager.java index 1af0000d6fb..3f7ad6909ba 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/JarResourceManager.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/JarResourceManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ class JarResourceManager implements ResourceManager { @Override public Resource getResource(String path) throws IOException { - URL url = new URL("jar:file:" + this.jarPath + "!" - + (path.startsWith("/") ? path : "/" + path)); + URL url = new URL("jar:file:" + this.jarPath + "!" + (path.startsWith("/") ? path : "/" + path)); URLResource resource = new URLResource(url, path); if (resource.getContentLength() < 0) { return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java index a2d33691548..95a7e418482 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java @@ -60,8 +60,7 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { private final SslStoreProvider sslStoreProvider; - SslBuilderCustomizer(int port, InetAddress address, Ssl ssl, - SslStoreProvider sslStoreProvider) { + SslBuilderCustomizer(int port, InetAddress address, Ssl ssl, SslStoreProvider sslStoreProvider) { this.port = port; this.address = address; this.ssl = ssl; @@ -75,15 +74,12 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { sslContext.init(getKeyManagers(this.ssl, this.sslStoreProvider), getTrustManagers(this.ssl, this.sslStoreProvider), null); builder.addHttpsListener(this.port, getListenAddress(), sslContext); - builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, - getSslClientAuthMode(this.ssl)); + builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, getSslClientAuthMode(this.ssl)); if (this.ssl.getEnabledProtocols() != null) { - builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, - Sequence.of(this.ssl.getEnabledProtocols())); + builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(this.ssl.getEnabledProtocols())); } if (this.ssl.getCiphers() != null) { - builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, - Sequence.of(this.ssl.getCiphers())); + builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, Sequence.of(this.ssl.getCiphers())); } } catch (NoSuchAlgorithmException | KeyManagementException ex) { @@ -113,15 +109,13 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { KeyStore keyStore = getKeyStore(ssl, sslStoreProvider); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); - char[] keyPassword = (ssl.getKeyPassword() != null) - ? ssl.getKeyPassword().toCharArray() : null; + char[] keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword().toCharArray() : null; if (keyPassword == null && ssl.getKeyStorePassword() != null) { keyPassword = ssl.getKeyStorePassword().toCharArray(); } keyManagerFactory.init(keyStore, keyPassword); if (ssl.getKeyAlias() != null) { - return getConfigurableAliasKeyManagers(ssl, - keyManagerFactory.getKeyManagers()); + return getConfigurableAliasKeyManagers(ssl, keyManagerFactory.getKeyManagers()); } return keyManagerFactory.getKeyManagers(); } @@ -130,24 +124,22 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { } } - private KeyManager[] getConfigurableAliasKeyManagers(Ssl ssl, - KeyManager[] keyManagers) { + private KeyManager[] getConfigurableAliasKeyManagers(Ssl ssl, KeyManager[] keyManagers) { for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509ExtendedKeyManager) { - keyManagers[i] = new ConfigurableAliasKeyManager( - (X509ExtendedKeyManager) keyManagers[i], ssl.getKeyAlias()); + keyManagers[i] = new ConfigurableAliasKeyManager((X509ExtendedKeyManager) keyManagers[i], + ssl.getKeyAlias()); } } return keyManagers; } - private KeyStore getKeyStore(Ssl ssl, SslStoreProvider sslStoreProvider) - throws Exception { + private KeyStore getKeyStore(Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception { if (sslStoreProvider != null) { return sslStoreProvider.getKeyStore(); } - return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), - ssl.getKeyStore(), ssl.getKeyStorePassword()); + return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), ssl.getKeyStore(), + ssl.getKeyStorePassword()); } private TrustManager[] getTrustManagers(Ssl ssl, SslStoreProvider sslStoreProvider) { @@ -163,42 +155,35 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { } } - private KeyStore getTrustStore(Ssl ssl, SslStoreProvider sslStoreProvider) - throws Exception { + private KeyStore getTrustStore(Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception { if (sslStoreProvider != null) { return sslStoreProvider.getTrustStore(); } - return loadTrustStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), - ssl.getTrustStore(), ssl.getTrustStorePassword()); + return loadTrustStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), ssl.getTrustStore(), + ssl.getTrustStorePassword()); } - private KeyStore loadKeyStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadKeyStore(String type, String provider, String resource, String password) throws Exception { return loadStore(type, provider, resource, password); } - private KeyStore loadTrustStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadTrustStore(String type, String provider, String resource, String password) throws Exception { if (resource == null) { return null; } return loadStore(type, provider, resource, password); } - private KeyStore loadStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadStore(String type, String provider, String resource, String password) throws Exception { type = (type != null) ? type : "JKS"; - KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) - : KeyStore.getInstance(type); + KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type); try { URL url = ResourceUtils.getURL(resource); - store.load(url.openStream(), - (password != null) ? password.toCharArray() : null); + store.load(url.openStream(), (password != null) ? password.toCharArray() : null); return store; } catch (Exception ex) { - throw new WebServerException("Could not load key store '" + resource + "'", - ex); + throw new WebServerException("Could not load key store '" + resource + "'", ex); } } @@ -217,15 +202,12 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { } @Override - public String chooseEngineClientAlias(String[] strings, Principal[] principals, - SSLEngine sslEngine) { - return this.keyManager.chooseEngineClientAlias(strings, principals, - sslEngine); + public String chooseEngineClientAlias(String[] strings, Principal[] principals, SSLEngine sslEngine) { + return this.keyManager.chooseEngineClientAlias(strings, principals, sslEngine); } @Override - public String chooseEngineServerAlias(String s, Principal[] principals, - SSLEngine sslEngine) { + public String chooseEngineServerAlias(String s, Principal[] principals, SSLEngine sslEngine) { if (this.alias == null) { return this.keyManager.chooseEngineServerAlias(s, principals, sslEngine); } @@ -233,14 +215,12 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { } @Override - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { + public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return this.keyManager.chooseClientAlias(keyType, issuers, socket); } @Override - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { + public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return this.keyManager.chooseServerAlias(keyType, issuers, socket); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowCompressionConfigurer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowCompressionConfigurer.java index cbfd6c9eaaa..f106cc7ffd3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowCompressionConfigurer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowCompressionConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,7 @@ final class UndertowCompressionConfigurer { * @param httpHandler the HTTP handler to wrap * @return the wrapped HTTP handler if compression is enabled, or the handler itself */ - public static HttpHandler configureCompression(Compression compression, - HttpHandler httpHandler) { + public static HttpHandler configureCompression(Compression compression, HttpHandler httpHandler) { if (compression == null || !compression.getEnabled()) { return httpHandler; } @@ -65,13 +64,11 @@ final class UndertowCompressionConfigurer { private static Predicate[] getCompressionPredicates(Compression compression) { List predicates = new ArrayList<>(); - predicates.add( - new MaxSizePredicate((int) compression.getMinResponseSize().toBytes())); + predicates.add(new MaxSizePredicate((int) compression.getMinResponseSize().toBytes())); predicates.add(new CompressibleMimeTypePredicate(compression.getMimeTypes())); if (compression.getExcludedUserAgents() != null) { for (String agent : compression.getExcludedUserAgents()) { - RequestHeaderAttribute agentHeader = new RequestHeaderAttribute( - new HttpString(HttpHeaders.USER_AGENT)); + RequestHeaderAttribute agentHeader = new RequestHeaderAttribute(new HttpString(HttpHeaders.USER_AGENT)); predicates.add(Predicates.not(Predicates.regex(agentHeader, agent))); } } @@ -91,12 +88,10 @@ final class UndertowCompressionConfigurer { @Override public boolean resolve(HttpServerExchange value) { - String contentType = value.getResponseHeaders() - .getFirst(HttpHeaders.CONTENT_TYPE); + String contentType = value.getResponseHeaders().getFirst(HttpHeaders.CONTENT_TYPE); if (contentType != null) { for (MimeType mimeType : this.mimeTypes) { - if (mimeType - .isCompatibleWith(MimeTypeUtils.parseMimeType(contentType))) { + if (mimeType.isCompatibleWith(MimeTypeUtils.parseMimeType(contentType))) { return true; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactory.java index 727eb91874d..d7a42b6a005 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,8 +93,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF } @Override - public WebServer getWebServer( - org.springframework.http.server.reactive.HttpHandler httpHandler) { + public WebServer getWebServer(org.springframework.http.server.reactive.HttpHandler httpHandler) { Undertow.Builder builder = createBuilder(getPort()); Closeable closeable = configureHandler(builder, httpHandler); return new UndertowWebServer(builder, getPort() >= 0, closeable); @@ -132,8 +131,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF if (this.useForwardHeaders) { handler = Handlers.proxyPeerAddress(handler); } - handler = UndertowCompressionConfigurer.configureCompression(getCompression(), - handler); + handler = UndertowCompressionConfigurer.configureCompression(getCompression(), handler); Closeable closeable = null; if (isAccessLogEnabled()) { closeable = configureAccessLogHandler(builder, handler); @@ -144,20 +142,16 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF return closeable; } - private Closeable configureAccessLogHandler(Undertow.Builder builder, - HttpHandler handler) { + private Closeable configureAccessLogHandler(Undertow.Builder builder, HttpHandler handler) { try { createAccessLogDirectoryIfNecessary(); XnioWorker worker = createWorker(); - String prefix = (this.accessLogPrefix != null) ? this.accessLogPrefix - : "access_log."; - DefaultAccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver( - worker, this.accessLogDirectory, prefix, this.accessLogSuffix, - this.accessLogRotate); - String formatString = ((this.accessLogPattern != null) ? this.accessLogPattern - : "common"); - builder.setHandler(new AccessLogHandler(handler, accessLogReceiver, - formatString, Undertow.class.getClassLoader())); + String prefix = (this.accessLogPrefix != null) ? this.accessLogPrefix : "access_log."; + DefaultAccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver(worker, this.accessLogDirectory, + prefix, this.accessLogSuffix, this.accessLogRotate); + String formatString = ((this.accessLogPattern != null) ? this.accessLogPattern : "common"); + builder.setHandler( + new AccessLogHandler(handler, accessLogReceiver, formatString, Undertow.class.getClassLoader())); return () -> { try { accessLogReceiver.close(); @@ -176,20 +170,17 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF private void createAccessLogDirectoryIfNecessary() { Assert.state(this.accessLogDirectory != null, "Access log directory is not set"); if (!this.accessLogDirectory.isDirectory() && !this.accessLogDirectory.mkdirs()) { - throw new IllegalStateException("Failed to create access log directory '" - + this.accessLogDirectory + "'"); + throw new IllegalStateException("Failed to create access log directory '" + this.accessLogDirectory + "'"); } } private XnioWorker createWorker() throws IOException { Xnio xnio = Xnio.getInstance(Undertow.class.getClassLoader()); - return xnio.createWorker( - OptionMap.builder().set(Options.THREAD_DAEMON, true).getMap()); + return xnio.createWorker(OptionMap.builder().set(Options.THREAD_DAEMON, true).getMap()); } private void customizeSsl(Undertow.Builder builder) { - new SslBuilderCustomizer(getPort(), getAddress(), getSsl(), getSslStoreProvider()) - .customize(builder); + new SslBuilderCustomizer(getPort(), getAddress(), getSsl(), getSslStoreProvider()).customize(builder); if (getHttp2() != null) { builder.setServerOption(UndertowOptions.ENABLE_HTTP2, getHttp2().isEnabled()); } @@ -208,8 +199,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF * customizers. * @param customizers the customizers to set */ - public void setDeploymentInfoCustomizers( - Collection customizers) { + public void setDeploymentInfoCustomizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.deploymentInfoCustomizers = new ArrayList<>(customizers); } @@ -224,8 +214,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF } @Override - public void addDeploymentInfoCustomizers( - UndertowDeploymentInfoCustomizer... customizers) { + public void addDeploymentInfoCustomizers(UndertowDeploymentInfoCustomizer... customizers) { Assert.notNull(customizers, "UndertowDeploymentInfoCustomizers must not be null"); this.deploymentInfoCustomizers.addAll(Arrays.asList(customizers)); } @@ -299,8 +288,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF * existing customizers. * @param customizers the customizers to set */ - public void setBuilderCustomizers( - Collection customizers) { + public void setBuilderCustomizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.builderCustomizers = new ArrayList<>(customizers); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java index 0bb01190e82..4003d0f5ece 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,8 +86,8 @@ public class UndertowServletWebServer implements WebServer { * @param autoStart if the server should be started * @param compression compression configuration */ - public UndertowServletWebServer(Builder builder, DeploymentManager manager, - String contextPath, boolean autoStart, Compression compression) { + public UndertowServletWebServer(Builder builder, DeploymentManager manager, String contextPath, boolean autoStart, + Compression compression) { this(builder, manager, contextPath, false, autoStart, compression); } @@ -100,11 +100,9 @@ public class UndertowServletWebServer implements WebServer { * @param autoStart if the server should be started * @param compression compression configuration */ - public UndertowServletWebServer(Builder builder, DeploymentManager manager, - String contextPath, boolean useForwardHeaders, boolean autoStart, - Compression compression) { - this(builder, manager, contextPath, useForwardHeaders, autoStart, compression, - null); + public UndertowServletWebServer(Builder builder, DeploymentManager manager, String contextPath, + boolean useForwardHeaders, boolean autoStart, Compression compression) { + this(builder, manager, contextPath, useForwardHeaders, autoStart, compression, null); } /** @@ -117,9 +115,8 @@ public class UndertowServletWebServer implements WebServer { * @param compression compression configuration * @param serverHeader string to be used in HTTP header */ - public UndertowServletWebServer(Builder builder, DeploymentManager manager, - String contextPath, boolean useForwardHeaders, boolean autoStart, - Compression compression, String serverHeader) { + public UndertowServletWebServer(Builder builder, DeploymentManager manager, String contextPath, + boolean useForwardHeaders, boolean autoStart, Compression compression, String serverHeader) { this.builder = builder; this.manager = manager; this.contextPath = contextPath; @@ -144,9 +141,8 @@ public class UndertowServletWebServer implements WebServer { } this.undertow.start(); this.started = true; - UndertowServletWebServer.logger - .info("Undertow started on port(s) " + getPortsDescription() - + " with context path '" + this.contextPath + "'"); + UndertowServletWebServer.logger.info("Undertow started on port(s) " + getPortsDescription() + + " with context path '" + this.contextPath + "'"); } catch (Exception ex) { try { @@ -155,8 +151,7 @@ public class UndertowServletWebServer implements WebServer { List actualPorts = getActualPorts(); failedPorts.removeAll(actualPorts); if (failedPorts.size() == 1) { - throw new PortInUseException( - failedPorts.iterator().next().getNumber()); + throw new PortInUseException(failedPorts.iterator().next().getNumber()); } } throw new WebServerException("Unable to start embedded Undertow", ex); @@ -210,8 +205,7 @@ public class UndertowServletWebServer implements WebServer { } private HttpHandler getContextHandler(HttpHandler httpHandler) { - HttpHandler contextHandler = UndertowCompressionConfigurer - .configureCompression(this.compression, httpHandler); + HttpHandler contextHandler = UndertowCompressionConfigurer.configureCompression(this.compression, httpHandler); if (StringUtils.isEmpty(this.contextPath)) { return contextHandler; } @@ -248,15 +242,13 @@ public class UndertowServletWebServer implements WebServer { private List extractChannels() { Field channelsField = ReflectionUtils.findField(Undertow.class, "channels"); ReflectionUtils.makeAccessible(channelsField); - return (List) ReflectionUtils.getField(channelsField, - this.undertow); + return (List) ReflectionUtils.getField(channelsField, this.undertow); } private Port getPortFromChannel(BoundChannel channel) { SocketAddress socketAddress = channel.getLocalAddress(); if (socketAddress instanceof InetSocketAddress) { - String protocol = (ReflectionUtils.findField(channel.getClass(), - "ssl") != null) ? "https" : "http"; + String protocol = (ReflectionUtils.findField(channel.getClass(), "ssl") != null) ? "https" : "http"; return new Port(((InetSocketAddress) socketAddress).getPort(), protocol); } return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index c1bc65e664e..840195341e1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -154,8 +154,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac * {@link Builder}. Calling this method will replace any existing customizers. * @param customizers the customizers to set */ - public void setBuilderCustomizers( - Collection customizers) { + public void setBuilderCustomizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.builderCustomizers = new ArrayList<>(customizers); } @@ -181,8 +180,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac * customizers. * @param customizers the customizers to set */ - public void setDeploymentInfoCustomizers( - Collection customizers) { + public void setDeploymentInfoCustomizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.deploymentInfoCustomizers = new ArrayList<>(customizers); } @@ -197,8 +195,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac } @Override - public void addDeploymentInfoCustomizers( - UndertowDeploymentInfoCustomizer... customizers) { + public void addDeploymentInfoCustomizers(UndertowDeploymentInfoCustomizer... customizers) { Assert.notNull(customizers, "UndertowDeploymentInfoCustomizers must not be null"); this.deploymentInfoCustomizers.addAll(Arrays.asList(customizers)); } @@ -238,8 +235,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac } private void customizeSsl(Builder builder) { - new SslBuilderCustomizer(getPort(), getAddress(), getSsl(), getSslStoreProvider()) - .customize(builder); + new SslBuilderCustomizer(getPort(), getAddress(), getSsl(), getSslStoreProvider()).customize(builder); if (getHttp2() != null) { builder.setServerOption(UndertowOptions.ENABLE_HTTP2, getHttp2().isEnabled()); } @@ -252,11 +248,9 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac return getAddress().getHostAddress(); } - private DeploymentManager createDeploymentManager( - ServletContextInitializer... initializers) { + private DeploymentManager createDeploymentManager(ServletContextInitializer... initializers) { DeploymentInfo deployment = Servlets.deployment(); - registerServletContainerInitializerToDriveServletContextInitializers(deployment, - initializers); + registerServletContainerInitializerToDriveServletContextInitializers(deployment, initializers); deployment.setClassLoader(getServletClassLoader()); deployment.setContextPath(getContextPath()); deployment.setDisplayName(getDisplayName()); @@ -284,74 +278,62 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac manager.deploy(); SessionManager sessionManager = manager.getDeployment().getSessionManager(); Duration timeoutDuration = getSession().getTimeout(); - int sessionTimeout = (isZeroOrLess(timeoutDuration) ? -1 - : (int) timeoutDuration.getSeconds()); + int sessionTimeout = (isZeroOrLess(timeoutDuration) ? -1 : (int) timeoutDuration.getSeconds()); sessionManager.setDefaultSessionTimeout(sessionTimeout); return manager; } private boolean isZeroOrLess(Duration timeoutDuration) { - return timeoutDuration == null || timeoutDuration.isZero() - || timeoutDuration.isNegative(); + return timeoutDuration == null || timeoutDuration.isZero() || timeoutDuration.isNegative(); } private void configureAccessLog(DeploymentInfo deploymentInfo) { try { createAccessLogDirectoryIfNecessary(); XnioWorker worker = createWorker(); - String prefix = (this.accessLogPrefix != null) ? this.accessLogPrefix - : "access_log."; - DefaultAccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver( - worker, this.accessLogDirectory, prefix, this.accessLogSuffix, - this.accessLogRotate); - EventListener listener = new AccessLogShutdownListener(worker, - accessLogReceiver); - deploymentInfo.addListener(new ListenerInfo(AccessLogShutdownListener.class, - new ImmediateInstanceFactory<>(listener))); - deploymentInfo.addInitialHandlerChainWrapper( - (handler) -> createAccessLogHandler(handler, accessLogReceiver)); + String prefix = (this.accessLogPrefix != null) ? this.accessLogPrefix : "access_log."; + DefaultAccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver(worker, this.accessLogDirectory, + prefix, this.accessLogSuffix, this.accessLogRotate); + EventListener listener = new AccessLogShutdownListener(worker, accessLogReceiver); + deploymentInfo.addListener( + new ListenerInfo(AccessLogShutdownListener.class, new ImmediateInstanceFactory<>(listener))); + deploymentInfo + .addInitialHandlerChainWrapper((handler) -> createAccessLogHandler(handler, accessLogReceiver)); } catch (IOException ex) { throw new IllegalStateException("Failed to create AccessLogHandler", ex); } } - private AccessLogHandler createAccessLogHandler(HttpHandler handler, - AccessLogReceiver accessLogReceiver) { + private AccessLogHandler createAccessLogHandler(HttpHandler handler, AccessLogReceiver accessLogReceiver) { createAccessLogDirectoryIfNecessary(); - String formatString = (this.accessLogPattern != null) ? this.accessLogPattern - : "common"; - return new AccessLogHandler(handler, accessLogReceiver, formatString, - Undertow.class.getClassLoader()); + String formatString = (this.accessLogPattern != null) ? this.accessLogPattern : "common"; + return new AccessLogHandler(handler, accessLogReceiver, formatString, Undertow.class.getClassLoader()); } private void createAccessLogDirectoryIfNecessary() { Assert.state(this.accessLogDirectory != null, "Access log directory is not set"); if (!this.accessLogDirectory.isDirectory() && !this.accessLogDirectory.mkdirs()) { - throw new IllegalStateException("Failed to create access log directory '" - + this.accessLogDirectory + "'"); + throw new IllegalStateException("Failed to create access log directory '" + this.accessLogDirectory + "'"); } } private XnioWorker createWorker() throws IOException { Xnio xnio = Xnio.getInstance(Undertow.class.getClassLoader()); - return xnio.createWorker( - OptionMap.builder().set(Options.THREAD_DAEMON, true).getMap()); + return xnio.createWorker(OptionMap.builder().set(Options.THREAD_DAEMON, true).getMap()); } private void addLocaleMappings(DeploymentInfo deployment) { - getLocaleCharsetMappings().forEach((locale, charset) -> deployment - .addLocaleCharsetMapping(locale.toString(), charset.toString())); + getLocaleCharsetMappings().forEach( + (locale, charset) -> deployment.addLocaleCharsetMapping(locale.toString(), charset.toString())); } - private void registerServletContainerInitializerToDriveServletContextInitializers( - DeploymentInfo deployment, ServletContextInitializer... initializers) { + private void registerServletContainerInitializerToDriveServletContextInitializers(DeploymentInfo deployment, + ServletContextInitializer... initializers) { ServletContextInitializer[] mergedInitializers = mergeInitializers(initializers); Initializer initializer = new Initializer(mergedInitializers); - deployment.addServletContainerInitializer(new ServletContainerInitializerInfo( - Initializer.class, - new ImmediateInstanceFactory(initializer), - NO_CLASSES)); + deployment.addServletContainerInitializer(new ServletContainerInitializerInfo(Initializer.class, + new ImmediateInstanceFactory(initializer), NO_CLASSES)); } private ClassLoader getServletClassLoader() { @@ -367,8 +349,8 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac List metaInfResourceUrls = getUrlsOfJarsWithMetaInfResources(); List resourceJarUrls = new ArrayList<>(); List managers = new ArrayList<>(); - ResourceManager rootManager = (docBase.isDirectory() - ? new FileResourceManager(docBase, 0) : new JarResourceManager(docBase)); + ResourceManager rootManager = (docBase.isDirectory() ? new FileResourceManager(docBase, 0) + : new JarResourceManager(docBase)); if (root != null) { rootManager = new LoaderHidingResourceManager(rootManager); } @@ -381,8 +363,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac resourceJarUrls.add(new URL("jar:" + url + "!/")); } else { - managers.add(new FileResourceManager( - new File(file, "META-INF/resources"), 0)); + managers.add(new FileResourceManager(new File(file, "META-INF/resources"), 0)); } } catch (Exception ex) { @@ -415,20 +396,17 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac private io.undertow.servlet.api.ErrorPage getUndertowErrorPage(ErrorPage errorPage) { if (errorPage.getStatus() != null) { - return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), - errorPage.getStatusCode()); + return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), errorPage.getStatusCode()); } if (errorPage.getException() != null) { - return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), - errorPage.getException()); + return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), errorPage.getException()); } return new io.undertow.servlet.api.ErrorPage(errorPage.getPath()); } private void configureMimeMappings(DeploymentInfo servletBuilder) { for (Mapping mimeMapping : getMimeMappings()) { - servletBuilder.addMimeMapping(new MimeMapping(mimeMapping.getExtension(), - mimeMapping.getMimeType())); + servletBuilder.addMimeMapping(new MimeMapping(mimeMapping.getExtension(), mimeMapping.getMimeType())); } } @@ -442,10 +420,9 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac * @param port the port that Undertow should listen on * @return a new {@link UndertowServletWebServer} instance */ - protected UndertowServletWebServer getUndertowWebServer(Builder builder, - DeploymentManager manager, int port) { - return new UndertowServletWebServer(builder, manager, getContextPath(), - isUseForwardHeaders(), port >= 0, getCompression(), getServerHeader()); + protected UndertowServletWebServer getUndertowWebServer(Builder builder, DeploymentManager manager, int port) { + return new UndertowServletWebServer(builder, manager, getContextPath(), isUseForwardHeaders(), port >= 0, + getCompression(), getServerHeader()); } @Override @@ -543,8 +520,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac * {@link ResourceManager} that exposes resource in {@code META-INF/resources} * directory of nested (in {@code BOOT-INF/lib} or {@code WEB-INF/lib}) jars. */ - private static final class MetaInfResourcesResourceManager - implements ResourceManager { + private static final class MetaInfResourcesResourceManager implements ResourceManager { private final List metaInfResourceJarUrls; @@ -610,8 +586,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac } @Override - public void onStartup(Set> classes, ServletContext servletContext) - throws ServletException { + public void onStartup(Set> classes, ServletContext servletContext) throws ServletException { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); } @@ -663,8 +638,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac private final DefaultAccessLogReceiver accessLogReceiver; - AccessLogShutdownListener(XnioWorker worker, - DefaultAccessLogReceiver accessLogReceiver) { + AccessLogShutdownListener(XnioWorker worker, DefaultAccessLogReceiver accessLogReceiver) { this.worker = worker; this.accessLogReceiver = accessLogReceiver; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java index 5fd88caf7aa..6f099dbdb6b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java @@ -79,8 +79,7 @@ public class UndertowWebServer implements WebServer { * @param closeable called when the server is stopped * @since 2.0.4 */ - public UndertowWebServer(Undertow.Builder builder, boolean autoStart, - Closeable closeable) { + public UndertowWebServer(Undertow.Builder builder, boolean autoStart, Closeable closeable) { this.builder = builder; this.autoStart = autoStart; this.closeable = closeable; @@ -110,8 +109,7 @@ public class UndertowWebServer implements WebServer { List actualPorts = getActualPorts(); failedPorts.removeAll(actualPorts); if (failedPorts.size() == 1) { - throw new PortInUseException( - failedPorts.iterator().next().getNumber()); + throw new PortInUseException(failedPorts.iterator().next().getNumber()); } } throw new WebServerException("Unable to start embedded Undertow", ex); @@ -176,8 +174,7 @@ public class UndertowWebServer implements WebServer { private List extractChannels() { Field channelsField = ReflectionUtils.findField(Undertow.class, "channels"); ReflectionUtils.makeAccessible(channelsField); - return (List) ReflectionUtils.getField(channelsField, - this.undertow); + return (List) ReflectionUtils.getField(channelsField, this.undertow); } private UndertowWebServer.Port getPortFromChannel(BoundChannel channel) { @@ -185,8 +182,7 @@ public class UndertowWebServer implements WebServer { if (socketAddress instanceof InetSocketAddress) { Field sslField = ReflectionUtils.findField(channel.getClass(), "ssl"); String protocol = (sslField != null) ? "https" : "http"; - return new UndertowWebServer.Port( - ((InetSocketAddress) socketAddress).getPort(), protocol); + return new UndertowWebServer.Port(((InetSocketAddress) socketAddress).getPort(), protocol); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebApplicationContext.java index dafe464e405..27f4afe181b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebApplicationContext.java @@ -46,8 +46,7 @@ import org.springframework.stereotype.Component; * @since 2.0.0 * @see AnnotationConfigApplicationContext */ -public class AnnotationConfigReactiveWebApplicationContext - extends AnnotationConfigApplicationContext +public class AnnotationConfigReactiveWebApplicationContext extends AnnotationConfigApplicationContext implements ConfigurableReactiveWebApplicationContext { /** @@ -64,8 +63,7 @@ public class AnnotationConfigReactiveWebApplicationContext * @param beanFactory the DefaultListableBeanFactory instance to use for this context * @since 2.2.0 */ - public AnnotationConfigReactiveWebApplicationContext( - DefaultListableBeanFactory beanFactory) { + public AnnotationConfigReactiveWebApplicationContext(DefaultListableBeanFactory beanFactory) { super(beanFactory); } @@ -172,8 +170,7 @@ public class AnnotationConfigReactiveWebApplicationContext * {@code AbstractRefreshableConfigApplicationContext} */ @Deprecated - protected AnnotatedBeanDefinitionReader getAnnotatedBeanDefinitionReader( - DefaultListableBeanFactory beanFactory) { + protected AnnotatedBeanDefinitionReader getAnnotatedBeanDefinitionReader(DefaultListableBeanFactory beanFactory) { throw new UnsupportedOperationException(); } @@ -191,8 +188,7 @@ public class AnnotationConfigReactiveWebApplicationContext * {@code AbstractRefreshableConfigApplicationContext} */ @Deprecated - protected ClassPathBeanDefinitionScanner getClassPathBeanDefinitionScanner( - DefaultListableBeanFactory beanFactory) { + protected ClassPathBeanDefinitionScanner getClassPathBeanDefinitionScanner(DefaultListableBeanFactory beanFactory) { throw new UnsupportedOperationException(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContext.java index 7e960ab0632..cf2459ae10d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContext.java @@ -56,8 +56,8 @@ import org.springframework.util.ObjectUtils; * @see ReactiveWebServerApplicationContext * @see AnnotationConfigApplicationContext */ -public class AnnotationConfigReactiveWebServerApplicationContext - extends ReactiveWebServerApplicationContext implements AnnotationConfigRegistry { +public class AnnotationConfigReactiveWebServerApplicationContext extends ReactiveWebServerApplicationContext + implements AnnotationConfigRegistry { private final AnnotatedBeanDefinitionReader reader; @@ -83,8 +83,7 @@ public class AnnotationConfigReactiveWebServerApplicationContext * {@link #register} calls and then manually {@linkplain #refresh refreshed}. * @param beanFactory the DefaultListableBeanFactory instance to use for this context */ - public AnnotationConfigReactiveWebServerApplicationContext( - DefaultListableBeanFactory beanFactory) { + public AnnotationConfigReactiveWebServerApplicationContext(DefaultListableBeanFactory beanFactory) { super(beanFactory); this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); @@ -97,8 +96,7 @@ public class AnnotationConfigReactiveWebServerApplicationContext * @param annotatedClasses one or more annotated classes, e.g. {@code @Configuration} * classes */ - public AnnotationConfigReactiveWebServerApplicationContext( - Class... annotatedClasses) { + public AnnotationConfigReactiveWebServerApplicationContext(Class... annotatedClasses) { this(); register(annotatedClasses); refresh(); @@ -146,8 +144,7 @@ public class AnnotationConfigReactiveWebServerApplicationContext public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.reader.setBeanNameGenerator(beanNameGenerator); this.scanner.setBeanNameGenerator(beanNameGenerator); - this.getBeanFactory().registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, + this.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator); } @@ -179,8 +176,7 @@ public class AnnotationConfigReactiveWebServerApplicationContext */ @Override public final void register(Class... annotatedClasses) { - Assert.notEmpty(annotatedClasses, - "At least one annotated class must be specified"); + Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); this.annotatedClasses.addAll(Arrays.asList(annotatedClasses)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/FilteredReactiveWebContextResource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/FilteredReactiveWebContextResource.java index b7e3374a740..facf90e0512 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/FilteredReactiveWebContextResource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/FilteredReactiveWebContextResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ class FilteredReactiveWebContextResource extends AbstractResource { @Override public InputStream getInputStream() throws IOException { - throw new FileNotFoundException( - this.getDescription() + " cannot be opened because it does not exist"); + throw new FileNotFoundException(this.getDescription() + " cannot be opened because it does not exist"); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContext.java index 1f39aac83fb..fe723dc66fa 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContext.java @@ -38,8 +38,7 @@ import org.springframework.util.StringUtils; * @author Brian Clozel * @since 2.0.0 */ -public class ReactiveWebServerApplicationContext - extends GenericReactiveWebApplicationContext +public class ReactiveWebServerApplicationContext extends GenericReactiveWebApplicationContext implements ConfigurableWebServerApplicationContext { private volatile ServerManager serverManager; @@ -79,8 +78,7 @@ public class ReactiveWebServerApplicationContext createWebServer(); } catch (Throwable ex) { - throw new ApplicationContextException("Unable to start reactive web server", - ex); + throw new ApplicationContextException("Unable to start reactive web server", ex); } } @@ -88,10 +86,8 @@ public class ReactiveWebServerApplicationContext ServerManager serverManager = this.serverManager; if (serverManager == null) { String webServerFactoryBeanName = getWebServerFactoryBeanName(); - ReactiveWebServerFactory webServerFactory = getWebServerFactory( - webServerFactoryBeanName); - boolean lazyInit = getBeanFactory() - .getBeanDefinition(webServerFactoryBeanName).isLazyInit(); + ReactiveWebServerFactory webServerFactory = getWebServerFactory(webServerFactoryBeanName); + boolean lazyInit = getBeanFactory().getBeanDefinition(webServerFactoryBeanName).isLazyInit(); this.serverManager = ServerManager.get(webServerFactory, lazyInit); } initPropertySources(); @@ -99,18 +95,14 @@ public class ReactiveWebServerApplicationContext protected String getWebServerFactoryBeanName() { // Use bean names so that we don't consider the hierarchy - String[] beanNames = getBeanFactory() - .getBeanNamesForType(ReactiveWebServerFactory.class); + String[] beanNames = getBeanFactory().getBeanNamesForType(ReactiveWebServerFactory.class); if (beanNames.length == 0) { throw new ApplicationContextException( - "Unable to start ReactiveWebApplicationContext due to missing " - + "ReactiveWebServerFactory bean."); + "Unable to start ReactiveWebApplicationContext due to missing " + "ReactiveWebServerFactory bean."); } if (beanNames.length > 1) { - throw new ApplicationContextException( - "Unable to start ReactiveWebApplicationContext due to multiple " - + "ReactiveWebServerFactory beans : " - + StringUtils.arrayToCommaDelimitedString(beanNames)); + throw new ApplicationContextException("Unable to start ReactiveWebApplicationContext due to multiple " + + "ReactiveWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } return beanNames[0]; } @@ -239,10 +231,8 @@ public class ReactiveWebServerApplicationContext this.lazyInit = lazyInit; } - private Mono handleUninitialized(ServerHttpRequest request, - ServerHttpResponse response) { - throw new IllegalStateException( - "The HttpHandler has not yet been initialized"); + private Mono handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) { + throw new IllegalStateException("The HttpHandler has not yet been initialized"); } @Override @@ -254,8 +244,7 @@ public class ReactiveWebServerApplicationContext return this.handler; } - public static ServerManager get(ReactiveWebServerFactory factory, - boolean lazyInit) { + public static ServerManager get(ReactiveWebServerFactory factory, boolean lazyInit) { return new ServerManager(factory, lazyInit); } @@ -263,11 +252,9 @@ public class ReactiveWebServerApplicationContext return (manager != null) ? manager.server : null; } - public static void start(ServerManager manager, - Supplier handlerSupplier) { + public static void start(ServerManager manager, Supplier handlerSupplier) { if (manager != null && manager.server != null) { - manager.handler = manager.lazyInit - ? new LazyHttpHandler(Mono.fromSupplier(handlerSupplier)) + manager.handler = manager.lazyInit ? new LazyHttpHandler(Mono.fromSupplier(handlerSupplier)) : handlerSupplier.get(); manager.server.start(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/StandardReactiveWebEnvironment.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/StandardReactiveWebEnvironment.java index ae4b5876f07..69676174174 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/StandardReactiveWebEnvironment.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/StandardReactiveWebEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import org.springframework.core.env.StandardEnvironment; * @author Phillip Webb * @since 2.0.0 */ -public class StandardReactiveWebEnvironment extends StandardEnvironment - implements ConfigurableReactiveWebEnvironment { +public class StandardReactiveWebEnvironment extends StandardEnvironment implements ConfigurableReactiveWebEnvironment { } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java index ccf1682c998..551d8da174d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java @@ -57,8 +57,7 @@ import org.springframework.web.server.ServerWebExchange; */ public class DefaultErrorAttributes implements ErrorAttributes { - private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() - + ".ERROR"; + private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() + ".ERROR"; private final boolean includeException; @@ -79,15 +78,13 @@ public class DefaultErrorAttributes implements ErrorAttributes { } @Override - public Map getErrorAttributes(ServerRequest request, - boolean includeStackTrace) { + public Map getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Map errorAttributes = new LinkedHashMap<>(); errorAttributes.put("timestamp", new Date()); errorAttributes.put("path", request.path()); Throwable error = getError(request); MergedAnnotation responseStatusAnnotation = MergedAnnotations - .from(error.getClass(), SearchStrategy.EXHAUSTIVE) - .get(ResponseStatus.class); + .from(error.getClass(), SearchStrategy.EXHAUSTIVE).get(ResponseStatus.class); HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation); errorAttributes.put("status", errorStatus.value()); errorAttributes.put("error", errorStatus.getReasonPhrase()); @@ -98,25 +95,21 @@ public class DefaultErrorAttributes implements ErrorAttributes { return errorAttributes; } - private HttpStatus determineHttpStatus(Throwable error, - MergedAnnotation responseStatusAnnotation) { + private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation responseStatusAnnotation) { if (error instanceof ResponseStatusException) { return ((ResponseStatusException) error).getStatus(); } - return responseStatusAnnotation.getValue("code", HttpStatus.class) - .orElse(HttpStatus.INTERNAL_SERVER_ERROR); + return responseStatusAnnotation.getValue("code", HttpStatus.class).orElse(HttpStatus.INTERNAL_SERVER_ERROR); } - private String determineMessage(Throwable error, - MergedAnnotation responseStatusAnnotation) { + private String determineMessage(Throwable error, MergedAnnotation responseStatusAnnotation) { if (error instanceof WebExchangeBindException) { return error.getMessage(); } if (error instanceof ResponseStatusException) { return ((ResponseStatusException) error).getReason(); } - return responseStatusAnnotation.getValue("reason", String.class) - .orElseGet(error::getMessage); + return responseStatusAnnotation.getValue("reason", String.class).orElseGet(error::getMessage); } private Throwable determineException(Throwable error) { @@ -133,8 +126,7 @@ public class DefaultErrorAttributes implements ErrorAttributes { errorAttributes.put("trace", stackTrace.toString()); } - private void handleException(Map errorAttributes, Throwable error, - boolean includeStackTrace) { + private void handleException(Map errorAttributes, Throwable error, boolean includeStackTrace) { if (this.includeException) { errorAttributes.put("exception", error.getClass().getName()); } @@ -152,8 +144,7 @@ public class DefaultErrorAttributes implements ErrorAttributes { @Override public Throwable getError(ServerRequest request) { return (Throwable) request.attribute(ERROR_ATTRIBUTE) - .orElseThrow(() -> new IllegalStateException( - "Missing exception attribute in ServerWebExchange")); + .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange")); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorAttributes.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorAttributes.java index 9e535e488a3..2791619033c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorAttributes.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ public interface ErrorAttributes { * @param includeStackTrace if stack trace elements should be included * @return a map of error attributes */ - Map getErrorAttributes(ServerRequest request, - boolean includeStackTrace); + Map getErrorAttributes(ServerRequest request, boolean includeStackTrace); /** * Return the underlying cause of the error or {@code null} if the error cannot be diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/filter/OrderedHiddenHttpMethodFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/filter/OrderedHiddenHttpMethodFilter.java index 447d0e294ec..978222c7c25 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/filter/OrderedHiddenHttpMethodFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/filter/OrderedHiddenHttpMethodFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.web.filter.reactive.HiddenHttpMethodFilter; * @author Artsiom Yudovin * @since 2.0.5 */ -public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter - implements OrderedWebFilter { +public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter implements OrderedWebFilter { /** * The default order is high to ensure the filter is applied before Spring Security. diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java index 5a6e4bedcf5..a5ba093e834 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,19 +75,17 @@ public class MustacheView extends AbstractUrlBasedView { } @Override - protected Mono renderInternal(Map model, MediaType contentType, - ServerWebExchange exchange) { + protected Mono renderInternal(Map model, MediaType contentType, ServerWebExchange exchange) { Resource resource = resolveResource(); if (resource == null) { - return Mono.error(new IllegalStateException( - "Could not find Mustache template with URL [" + getUrl() + "]")); + return Mono + .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); } DataBuffer dataBuffer = exchange.getResponse().bufferFactory().allocateBuffer(); try (Reader reader = getReader(resource)) { Template template = this.compiler.compile(reader); Charset charset = getCharset(contentType).orElse(getDefaultCharset()); - try (Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream(), - charset)) { + try (Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream(), charset)) { template.execute(model, writer); writer.flush(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactory.java index e2412058140..227261938b7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ import org.springframework.boot.web.server.AbstractConfigurableWebServerFactory; * @author Brian Clozel * @since 2.0.0 */ -public abstract class AbstractReactiveWebServerFactory - extends AbstractConfigurableWebServerFactory +public abstract class AbstractReactiveWebServerFactory extends AbstractConfigurableWebServerFactory implements ConfigurableReactiveWebServerFactory { public AbstractReactiveWebServerFactory() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/ConfigurableReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/ConfigurableReactiveWebServerFactory.java index cfdd5ea7ee9..698f8d145c0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/ConfigurableReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/server/ConfigurableReactiveWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.springframework.boot.web.server.ConfigurableWebServerFactory; * @author Brian Clozel * @since 2.0.0 */ -public interface ConfigurableReactiveWebServerFactory - extends ConfigurableWebServerFactory, ReactiveWebServerFactory { +public interface ConfigurableReactiveWebServerFactory extends ConfigurableWebServerFactory, ReactiveWebServerFactory { } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/AbstractConfigurableWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/AbstractConfigurableWebServerFactory.java index 80073c72302..2b136064ed0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/AbstractConfigurableWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/AbstractConfigurableWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.util.Assert; * @author Brian Clozel * @since 2.0.0 */ -public abstract class AbstractConfigurableWebServerFactory - implements ConfigurableWebServerFactory { +public abstract class AbstractConfigurableWebServerFactory implements ConfigurableWebServerFactory { private int port = 8080; @@ -178,9 +177,7 @@ public abstract class AbstractConfigurableWebServerFactory } catch (IOException ex) { throw new WebServerException( - "Unable to create tempDir. java.io.tmpdir is set to " - + System.getProperty("java.io.tmpdir"), - ex); + "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/Compression.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/Compression.java index 147d61e7248..1f894939aca 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/Compression.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/Compression.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,9 +30,8 @@ public class Compression { private boolean enabled = false; - private String[] mimeTypes = new String[] { "text/html", "text/xml", "text/plain", - "text/css", "text/javascript", "application/javascript", "application/json", - "application/xml" }; + private String[] mimeTypes = new String[] { "text/html", "text/xml", "text/plain", "text/css", "text/javascript", + "application/javascript", "application/json", "application/xml" }; private String[] excludedUserAgents = null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ConfigurableWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ConfigurableWebServerFactory.java index ce9785b0057..d9890298f54 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ConfigurableWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ConfigurableWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import java.util.Set; * @since 2.0.0 * @see ErrorPageRegistry */ -public interface ConfigurableWebServerFactory - extends WebServerFactory, ErrorPageRegistry { +public interface ConfigurableWebServerFactory extends WebServerFactory, ErrorPageRegistry { /** * Sets the port that the web server should listen on. If not specified port '8080' diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java index 64e28b9d908..b49cee29d59 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,8 +115,7 @@ public class ErrorPage { if (obj instanceof ErrorPage) { ErrorPage other = (ErrorPage) obj; boolean rtn = true; - rtn = rtn && ObjectUtils.nullSafeEquals(getExceptionName(), - other.getExceptionName()); + rtn = rtn && ObjectUtils.nullSafeEquals(getExceptionName(), other.getExceptionName()); rtn = rtn && ObjectUtils.nullSafeEquals(this.path, other.path); rtn = rtn && this.status == other.status; return rtn; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java index e89970ff654..bbe72b12bdb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.util.Assert; * @author Stephane Nicoll * @since 2.0.0 */ -public class ErrorPageRegistrarBeanPostProcessor - implements BeanPostProcessor, BeanFactoryAware { +public class ErrorPageRegistrarBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { private ListableBeanFactory beanFactory; @@ -47,14 +46,12 @@ public class ErrorPageRegistrarBeanPostProcessor @Override public void setBeanFactory(BeanFactory beanFactory) { Assert.isInstanceOf(ListableBeanFactory.class, beanFactory, - "ErrorPageRegistrarBeanPostProcessor can only be used " - + "with a ListableBeanFactory"); + "ErrorPageRegistrarBeanPostProcessor can only be used " + "with a ListableBeanFactory"); this.beanFactory = (ListableBeanFactory) beanFactory; } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ErrorPageRegistry) { postProcessBeforeInitialization((ErrorPageRegistry) bean); } @@ -62,8 +59,7 @@ public class ErrorPageRegistrarBeanPostProcessor } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @@ -76,8 +72,8 @@ public class ErrorPageRegistrarBeanPostProcessor private Collection getRegistrars() { if (this.registrars == null) { // Look up does not include the parent context - this.registrars = new ArrayList<>(this.beanFactory - .getBeansOfType(ErrorPageRegistrar.class, false, false).values()); + this.registrars = new ArrayList<>( + this.beanFactory.getBeansOfType(ErrorPageRegistrar.class, false, false).values()); this.registrars.sort(AnnotationAwareOrderComparator.INSTANCE); this.registrars = Collections.unmodifiableList(this.registrars); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java index d256935a378..07d2e2893c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Value; * @author Stephane Nicoll * @since 2.0.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Value("${local.server.port}") diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java index 7fb2c9a1871..2cda5234e8c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -254,8 +254,7 @@ public final class MimeMappings implements Iterable { */ private MimeMappings(MimeMappings mappings, boolean mutable) { Assert.notNull(mappings, "Mappings must not be null"); - this.map = (mutable ? new LinkedHashMap<>(mappings.map) - : Collections.unmodifiableMap(mappings.map)); + this.map = (mutable ? new LinkedHashMap<>(mappings.map) : Collections.unmodifiableMap(mappings.map)); } @Override @@ -366,8 +365,7 @@ public final class MimeMappings implements Iterable { } if (obj instanceof Mapping) { Mapping other = (Mapping) obj; - return this.extension.equals(other.extension) - && this.mimeType.equals(other.mimeType); + return this.extension.equals(other.extension) && this.mimeType.equals(other.mimeType); } return false; } @@ -379,8 +377,7 @@ public final class MimeMappings implements Iterable { @Override public String toString() { - return "Mapping [extension=" + this.extension + ", mimeType=" + this.mimeType - + "]"; + return "Mapping [extension=" + this.extension + ", mimeType=" + this.mimeType + "]"; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java index 8b3efe9117d..e2485300e61 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,7 @@ import org.springframework.util.Assert; * @author Stephane Nicoll * @since 2.0.0 */ -public class WebServerFactoryCustomizerBeanPostProcessor - implements BeanPostProcessor, BeanFactoryAware { +public class WebServerFactoryCustomizerBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { private ListableBeanFactory beanFactory; @@ -49,14 +48,12 @@ public class WebServerFactoryCustomizerBeanPostProcessor @Override public void setBeanFactory(BeanFactory beanFactory) { Assert.isInstanceOf(ListableBeanFactory.class, beanFactory, - "WebServerCustomizerBeanPostProcessor can only be used " - + "with a ListableBeanFactory"); + "WebServerCustomizerBeanPostProcessor can only be used " + "with a ListableBeanFactory"); this.beanFactory = (ListableBeanFactory) beanFactory; } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebServerFactory) { postProcessBeforeInitialization((WebServerFactory) bean); } @@ -64,16 +61,13 @@ public class WebServerFactoryCustomizerBeanPostProcessor } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @SuppressWarnings("unchecked") private void postProcessBeforeInitialization(WebServerFactory webServerFactory) { - LambdaSafe - .callbacks(WebServerFactoryCustomizer.class, getCustomizers(), - webServerFactory) + LambdaSafe.callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory) .withLogger(WebServerFactoryCustomizerBeanPostProcessor.class) .invoke((customizer) -> customizer.customize(webServerFactory)); } @@ -90,8 +84,7 @@ public class WebServerFactoryCustomizerBeanPostProcessor @SuppressWarnings({ "unchecked", "rawtypes" }) private Collection> getWebServerFactoryCustomizerBeans() { - return (Collection) this.beanFactory - .getBeansOfType(WebServerFactoryCustomizer.class, false, false).values(); + return (Collection) this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false).values(); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java index 4cc5eed61af..552e202dbf2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java @@ -41,8 +41,7 @@ import org.springframework.util.StringUtils; * @author Brian Clozel * @since 2.0.1 */ -public abstract class AbstractFilterRegistrationBean - extends DynamicRegistrationBean { +public abstract class AbstractFilterRegistrationBean extends DynamicRegistrationBean { private static final String[] DEFAULT_URL_MAPPINGS = { "/*" }; @@ -61,10 +60,8 @@ public abstract class AbstractFilterRegistrationBean * {@link ServletRegistrationBean}s. * @param servletRegistrationBeans associate {@link ServletRegistrationBean}s */ - AbstractFilterRegistrationBean( - ServletRegistrationBean... servletRegistrationBeans) { - Assert.notNull(servletRegistrationBeans, - "ServletRegistrationBeans must not be null"); + AbstractFilterRegistrationBean(ServletRegistrationBean... servletRegistrationBeans) { + Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); Collections.addAll(this.servletRegistrationBeans, servletRegistrationBeans); } @@ -72,10 +69,8 @@ public abstract class AbstractFilterRegistrationBean * Set {@link ServletRegistrationBean}s that the filter will be registered against. * @param servletRegistrationBeans the Servlet registration beans */ - public void setServletRegistrationBeans( - Collection> servletRegistrationBeans) { - Assert.notNull(servletRegistrationBeans, - "ServletRegistrationBeans must not be null"); + public void setServletRegistrationBeans(Collection> servletRegistrationBeans) { + Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); this.servletRegistrationBeans = new LinkedHashSet<>(servletRegistrationBeans); } @@ -95,10 +90,8 @@ public abstract class AbstractFilterRegistrationBean * @param servletRegistrationBeans the servlet registration beans to add * @see #setServletRegistrationBeans */ - public void addServletRegistrationBeans( - ServletRegistrationBean... servletRegistrationBeans) { - Assert.notNull(servletRegistrationBeans, - "ServletRegistrationBeans must not be null"); + public void addServletRegistrationBeans(ServletRegistrationBean... servletRegistrationBeans) { + Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); Collections.addAll(this.servletRegistrationBeans, servletRegistrationBeans); } @@ -233,8 +226,7 @@ public abstract class AbstractFilterRegistrationBean } servletNames.addAll(this.servletNames); if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) { - registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, - DEFAULT_URL_MAPPINGS); + registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS); } else { if (!servletNames.isEmpty()) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java index b23ed416e8b..9c1bceacfd2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ import org.springframework.web.filter.DelegatingFilterProxy; * @see FilterRegistrationBean * @see DelegatingFilterProxy */ -public class DelegatingFilterProxyRegistrationBean - extends AbstractFilterRegistrationBean +public class DelegatingFilterProxyRegistrationBean extends AbstractFilterRegistrationBean implements ApplicationContextAware { private ApplicationContext applicationContext; @@ -75,8 +74,7 @@ public class DelegatingFilterProxyRegistrationBean } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -86,8 +84,7 @@ public class DelegatingFilterProxyRegistrationBean @Override public DelegatingFilterProxy getFilter() { - return new DelegatingFilterProxy(this.targetBeanName, - getWebApplicationContext()) { + return new DelegatingFilterProxy(this.targetBeanName, getWebApplicationContext()) { @Override protected void initFilterBean() throws ServletException { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DynamicRegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DynamicRegistrationBean.java index 08ed3513809..944812e8beb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DynamicRegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DynamicRegistrationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @since 2.0.0 */ -public abstract class DynamicRegistrationBean - extends RegistrationBean { +public abstract class DynamicRegistrationBean extends RegistrationBean { private static final Log logger = LogFactory.getLog(RegistrationBean.class); @@ -108,15 +107,14 @@ public abstract class DynamicRegistrationBean protected final void register(String description, ServletContext servletContext) { D registration = addRegistration(description, servletContext); if (registration == null) { - logger.info(StringUtils.capitalize(description) + " was not registered " - + "(possibly already registered?)"); + logger.info( + StringUtils.capitalize(description) + " was not registered " + "(possibly already registered?)"); return; } configure(registration); } - protected abstract D addRegistration(String description, - ServletContext servletContext); + protected abstract D addRegistration(String description, ServletContext servletContext); protected void configure(D registration) { registration.setAsyncSupported(this.asyncSupported); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java index 5c918c95c26..8a84b63dfb2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java @@ -40,8 +40,7 @@ import org.springframework.util.Assert; * @see ServletContext#addFilter(String, Filter) * @see DelegatingFilterProxyRegistrationBean */ -public class FilterRegistrationBean - extends AbstractFilterRegistrationBean { +public class FilterRegistrationBean extends AbstractFilterRegistrationBean { private T filter; @@ -57,8 +56,7 @@ public class FilterRegistrationBean * @param filter the filter to register * @param servletRegistrationBeans associate {@link ServletRegistrationBean}s */ - public FilterRegistrationBean(T filter, - ServletRegistrationBean... servletRegistrationBeans) { + public FilterRegistrationBean(T filter, ServletRegistrationBean... servletRegistrationBeans) { super(servletRegistrationBeans); Assert.notNull(filter, "Filter must not be null"); this.filter = filter; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java index 30fba2f9e06..a2fa68d4c4b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java @@ -78,8 +78,8 @@ public class MultipartConfigFactory { long maxFileSizeBytes = convertToBytes(this.maxFileSize, -1); long maxRequestSizeBytes = convertToBytes(this.maxRequestSize, -1); long fileSizeThresholdBytes = convertToBytes(this.fileSizeThreshold, 0); - return new MultipartConfigElement(this.location, maxFileSizeBytes, - maxRequestSizeBytes, (int) fileSizeThresholdBytes); + return new MultipartConfigElement(this.location, maxFileSizeBytes, maxRequestSizeBytes, + (int) fileSizeThresholdBytes); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java index e961d181e61..9e0897f8775 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ public abstract class RegistrationBean implements ServletContextInitializer, Ord public final void onStartup(ServletContext servletContext) throws ServletException { String description = getDescription(); if (!isEnabled()) { - logger.info(StringUtils.capitalize(description) - + " was not registered (disabled)"); + logger.info(StringUtils.capitalize(description) + " was not registered (disabled)"); return; } register(description, servletContext); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java index 0fa147fd6e2..1ac3530d3c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,18 +52,15 @@ abstract class ServletComponentHandler { String[] value = (String[]) attributes.get("value"); String[] urlPatterns = (String[]) attributes.get("urlPatterns"); if (urlPatterns.length > 0) { - Assert.state(value.length == 0, - "The urlPatterns and value attributes are mutually exclusive."); + Assert.state(value.length == 0, "The urlPatterns and value attributes are mutually exclusive."); return urlPatterns; } return value; } - protected final Map extractInitParameters( - Map attributes) { + protected final Map extractInitParameters(Map attributes) { Map initParameters = new HashMap<>(); - for (AnnotationAttributes initParam : (AnnotationAttributes[]) attributes - .get("initParams")) { + for (AnnotationAttributes initParam : (AnnotationAttributes[]) attributes.get("initParams")) { String name = (String) initParam.get("name"); String value = (String) initParam.get("value"); initParameters.put(name, value); @@ -71,8 +68,7 @@ abstract class ServletComponentHandler { return initParameters; } - void handle(ScannedGenericBeanDefinition beanDefinition, - BeanDefinitionRegistry registry) { + void handle(ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { Map attributes = beanDefinition.getMetadata() .getAnnotationAttributes(this.annotationType.getName()); if (attributes != null) { @@ -80,7 +76,7 @@ abstract class ServletComponentHandler { } } - protected abstract void doHandle(Map attributes, - ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry); + protected abstract void doHandle(Map attributes, ScannedGenericBeanDefinition beanDefinition, + BeanDefinitionRegistry registry); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java index 95c64e913c0..ebe21afd544 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ import org.springframework.web.context.WebApplicationContext; * @see ServletComponentScan * @see ServletComponentScanRegistrar */ -class ServletComponentRegisteringPostProcessor - implements BeanFactoryPostProcessor, ApplicationContextAware { +class ServletComponentRegisteringPostProcessor implements BeanFactoryPostProcessor, ApplicationContextAware { private static final List HANDLERS; @@ -62,8 +61,7 @@ class ServletComponentRegisteringPostProcessor } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (isRunningInEmbeddedWebServer()) { ClassPathScanningCandidateComponentProvider componentProvider = createComponentProvider(); for (String packageToScan : this.packagesToScan) { @@ -72,11 +70,8 @@ class ServletComponentRegisteringPostProcessor } } - private void scanPackage( - ClassPathScanningCandidateComponentProvider componentProvider, - String packageToScan) { - for (BeanDefinition candidate : componentProvider - .findCandidateComponents(packageToScan)) { + private void scanPackage(ClassPathScanningCandidateComponentProvider componentProvider, String packageToScan) { + for (BeanDefinition candidate : componentProvider.findCandidateComponents(packageToScan)) { if (candidate instanceof ScannedGenericBeanDefinition) { for (ServletComponentHandler handler : HANDLERS) { handler.handle(((ScannedGenericBeanDefinition) candidate), @@ -88,8 +83,7 @@ class ServletComponentRegisteringPostProcessor private boolean isRunningInEmbeddedWebServer() { return this.applicationContext instanceof WebApplicationContext - && ((WebApplicationContext) this.applicationContext) - .getServletContext() == null; + && ((WebApplicationContext) this.applicationContext).getServletContext() == null; } private ClassPathScanningCandidateComponentProvider createComponentProvider() { @@ -108,8 +102,7 @@ class ServletComponentRegisteringPostProcessor } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java index 2cd621934a5..32da4a6748e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java @@ -40,8 +40,7 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { private static final String BEAN_NAME = "servletComponentRegisteringPostProcessor"; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Set packagesToScan = getPackagesToScan(importingClassMetadata); if (registry.containsBeanDefinition(BEAN_NAME)) { updatePostProcessor(registry, packagesToScan); @@ -51,30 +50,26 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { } } - private void updatePostProcessor(BeanDefinitionRegistry registry, - Set packagesToScan) { + private void updatePostProcessor(BeanDefinitionRegistry registry, Set packagesToScan) { BeanDefinition definition = registry.getBeanDefinition(BEAN_NAME); - ValueHolder constructorArguments = definition.getConstructorArgumentValues() - .getGenericArgumentValue(Set.class); + ValueHolder constructorArguments = definition.getConstructorArgumentValues().getGenericArgumentValue(Set.class); @SuppressWarnings("unchecked") Set mergedPackages = (Set) constructorArguments.getValue(); mergedPackages.addAll(packagesToScan); constructorArguments.setValue(mergedPackages); } - private void addPostProcessor(BeanDefinitionRegistry registry, - Set packagesToScan) { + private void addPostProcessor(BeanDefinitionRegistry registry, Set packagesToScan) { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(ServletComponentRegisteringPostProcessor.class); - beanDefinition.getConstructorArgumentValues() - .addGenericArgumentValue(packagesToScan); + beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(packagesToScan); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, beanDefinition); } private Set getPackagesToScan(AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java index f08e31ab1cb..488545a6310 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java @@ -59,13 +59,11 @@ import org.springframework.util.MultiValueMap; * @author Brian Clozel * @since 1.4.0 */ -public class ServletContextInitializerBeans - extends AbstractCollection { +public class ServletContextInitializerBeans extends AbstractCollection { private static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet"; - private static final Log logger = LogFactory - .getLog(ServletContextInitializerBeans.class); + private static final Log logger = LogFactory.getLog(ServletContextInitializerBeans.class); /** * Seen bean instances or bean names. @@ -82,15 +80,12 @@ public class ServletContextInitializerBeans public ServletContextInitializerBeans(ListableBeanFactory beanFactory, Class... initializerTypes) { this.initializers = new LinkedMultiValueMap<>(); - this.initializerTypes = (initializerTypes.length != 0) - ? Arrays.asList(initializerTypes) + this.initializerTypes = (initializerTypes.length != 0) ? Arrays.asList(initializerTypes) : Collections.singletonList(ServletContextInitializer.class); addServletContextInitializerBeans(beanFactory); addAdaptableBeans(beanFactory); - List sortedInitializers = this.initializers.values() - .stream() - .flatMap((value) -> value.stream() - .sorted(AnnotationAwareOrderComparator.INSTANCE)) + List sortedInitializers = this.initializers.values().stream() + .flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE)) .collect(Collectors.toList()); this.sortedList = Collections.unmodifiableList(sortedInitializers); logMappings(this.initializers); @@ -98,47 +93,39 @@ public class ServletContextInitializerBeans private void addServletContextInitializerBeans(ListableBeanFactory beanFactory) { for (Class initializerType : this.initializerTypes) { - for (Entry initializerBean : getOrderedBeansOfType( - beanFactory, initializerType)) { - addServletContextInitializerBean(initializerBean.getKey(), - initializerBean.getValue(), beanFactory); + for (Entry initializerBean : getOrderedBeansOfType(beanFactory, + initializerType)) { + addServletContextInitializerBean(initializerBean.getKey(), initializerBean.getValue(), beanFactory); } } } - private void addServletContextInitializerBean(String beanName, - ServletContextInitializer initializer, ListableBeanFactory beanFactory) { + private void addServletContextInitializerBean(String beanName, ServletContextInitializer initializer, + ListableBeanFactory beanFactory) { if (initializer instanceof ServletRegistrationBean) { Servlet source = ((ServletRegistrationBean) initializer).getServlet(); - addServletContextInitializerBean(Servlet.class, beanName, initializer, - beanFactory, source); + addServletContextInitializerBean(Servlet.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof FilterRegistrationBean) { Filter source = ((FilterRegistrationBean) initializer).getFilter(); - addServletContextInitializerBean(Filter.class, beanName, initializer, - beanFactory, source); + addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof DelegatingFilterProxyRegistrationBean) { - String source = ((DelegatingFilterProxyRegistrationBean) initializer) - .getTargetBeanName(); - addServletContextInitializerBean(Filter.class, beanName, initializer, - beanFactory, source); + String source = ((DelegatingFilterProxyRegistrationBean) initializer).getTargetBeanName(); + addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof ServletListenerRegistrationBean) { - EventListener source = ((ServletListenerRegistrationBean) initializer) - .getListener(); - addServletContextInitializerBean(EventListener.class, beanName, initializer, - beanFactory, source); + EventListener source = ((ServletListenerRegistrationBean) initializer).getListener(); + addServletContextInitializerBean(EventListener.class, beanName, initializer, beanFactory, source); } else { - addServletContextInitializerBean(ServletContextInitializer.class, beanName, - initializer, beanFactory, initializer); + addServletContextInitializerBean(ServletContextInitializer.class, beanName, initializer, beanFactory, + initializer); } } - private void addServletContextInitializerBean(Class type, String beanName, - ServletContextInitializer initializer, ListableBeanFactory beanFactory, - Object source) { + private void addServletContextInitializerBean(Class type, String beanName, ServletContextInitializer initializer, + ListableBeanFactory beanFactory, Object source) { this.initializers.add(type, initializer); if (source != null) { // Mark the underlying source as seen in case it wraps an existing bean @@ -147,14 +134,12 @@ public class ServletContextInitializerBeans if (logger.isTraceEnabled()) { String resourceDescription = getResourceDescription(beanName, beanFactory); int order = getOrder(initializer); - logger.trace("Added existing " + type.getSimpleName() + " initializer bean '" - + beanName + "'; order=" + order + ", resource=" - + resourceDescription); + logger.trace("Added existing " + type.getSimpleName() + " initializer bean '" + beanName + "'; order=" + + order + ", resource=" + resourceDescription); } } - private String getResourceDescription(String beanName, - ListableBeanFactory beanFactory) { + private String getResourceDescription(String beanName, ListableBeanFactory beanFactory) { if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; return registry.getBeanDefinition(beanName).getResourceDescription(); @@ -165,48 +150,40 @@ public class ServletContextInitializerBeans @SuppressWarnings("unchecked") protected void addAdaptableBeans(ListableBeanFactory beanFactory) { MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory); - addAsRegistrationBean(beanFactory, Servlet.class, - new ServletRegistrationBeanAdapter(multipartConfig)); - addAsRegistrationBean(beanFactory, Filter.class, - new FilterRegistrationBeanAdapter()); - for (Class listenerType : ServletListenerRegistrationBean - .getSupportedTypes()) { - addAsRegistrationBean(beanFactory, EventListener.class, - (Class) listenerType, + addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig)); + addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter()); + for (Class listenerType : ServletListenerRegistrationBean.getSupportedTypes()) { + addAsRegistrationBean(beanFactory, EventListener.class, (Class) listenerType, new ServletListenerRegistrationBeanAdapter()); } } private MultipartConfigElement getMultipartConfig(ListableBeanFactory beanFactory) { - List> beans = getOrderedBeansOfType( - beanFactory, MultipartConfigElement.class); + List> beans = getOrderedBeansOfType(beanFactory, + MultipartConfigElement.class); return beans.isEmpty() ? null : beans.get(0).getValue(); } - protected void addAsRegistrationBean(ListableBeanFactory beanFactory, - Class type, RegistrationBeanAdapter adapter) { + protected void addAsRegistrationBean(ListableBeanFactory beanFactory, Class type, + RegistrationBeanAdapter adapter) { addAsRegistrationBean(beanFactory, type, type, adapter); } - private void addAsRegistrationBean(ListableBeanFactory beanFactory, - Class type, Class beanType, RegistrationBeanAdapter adapter) { - List> entries = getOrderedBeansOfType(beanFactory, beanType, - this.seen); + private void addAsRegistrationBean(ListableBeanFactory beanFactory, Class type, + Class beanType, RegistrationBeanAdapter adapter) { + List> entries = getOrderedBeansOfType(beanFactory, beanType, this.seen); for (Entry entry : entries) { String beanName = entry.getKey(); B bean = entry.getValue(); if (this.seen.add(bean)) { // One that we haven't already seen - RegistrationBean registration = adapter.createRegistrationBean(beanName, - bean, entries.size()); + RegistrationBean registration = adapter.createRegistrationBean(beanName, bean, entries.size()); int order = getOrder(bean); registration.setOrder(order); this.initializers.add(type, registration); if (logger.isTraceEnabled()) { - logger.trace( - "Created " + type.getSimpleName() + " initializer for bean '" - + beanName + "'; order=" + order + ", resource=" - + getResourceDescription(beanName, beanFactory)); + logger.trace("Created " + type.getSimpleName() + " initializer for bean '" + beanName + "'; order=" + + order + ", resource=" + getResourceDescription(beanName, beanFactory)); } } } @@ -221,13 +198,12 @@ public class ServletContextInitializerBeans }.getOrder(value); } - private List> getOrderedBeansOfType( - ListableBeanFactory beanFactory, Class type) { + private List> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class type) { return getOrderedBeansOfType(beanFactory, type, Collections.emptySet()); } - private List> getOrderedBeansOfType( - ListableBeanFactory beanFactory, Class type, Set excludes) { + private List> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class type, + Set excludes) { String[] names = beanFactory.getBeanNamesForType(type, true, false); Map map = new LinkedHashMap<>(); for (String name : names) { @@ -239,30 +215,23 @@ public class ServletContextInitializerBeans } } List> beans = new ArrayList<>(map.entrySet()); - beans.sort((o1, o2) -> AnnotationAwareOrderComparator.INSTANCE - .compare(o1.getValue(), o2.getValue())); + beans.sort((o1, o2) -> AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), o2.getValue())); return beans; } - private void logMappings( - MultiValueMap, ServletContextInitializer> initializers) { + private void logMappings(MultiValueMap, ServletContextInitializer> initializers) { if (logger.isDebugEnabled()) { - logMappings("filters", initializers, Filter.class, - FilterRegistrationBean.class); - logMappings("servlets", initializers, Servlet.class, - ServletRegistrationBean.class); + logMappings("filters", initializers, Filter.class, FilterRegistrationBean.class); + logMappings("servlets", initializers, Servlet.class, ServletRegistrationBean.class); } } - private void logMappings(String name, - MultiValueMap, ServletContextInitializer> initializers, + private void logMappings(String name, MultiValueMap, ServletContextInitializer> initializers, Class type, Class registrationType) { List registrations = new ArrayList<>(); - registrations.addAll( - initializers.getOrDefault(registrationType, Collections.emptyList())); + registrations.addAll(initializers.getOrDefault(registrationType, Collections.emptyList())); registrations.addAll(initializers.getOrDefault(type, Collections.emptyList())); - String info = registrations.stream().map(Object::toString) - .collect(Collectors.joining(", ")); + String info = registrations.stream().map(Object::toString).collect(Collectors.joining(", ")); logger.debug("Mapping " + name + ": " + info); } @@ -285,16 +254,14 @@ public class ServletContextInitializerBeans @FunctionalInterface protected interface RegistrationBeanAdapter { - RegistrationBean createRegistrationBean(String name, T source, - int totalNumberOfSourceBeans); + RegistrationBean createRegistrationBean(String name, T source, int totalNumberOfSourceBeans); } /** * {@link RegistrationBeanAdapter} for {@link Servlet} beans. */ - private static class ServletRegistrationBeanAdapter - implements RegistrationBeanAdapter { + private static class ServletRegistrationBeanAdapter implements RegistrationBeanAdapter { private final MultipartConfigElement multipartConfig; @@ -303,14 +270,12 @@ public class ServletContextInitializerBeans } @Override - public RegistrationBean createRegistrationBean(String name, Servlet source, - int totalNumberOfSourceBeans) { + public RegistrationBean createRegistrationBean(String name, Servlet source, int totalNumberOfSourceBeans) { String url = (totalNumberOfSourceBeans != 1) ? "/" + name + "/" : "/"; if (name.equals(DISPATCHER_SERVLET_NAME)) { url = "/"; // always map the main dispatcherServlet to "/" } - ServletRegistrationBean bean = new ServletRegistrationBean<>(source, - url); + ServletRegistrationBean bean = new ServletRegistrationBean<>(source, url); bean.setName(name); bean.setMultipartConfig(this.multipartConfig); return bean; @@ -321,12 +286,10 @@ public class ServletContextInitializerBeans /** * {@link RegistrationBeanAdapter} for {@link Filter} beans. */ - private static class FilterRegistrationBeanAdapter - implements RegistrationBeanAdapter { + private static class FilterRegistrationBeanAdapter implements RegistrationBeanAdapter { @Override - public RegistrationBean createRegistrationBean(String name, Filter source, - int totalNumberOfSourceBeans) { + public RegistrationBean createRegistrationBean(String name, Filter source, int totalNumberOfSourceBeans) { FilterRegistrationBean bean = new FilterRegistrationBean<>(source); bean.setName(name); return bean; @@ -337,8 +300,7 @@ public class ServletContextInitializerBeans /** * {@link RegistrationBeanAdapter} for certain {@link EventListener} beans. */ - private static class ServletListenerRegistrationBeanAdapter - implements RegistrationBeanAdapter { + private static class ServletListenerRegistrationBeanAdapter implements RegistrationBeanAdapter { @Override public RegistrationBean createRegistrationBean(String name, EventListener source, diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java index 747a0bec0ae..ebee46669d6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @since 1.4.0 */ -public class ServletListenerRegistrationBean - extends RegistrationBean { +public class ServletListenerRegistrationBean extends RegistrationBean { private static final Set> SUPPORTED_TYPES; @@ -117,9 +116,7 @@ public class ServletListenerRegistrationBean servletContext.addListener(this.listener); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Failed to add listener '" + this.listener + "' to servlet context", - ex); + throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java index ec11bf92e2b..1a7533c45b9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ import org.springframework.util.StringUtils; * @see ServletContextInitializer * @see ServletContext#addServlet(String, Servlet) */ -public class ServletRegistrationBean - extends DynamicRegistrationBean { +public class ServletRegistrationBean extends DynamicRegistrationBean { private static final String[] DEFAULT_MAPPINGS = { "/*" }; @@ -86,8 +85,7 @@ public class ServletRegistrationBean * @param alwaysMapUrl if omitted URL mappings should be replaced with '/*' * @param urlMappings the URLs being mapped */ - public ServletRegistrationBean(T servlet, boolean alwaysMapUrl, - String... urlMappings) { + public ServletRegistrationBean(T servlet, boolean alwaysMapUrl, String... urlMappings) { Assert.notNull(servlet, "Servlet must not be null"); Assert.notNull(urlMappings, "UrlMappings must not be null"); this.servlet = servlet; @@ -175,8 +173,7 @@ public class ServletRegistrationBean } @Override - protected ServletRegistration.Dynamic addRegistration(String description, - ServletContext servletContext) { + protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); return servletContext.addServlet(name, this.servlet); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java index 1cc4ea443b6..898da4ed981 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,11 +41,9 @@ class WebFilterHandler extends ServletComponentHandler { } @Override - public void doHandle(Map attributes, - ScannedGenericBeanDefinition beanDefinition, + public void doHandle(Map attributes, ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(FilterRegistrationBean.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FilterRegistrationBean.class); builder.addPropertyValue("asyncSupported", attributes.get("asyncSupported")); builder.addPropertyValue("dispatcherTypes", extractDispatcherTypes(attributes)); builder.addPropertyValue("filter", beanDefinition); @@ -57,24 +55,20 @@ class WebFilterHandler extends ServletComponentHandler { registry.registerBeanDefinition(name, builder.getBeanDefinition()); } - private EnumSet extractDispatcherTypes( - Map attributes) { - DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes - .get("dispatcherTypes"); + private EnumSet extractDispatcherTypes(Map attributes) { + DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes.get("dispatcherTypes"); if (dispatcherTypes.length == 0) { return EnumSet.noneOf(DispatcherType.class); } if (dispatcherTypes.length == 1) { return EnumSet.of(dispatcherTypes[0]); } - return EnumSet.of(dispatcherTypes[0], - Arrays.copyOfRange(dispatcherTypes, 1, dispatcherTypes.length)); + return EnumSet.of(dispatcherTypes[0], Arrays.copyOfRange(dispatcherTypes, 1, dispatcherTypes.length)); } - private String determineName(Map attributes, - BeanDefinition beanDefinition) { - return (String) (StringUtils.hasText((String) attributes.get("filterName")) - ? attributes.get("filterName") : beanDefinition.getBeanClassName()); + private String determineName(Map attributes, BeanDefinition beanDefinition) { + return (String) (StringUtils.hasText((String) attributes.get("filterName")) ? attributes.get("filterName") + : beanDefinition.getBeanClassName()); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java index da799ec6c8b..96451eb9be7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,14 +36,11 @@ class WebListenerHandler extends ServletComponentHandler { } @Override - protected void doHandle(Map attributes, - ScannedGenericBeanDefinition beanDefinition, + protected void doHandle(Map attributes, ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(ServletListenerRegistrationBean.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ServletListenerRegistrationBean.class); builder.addPropertyValue("listener", beanDefinition); - registry.registerBeanDefinition(beanDefinition.getBeanClassName(), - builder.getBeanDefinition()); + registry.registerBeanDefinition(beanDefinition.getBeanClassName(), builder.getBeanDefinition()); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java index 5ba8e27a8f5..71cc4bc5e16 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,11 +40,9 @@ class WebServletHandler extends ServletComponentHandler { } @Override - public void doHandle(Map attributes, - ScannedGenericBeanDefinition beanDefinition, + public void doHandle(Map attributes, ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(ServletRegistrationBean.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ServletRegistrationBean.class); builder.addPropertyValue("asyncSupported", attributes.get("asyncSupported")); builder.addPropertyValue("initParameters", extractInitParameters(attributes)); builder.addPropertyValue("loadOnStartup", attributes.get("loadOnStartup")); @@ -52,28 +50,23 @@ class WebServletHandler extends ServletComponentHandler { builder.addPropertyValue("name", name); builder.addPropertyValue("servlet", beanDefinition); builder.addPropertyValue("urlMappings", extractUrlPatterns(attributes)); - builder.addPropertyValue("multipartConfig", - determineMultipartConfig(beanDefinition)); + builder.addPropertyValue("multipartConfig", determineMultipartConfig(beanDefinition)); registry.registerBeanDefinition(name, builder.getBeanDefinition()); } - private String determineName(Map attributes, - BeanDefinition beanDefinition) { - return (String) (StringUtils.hasText((String) attributes.get("name")) - ? attributes.get("name") : beanDefinition.getBeanClassName()); + private String determineName(Map attributes, BeanDefinition beanDefinition) { + return (String) (StringUtils.hasText((String) attributes.get("name")) ? attributes.get("name") + : beanDefinition.getBeanClassName()); } - private MultipartConfigElement determineMultipartConfig( - ScannedGenericBeanDefinition beanDefinition) { + private MultipartConfigElement determineMultipartConfig(ScannedGenericBeanDefinition beanDefinition) { Map attributes = beanDefinition.getMetadata() .getAnnotationAttributes(MultipartConfig.class.getName()); if (attributes == null) { return null; } - return new MultipartConfigElement((String) attributes.get("location"), - (Long) attributes.get("maxFileSize"), - (Long) attributes.get("maxRequestSize"), - (Integer) attributes.get("fileSizeThreshold")); + return new MultipartConfigElement((String) attributes.get("location"), (Long) attributes.get("maxFileSize"), + (Long) attributes.get("maxRequestSize"), (Integer) attributes.get("fileSizeThreshold")); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebApplicationContext.java index 90f632879ba..f1a05e3f9e8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebApplicationContext.java @@ -56,8 +56,8 @@ import org.springframework.web.context.support.GenericWebApplicationContext; * @see #register(Class...) * @see #scan(String...) */ -public class AnnotationConfigServletWebApplicationContext - extends GenericWebApplicationContext implements AnnotationConfigRegistry { +public class AnnotationConfigServletWebApplicationContext extends GenericWebApplicationContext + implements AnnotationConfigRegistry { private final AnnotatedBeanDefinitionReader reader; @@ -83,8 +83,7 @@ public class AnnotationConfigServletWebApplicationContext * {@link #register} calls and then manually {@linkplain #refresh refreshed}. * @param beanFactory the DefaultListableBeanFactory instance to use for this context */ - public AnnotationConfigServletWebApplicationContext( - DefaultListableBeanFactory beanFactory) { + public AnnotationConfigServletWebApplicationContext(DefaultListableBeanFactory beanFactory) { super(beanFactory); this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); @@ -144,8 +143,7 @@ public class AnnotationConfigServletWebApplicationContext public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.reader.setBeanNameGenerator(beanNameGenerator); this.scanner.setBeanNameGenerator(beanNameGenerator); - this.getBeanFactory().registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, + this.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator); } @@ -177,8 +175,7 @@ public class AnnotationConfigServletWebApplicationContext */ @Override public final void register(Class... annotatedClasses) { - Assert.notEmpty(annotatedClasses, - "At least one annotated class must be specified"); + Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); this.annotatedClasses.addAll(Arrays.asList(annotatedClasses)); } @@ -213,8 +210,8 @@ public class AnnotationConfigServletWebApplicationContext } @Override - public void registerBean(String beanName, Class beanClass, - Supplier supplier, BeanDefinitionCustomizer... customizers) { + public void registerBean(String beanName, Class beanClass, Supplier supplier, + BeanDefinitionCustomizer... customizers) { this.reader.registerBean(beanClass, beanName, supplier, customizers); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContext.java index 7b27cbbb1f3..c3063eb7dcd 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContext.java @@ -52,8 +52,8 @@ import org.springframework.util.ClassUtils; * @see ServletWebServerApplicationContext * @see AnnotationConfigServletWebApplicationContext */ -public class AnnotationConfigServletWebServerApplicationContext - extends ServletWebServerApplicationContext implements AnnotationConfigRegistry { +public class AnnotationConfigServletWebServerApplicationContext extends ServletWebServerApplicationContext + implements AnnotationConfigRegistry { private final AnnotatedBeanDefinitionReader reader; @@ -79,8 +79,7 @@ public class AnnotationConfigServletWebServerApplicationContext * {@link #register} calls and then manually {@linkplain #refresh refreshed}. * @param beanFactory the DefaultListableBeanFactory instance to use for this context */ - public AnnotationConfigServletWebServerApplicationContext( - DefaultListableBeanFactory beanFactory) { + public AnnotationConfigServletWebServerApplicationContext(DefaultListableBeanFactory beanFactory) { super(beanFactory); this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); @@ -93,8 +92,7 @@ public class AnnotationConfigServletWebServerApplicationContext * @param annotatedClasses one or more annotated classes, e.g. {@code @Configuration} * classes */ - public AnnotationConfigServletWebServerApplicationContext( - Class... annotatedClasses) { + public AnnotationConfigServletWebServerApplicationContext(Class... annotatedClasses) { this(); register(annotatedClasses); refresh(); @@ -142,8 +140,7 @@ public class AnnotationConfigServletWebServerApplicationContext public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.reader.setBeanNameGenerator(beanNameGenerator); this.scanner.setBeanNameGenerator(beanNameGenerator); - this.getBeanFactory().registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, + this.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator); } @@ -175,8 +172,7 @@ public class AnnotationConfigServletWebServerApplicationContext */ @Override public final void register(Class... annotatedClasses) { - Assert.notEmpty(annotatedClasses, - "At least one annotated class must be specified"); + Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); this.annotatedClasses.addAll(Arrays.asList(annotatedClasses)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java index 517ef80dcc5..a1e11ea68ae 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,8 +92,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils; public class ServletWebServerApplicationContext extends GenericWebApplicationContext implements ConfigurableWebServerApplicationContext { - private static final Log logger = LogFactory - .getLog(ServletWebServerApplicationContext.class); + private static final Log logger = LogFactory.getLog(ServletWebServerApplicationContext.class); /** * Constant value for the DispatcherServlet bean name. A Servlet bean with this name @@ -130,8 +129,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon */ @Override protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - beanFactory.addBeanPostProcessor( - new WebApplicationContextServletContextAwareProcessor(this)); + beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); registerWebApplicationScopes(); } @@ -185,8 +183,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon getSelfInitializer().onStartup(servletContext); } catch (ServletException ex) { - throw new ApplicationContextException("Cannot initialize servlet context", - ex); + throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); @@ -200,18 +197,14 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon */ protected ServletWebServerFactory getWebServerFactory() { // Use bean names so that we don't consider the hierarchy - String[] beanNames = getBeanFactory() - .getBeanNamesForType(ServletWebServerFactory.class); + String[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class); if (beanNames.length == 0) { - throw new ApplicationContextException( - "Unable to start ServletWebServerApplicationContext due to missing " - + "ServletWebServerFactory bean."); + throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing " + + "ServletWebServerFactory bean."); } if (beanNames.length > 1) { - throw new ApplicationContextException( - "Unable to start ServletWebServerApplicationContext due to multiple " - + "ServletWebServerFactory beans : " - + StringUtils.arrayToCommaDelimitedString(beanNames)); + throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple " + + "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class); } @@ -229,8 +222,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon private void selfInitialize(ServletContext servletContext) throws ServletException { prepareWebApplicationContext(servletContext); registerApplicationScope(servletContext); - WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), - servletContext); + WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext); for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } @@ -244,8 +236,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon } private void registerWebApplicationScopes() { - ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes( - getBeanFactory()); + ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes(getBeanFactory()); WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory()); existingScopes.restore(); } @@ -269,8 +260,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon * @param servletContext the operational servlet context */ protected void prepareWebApplicationContext(ServletContext servletContext) { - Object rootContext = servletContext.getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); + Object rootContext = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (rootContext != null) { if (rootContext == this) { throw new IllegalStateException( @@ -282,25 +272,20 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring embedded WebApplicationContext"); try { - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this); if (logger.isDebugEnabled()) { - logger.debug( - "Published root WebApplicationContext as ServletContext attribute with name [" - + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE - + "]"); + logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } setServletContext(servletContext); if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - getStartupDate(); - logger.info("Root WebApplicationContext: initialization completed in " - + elapsedTime + " ms"); + logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } } catch (RuntimeException | Error ex) { logger.error("Context initialization failed", ex); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebApplicationContextServletContextAwareProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebApplicationContextServletContextAwareProcessor.java index 3da754d2bbc..3d16b771a52 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebApplicationContextServletContextAwareProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebApplicationContextServletContextAwareProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,13 +31,11 @@ import org.springframework.web.context.support.ServletContextAwareProcessor; * * @author Phillip Webb */ -public class WebApplicationContextServletContextAwareProcessor - extends ServletContextAwareProcessor { +public class WebApplicationContextServletContextAwareProcessor extends ServletContextAwareProcessor { private final ConfigurableWebApplicationContext webApplicationContext; - public WebApplicationContextServletContextAwareProcessor( - ConfigurableWebApplicationContext webApplicationContext) { + public WebApplicationContextServletContextAwareProcessor(ConfigurableWebApplicationContext webApplicationContext) { Assert.notNull(webApplicationContext, "WebApplicationContext must not be null"); this.webApplicationContext = webApplicationContext; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContext.java index fdf3dfcae67..a945fc44f59 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ import org.springframework.web.context.support.XmlWebApplicationContext; * @see ServletWebServerApplicationContext * @see XmlWebApplicationContext */ -public class XmlServletWebServerApplicationContext - extends ServletWebServerApplicationContext { +public class XmlServletWebServerApplicationContext extends ServletWebServerApplicationContext { private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this); @@ -79,8 +78,7 @@ public class XmlServletWebServerApplicationContext * specified resource name * @param resourceNames relatively-qualified names of resources to load */ - public XmlServletWebServerApplicationContext(Class relativeClass, - String... resourceNames) { + public XmlServletWebServerApplicationContext(Class relativeClass, String... resourceNames) { load(relativeClass, resourceNames); refresh(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributes.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributes.java index c24e4f2e3bb..73917e896ff 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributes.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,11 +60,9 @@ import org.springframework.web.servlet.ModelAndView; * @see ErrorAttributes */ @Order(Ordered.HIGHEST_PRECEDENCE) -public class DefaultErrorAttributes - implements ErrorAttributes, HandlerExceptionResolver, Ordered { +public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered { - private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() - + ".ERROR"; + private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() + ".ERROR"; private final boolean includeException; @@ -90,8 +88,8 @@ public class DefaultErrorAttributes } @Override - public ModelAndView resolveException(HttpServletRequest request, - HttpServletResponse response, Object handler, Exception ex) { + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) { storeErrorAttributes(request, ex); return null; } @@ -101,8 +99,7 @@ public class DefaultErrorAttributes } @Override - public Map getErrorAttributes(WebRequest webRequest, - boolean includeStackTrace) { + public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map errorAttributes = new LinkedHashMap<>(); errorAttributes.put("timestamp", new Date()); addStatus(errorAttributes, webRequest); @@ -111,10 +108,8 @@ public class DefaultErrorAttributes return errorAttributes; } - private void addStatus(Map errorAttributes, - RequestAttributes requestAttributes) { - Integer status = getAttribute(requestAttributes, - "javax.servlet.error.status_code"); + private void addStatus(Map errorAttributes, RequestAttributes requestAttributes) { + Integer status = getAttribute(requestAttributes, "javax.servlet.error.status_code"); if (status == null) { errorAttributes.put("status", 999); errorAttributes.put("error", "None"); @@ -130,8 +125,8 @@ public class DefaultErrorAttributes } } - private void addErrorDetails(Map errorAttributes, - WebRequest webRequest, boolean includeStackTrace) { + private void addErrorDetails(Map errorAttributes, WebRequest webRequest, + boolean includeStackTrace) { Throwable error = getError(webRequest); if (error != null) { while (error instanceof ServletException && error.getCause() != null) { @@ -148,8 +143,7 @@ public class DefaultErrorAttributes Object message = getAttribute(webRequest, "javax.servlet.error.message"); if ((!StringUtils.isEmpty(message) || errorAttributes.get("message") == null) && !(error instanceof BindingResult)) { - errorAttributes.put("message", - StringUtils.isEmpty(message) ? "No message available" : message); + errorAttributes.put("message", StringUtils.isEmpty(message) ? "No message available" : message); } } @@ -161,9 +155,8 @@ public class DefaultErrorAttributes } if (result.hasErrors()) { errorAttributes.put("errors", result.getAllErrors()); - errorAttributes.put("message", - "Validation failed for object='" + result.getObjectName() - + "'. Error count: " + result.getErrorCount()); + errorAttributes.put("message", "Validation failed for object='" + result.getObjectName() + + "'. Error count: " + result.getErrorCount()); } else { errorAttributes.put("message", "No errors"); @@ -187,8 +180,7 @@ public class DefaultErrorAttributes errorAttributes.put("trace", stackTrace.toString()); } - private void addPath(Map errorAttributes, - RequestAttributes requestAttributes) { + private void addPath(Map errorAttributes, RequestAttributes requestAttributes) { String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri"); if (path != null) { errorAttributes.put("path", path); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/ErrorAttributes.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/ErrorAttributes.java index d40ade8ffa2..0bc732f9655 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/ErrorAttributes.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/error/ErrorAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ public interface ErrorAttributes { * @param includeStackTrace if stack trace elements should be included * @return a map of error attributes */ - Map getErrorAttributes(WebRequest webRequest, - boolean includeStackTrace); + Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace); /** * Return the underlying cause of the error or {@code null} if the error cannot be diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/ApplicationContextHeaderFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/ApplicationContextHeaderFilter.java index dc922bc10cd..21f184a2a29 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/ApplicationContextHeaderFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/ApplicationContextHeaderFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class ApplicationContextHeaderFilter extends OncePerRequestFilter { } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.addHeader(HEADER_NAME, this.applicationContext.getId()); filterChain.doFilter(request, response); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedCharacterEncodingFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedCharacterEncodingFilter.java index ff4782c9a41..df04a533dd7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedCharacterEncodingFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedCharacterEncodingFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.web.filter.CharacterEncodingFilter; * @author Phillip Webb * @since 2.0.0 */ -public class OrderedCharacterEncodingFilter extends CharacterEncodingFilter - implements OrderedFilter { +public class OrderedCharacterEncodingFilter extends CharacterEncodingFilter implements OrderedFilter { private int order = Ordered.HIGHEST_PRECEDENCE; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHiddenHttpMethodFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHiddenHttpMethodFilter.java index 83d72baa671..0885d2f77da 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHiddenHttpMethodFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHiddenHttpMethodFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.web.filter.HiddenHttpMethodFilter; * @author Phillip Webb * @since 2.0.0 */ -public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter - implements OrderedFilter { +public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter implements OrderedFilter { /** * The default order is high to ensure the filter is applied before Spring Security. diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedRequestContextFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedRequestContextFilter.java index c5f6388f09a..9f7df0ccbe9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedRequestContextFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedRequestContextFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.web.filter.RequestContextFilter; * @author Phillip Webb * @since 2.0.0 */ -public class OrderedRequestContextFilter extends RequestContextFilter - implements OrderedFilter { +public class OrderedRequestContextFilter extends RequestContextFilter implements OrderedFilter { // Order defaults to after Spring Session filter private int order = REQUEST_WRAPPER_FILTER_MAX_ORDER - 105; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactory.java index 8e6117367db..9cddc7198fc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ import org.springframework.util.ClassUtils; * @author Brian Clozel * @since 2.0.0 */ -public abstract class AbstractServletWebServerFactory - extends AbstractConfigurableWebServerFactory +public abstract class AbstractServletWebServerFactory extends AbstractConfigurableWebServerFactory implements ConfigurableServletWebServerFactory { protected final Log logger = LogFactory.getLog(getClass()); @@ -128,12 +127,10 @@ public abstract class AbstractServletWebServerFactory Assert.notNull(contextPath, "ContextPath must not be null"); if (!contextPath.isEmpty()) { if ("/".equals(contextPath)) { - throw new IllegalArgumentException( - "Root ContextPath must be specified using an empty string"); + throw new IllegalArgumentException("Root ContextPath must be specified using an empty string"); } if (!contextPath.startsWith("/") || contextPath.endsWith("/")) { - throw new IllegalArgumentException( - "ContextPath must start with '/' and not end with '/'"); + throw new IllegalArgumentException("ContextPath must start with '/' and not end with '/'"); } } } @@ -247,11 +244,9 @@ public abstract class AbstractServletWebServerFactory * @return a complete set of merged initializers (with the specified parameters * appearing first) */ - protected final ServletContextInitializer[] mergeInitializers( - ServletContextInitializer... initializers) { + protected final ServletContextInitializer[] mergeInitializers(ServletContextInitializer... initializers) { List mergedInitializers = new ArrayList<>(); - mergedInitializers.add((servletContext) -> this.initParameters - .forEach(servletContext::setInitParameter)); + mergedInitializers.add((servletContext) -> this.initParameters.forEach(servletContext::setInitParameter)); mergedInitializers.add(new SessionConfiguringInitializer(this.session)); mergedInitializers.addAll(Arrays.asList(initializers)); mergedInitializers.addAll(this.initializers); @@ -263,8 +258,8 @@ public abstract class AbstractServletWebServerFactory * @return {@code true} if the servlet should be registered, otherwise {@code false} */ protected boolean shouldRegisterJspServlet() { - return this.jsp != null && this.jsp.getRegistered() && ClassUtils - .isPresent(this.jsp.getClassName(), getClass().getClassLoader()); + return this.jsp != null && this.jsp.getRegistered() + && ClassUtils.isPresent(this.jsp.getClassName(), getClass().getClassLoader()); } /** @@ -292,8 +287,7 @@ public abstract class AbstractServletWebServerFactory * {@link ServletContextInitializer} to apply appropriate parts of the {@link Session} * configuration. */ - private static class SessionConfiguringInitializer - implements ServletContextInitializer { + private static class SessionConfiguringInitializer implements ServletContextInitializer { private final Session session; @@ -304,8 +298,7 @@ public abstract class AbstractServletWebServerFactory @Override public void onStartup(ServletContext servletContext) throws ServletException { if (this.session.getTrackingModes() != null) { - servletContext - .setSessionTrackingModes(unwrap(this.session.getTrackingModes())); + servletContext.setSessionTrackingModes(unwrap(this.session.getTrackingModes())); } configureSessionCookie(servletContext.getSessionCookieConfig()); } @@ -335,8 +328,7 @@ public abstract class AbstractServletWebServerFactory } } - private Set unwrap( - Set modes) { + private Set unwrap(Set modes) { if (modes == null) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/ConfigurableServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/ConfigurableServletWebServerFactory.java index b1f2d92785b..c60503c2986 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/ConfigurableServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/ConfigurableServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ import org.springframework.boot.web.servlet.ServletContextInitializer; * @see ServletWebServerFactory * @see WebServerFactoryCustomizer */ -public interface ConfigurableServletWebServerFactory - extends ConfigurableWebServerFactory, ServletWebServerFactory { +public interface ConfigurableServletWebServerFactory extends ConfigurableWebServerFactory, ServletWebServerFactory { /** * Sets the context path for the web server. The context should start with a "/" diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/DocumentRoot.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/DocumentRoot.java index 5b0d5fe136f..e5b266f6806 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/DocumentRoot.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/DocumentRoot.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import org.apache.commons.logging.Log; */ class DocumentRoot { - private static final String[] COMMON_DOC_ROOTS = { "src/main/webapp", "public", - "static" }; + private static final String[] COMMON_DOC_ROOTS = { "src/main/webapp", "public", "static" }; private final Log logger; @@ -127,8 +126,7 @@ class DocumentRoot { } if (codeSourceFile != null && codeSourceFile.exists()) { String path = codeSourceFile.getAbsolutePath(); - int webInfPathIndex = path - .indexOf(File.separatorChar + "WEB-INF" + File.separatorChar); + int webInfPathIndex = path.indexOf(File.separatorChar + "WEB-INF" + File.separatorChar); if (webInfPathIndex >= 0) { path = path.substring(0, webInfPathIndex); return new File(path); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/SessionStoreDirectory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/SessionStoreDirectory.java index be922500cff..4057dd12064 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/SessionStoreDirectory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/SessionStoreDirectory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ class SessionStoreDirectory { } private void assertDirectory(boolean mkdirs, File dir) { - Assert.state(!mkdirs || dir.exists(), - () -> "Session dir " + dir + " does not exist"); + Assert.state(!mkdirs || dir.exists(), () -> "Session dir " + dir + " does not exist"); Assert.state(!dir.isFile(), () -> "Session dir " + dir + " points to a file"); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java index 766627a66fa..0bd18af36e3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,9 +45,7 @@ class StaticResourceJars { return getUrlsFrom(((URLClassLoader) classLoader).getURLs()); } else { - return getUrlsFrom(Stream - .of(ManagementFactory.getRuntimeMXBean().getClassPath() - .split(File.pathSeparator)) + return getUrlsFrom(Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) .map(this::toUrl).toArray(URL[]::new)); } } @@ -65,8 +63,7 @@ class StaticResourceJars { return new File(classPathEntry).toURI().toURL(); } catch (MalformedURLException ex) { - throw new IllegalArgumentException( - "URL could not be created from '" + classPathEntry + "'", ex); + throw new IllegalArgumentException("URL could not be created from '" + classPathEntry + "'", ex); } } @@ -75,8 +72,7 @@ class StaticResourceJars { return new File(url.toURI()); } catch (URISyntaxException ex) { - throw new IllegalStateException( - "Failed to create File from URL '" + url + "'"); + throw new IllegalStateException("Failed to create File from URL '" + url + "'"); } catch (IllegalArgumentException ex) { return null; @@ -104,15 +100,13 @@ class StaticResourceJars { } private void addUrlFile(List urls, URL url, File file) { - if ((file.isDirectory() && new File(file, "META-INF/resources").isDirectory()) - || isResourcesJar(file)) { + if ((file.isDirectory() && new File(file, "META-INF/resources").isDirectory()) || isResourcesJar(file)) { urls.add(url); } } private void addUrlConnection(List urls, URL url, URLConnection connection) { - if (connection instanceof JarURLConnection - && isResourcesJar((JarURLConnection) connection)) { + if (connection instanceof JarURLConnection && isResourcesJar((JarURLConnection) connection)) { urls.add(url); } } @@ -137,8 +131,7 @@ class StaticResourceJars { private boolean isResourcesJar(JarFile jar) throws IOException { try { - return jar.getName().endsWith(".jar") - && (jar.getJarEntry("META-INF/resources") != null); + return jar.getName().endsWith(".jar") && (jar.getJarEntry("META-INF/resources") != null); } finally { jar.close(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java index 38014cfc38e..c71601cf248 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { private static final Set> CLIENT_ABORT_EXCEPTIONS; static { Set> clientAbortExceptions = new HashSet<>(); - addClassIfPresent(clientAbortExceptions, - "org.apache.catalina.connector.ClientAbortException"); + addClassIfPresent(clientAbortExceptions, "org.apache.catalina.connector.ClientAbortException"); CLIENT_ABORT_EXCEPTIONS = Collections.unmodifiableSet(clientAbortExceptions); } @@ -99,8 +98,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { private final OncePerRequestFilter delegate = new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { ErrorPageFilter.this.doFilter(request, response, chain); } @@ -118,19 +116,18 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { this.delegate.doFilter(request, response, chain); } - private void doFilter(HttpServletRequest request, HttpServletResponse response, - FilterChain chain) throws IOException, ServletException { + private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { ErrorWrapperResponse wrapped = new ErrorWrapperResponse(response); try { chain.doFilter(request, wrapped); if (wrapped.hasErrorToSend()) { - handleErrorStatus(request, response, wrapped.getStatus(), - wrapped.getMessage()); + handleErrorStatus(request, response, wrapped.getStatus(), wrapped.getMessage()); response.flushBuffer(); } else if (!request.isAsyncStarted() && !response.isCommitted()) { @@ -147,8 +144,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { } } - private void handleErrorStatus(HttpServletRequest request, - HttpServletResponse response, int status, String message) + private void handleErrorStatus(HttpServletRequest request, HttpServletResponse response, int status, String message) throws ServletException, IOException { if (response.isCommitted()) { handleCommittedResponse(request, null); @@ -164,9 +160,8 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { request.getRequestDispatcher(errorPath).forward(request, response); } - private void handleException(HttpServletRequest request, HttpServletResponse response, - ErrorWrapperResponse wrapped, Throwable ex) - throws IOException, ServletException { + private void handleException(HttpServletRequest request, HttpServletResponse response, ErrorWrapperResponse wrapped, + Throwable ex) throws IOException, ServletException { Class type = ex.getClass(); String errorPath = getErrorPath(type); if (errorPath == null) { @@ -180,13 +175,11 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { forwardToErrorPage(errorPath, request, wrapped, ex); } - private void forwardToErrorPage(String path, HttpServletRequest request, - HttpServletResponse response, Throwable ex) + private void forwardToErrorPage(String path, HttpServletRequest request, HttpServletResponse response, Throwable ex) throws ServletException, IOException { if (logger.isErrorEnabled()) { - String message = "Forwarding to error page from request " - + getDescription(request) + " due to exception [" + ex.getMessage() - + "]"; + String message = "Forwarding to error page from request " + getDescription(request) + " due to exception [" + + ex.getMessage() + "]"; logger.error(message, ex); } setErrorAttributes(request, 500, ex.getMessage()); @@ -215,8 +208,8 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { if (isClientAbortException(ex)) { return; } - String message = "Cannot forward to error page for request " - + getDescription(request) + " as the response has already been" + String message = "Cannot forward to error page for request " + getDescription(request) + + " as the response has already been" + " committed. As a result, the response may have the wrong status" + " code. If your application is running on WebSphere Application" + " Server you may be able to resolve this problem by setting" @@ -261,8 +254,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { return this.global; } - private void setErrorAttributes(HttpServletRequest request, int status, - String message) { + private void setErrorAttributes(HttpServletRequest request, int status, String message) { request.setAttribute(ERROR_STATUS_CODE, status); request.setAttribute(ERROR_MESSAGE, message); request.setAttribute(ERROR_REQUEST_URI, request.getRequestURI()); @@ -303,8 +295,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { public void destroy() { } - private static void addClassIfPresent(Collection> collection, - String className) { + private static void addClassIfPresent(Collection> collection, String className) { try { collection.add(ClassUtils.forName(className, null)); } @@ -355,8 +346,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { private void sendErrorIfNecessary() throws IOException { if (this.hasErrorToSend && !isCommitted()) { - ((HttpServletResponse) getResponse()).sendError(this.status, - this.message); + ((HttpServletResponse) getResponse()).sendError(this.status, this.message); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializer.java index 3d6e848a620..e99ec8a3682 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.web.context.WebApplicationContext; * @author Phillip Webb * @since 2.0.0 */ -public class ServletContextApplicationContextInitializer implements - ApplicationContextInitializer, Ordered { +public class ServletContextApplicationContextInitializer + implements ApplicationContextInitializer, Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; @@ -74,8 +74,7 @@ public class ServletContextApplicationContextInitializer implements public void initialize(ConfigurableWebApplicationContext applicationContext) { applicationContext.setServletContext(this.servletContext); if (this.addApplicationContextAttribute) { - this.servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java index 194387215cd..f43301345fe 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java @@ -89,8 +89,7 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit // Logger initialization is deferred in case an ordered // LogServletContextInitializer is being used this.logger = LogFactory.getLog(getClass()); - WebApplicationContext rootAppContext = createRootApplicationContext( - servletContext); + WebApplicationContext rootAppContext = createRootApplicationContext(servletContext); if (rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext) { @Override @@ -100,32 +99,27 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit }); } else { - this.logger.debug("No ContextLoaderListener registered, as " - + "createRootApplicationContext() did not " + this.logger.debug("No ContextLoaderListener registered, as " + "createRootApplicationContext() did not " + "return an application context"); } } - protected WebApplicationContext createRootApplicationContext( - ServletContext servletContext) { + protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) { SpringApplicationBuilder builder = createSpringApplicationBuilder(); builder.main(getClass()); ApplicationContext parent = getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); builder.initializers(new ParentContextApplicationContextInitializer(parent)); } - builder.initializers( - new ServletContextApplicationContextInitializer(servletContext)); + builder.initializers(new ServletContextApplicationContextInitializer(servletContext)); builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class); builder = configure(builder); builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext)); SpringApplication application = builder.build(); if (application.getAllSources().isEmpty() - && MergedAnnotations.from(getClass(), SearchStrategy.EXHAUSTIVE) - .isPresent(Configuration.class)) { + && MergedAnnotations.from(getClass(), SearchStrategy.EXHAUSTIVE).isPresent(Configuration.class)) { application.addPrimarySources(Collections.singleton(getClass())); } Assert.state(!application.getAllSources().isEmpty(), @@ -133,8 +127,7 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit + "configure method or add an @Configuration annotation"); // Ensure error pages are registered if (this.registerErrorPageFilter) { - application.addPrimarySources( - Collections.singleton(ErrorPageFilterConfiguration.class)); + application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class)); } return run(application); } @@ -159,10 +152,8 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit return (WebApplicationContext) application.run(); } - private ApplicationContext getExistingRootWebApplicationContext( - ServletContext servletContext) { - Object context = servletContext.getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); + private ApplicationContext getExistingRootWebApplicationContext(ServletContext servletContext) { + Object context = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (context instanceof ApplicationContext) { return (ApplicationContext) context; } @@ -195,8 +186,7 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); if (environment instanceof ConfigurableWebEnvironment) { - ((ConfigurableWebEnvironment) environment) - .initPropertySources(this.servletContext, null); + ((ConfigurableWebEnvironment) environment).initPropertySources(this.servletContext, null); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java index 86ef8433b92..e9a4f134b6b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,10 +73,9 @@ public class MustacheView extends AbstractTemplateView { } @Override - protected void renderMergedTemplateModel(Map model, - HttpServletRequest request, HttpServletResponse response) throws Exception { - Template template = createTemplate( - getApplicationContext().getResource(this.getUrl())); + protected void renderMergedTemplateModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { + Template template = createTemplate(getApplicationContext().getResource(this.getUrl())); if (template != null) { template.execute(model, response.getWriter()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilder.java index b5821dc4128..477feaa59eb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,23 +70,19 @@ public class HttpWebServiceMessageSenderBuilder { */ public HttpWebServiceMessageSenderBuilder requestFactory( Supplier requestFactorySupplier) { - Assert.notNull(requestFactorySupplier, - "RequestFactory Supplier must not be null"); + Assert.notNull(requestFactorySupplier, "RequestFactory Supplier must not be null"); this.requestFactorySupplier = requestFactorySupplier; return this; } public WebServiceMessageSender build() { ClientHttpRequestFactory requestFactory = (this.requestFactorySupplier != null) - ? this.requestFactorySupplier.get() - : new ClientHttpRequestFactorySupplier().get(); + ? this.requestFactorySupplier.get() : new ClientHttpRequestFactorySupplier().get(); if (this.connectTimeout != null) { - new TimeoutRequestFactoryCustomizer(this.connectTimeout, "setConnectTimeout") - .customize(requestFactory); + new TimeoutRequestFactoryCustomizer(this.connectTimeout, "setConnectTimeout").customize(requestFactory); } if (this.readTimeout != null) { - new TimeoutRequestFactoryCustomizer(this.readTimeout, "setReadTimeout") - .customize(requestFactory); + new TimeoutRequestFactoryCustomizer(this.readTimeout, "setReadTimeout").customize(requestFactory); } return new ClientHttpRequestMessageSender(requestFactory); } @@ -106,18 +102,16 @@ public class HttpWebServiceMessageSenderBuilder { } public void customize(ClientHttpRequestFactory factory) { - ReflectionUtils.invokeMethod(findMethod(factory), factory, - Math.toIntExact(this.timeout.toMillis())); + ReflectionUtils.invokeMethod(findMethod(factory), factory, Math.toIntExact(this.timeout.toMillis())); } private Method findMethod(ClientHttpRequestFactory factory) { - Method method = ReflectionUtils.findMethod(factory.getClass(), - this.methodName, int.class); + Method method = ReflectionUtils.findMethod(factory.getClass(), this.methodName, int.class); if (method != null) { return method; } - throw new IllegalStateException("Request factory " + factory.getClass() - + " does not have a " + this.methodName + "(int) method"); + throw new IllegalStateException( + "Request factory " + factory.getClass() + " does not have a " + this.methodName + "(int) method"); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java index 4c6f7cb4263..7e9539b76a4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,8 +80,7 @@ public class WebServiceTemplateBuilder { this.detectHttpMessageSender = true; this.interceptors = null; this.internalCustomizers = null; - this.customizers = Collections - .unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); + this.customizers = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); this.messageSenders = new WebServiceMessageSenders(); this.marshaller = null; this.unmarshaller = null; @@ -90,13 +89,10 @@ public class WebServiceTemplateBuilder { this.messageFactory = null; } - private WebServiceTemplateBuilder(boolean detectHttpMessageSender, - Set interceptors, - Set internalCustomizers, - Set customizers, - WebServiceMessageSenders messageSenders, Marshaller marshaller, - Unmarshaller unmarshaller, DestinationProvider destinationProvider, - Class transformerFactoryClass, + private WebServiceTemplateBuilder(boolean detectHttpMessageSender, Set interceptors, + Set internalCustomizers, Set customizers, + WebServiceMessageSenders messageSenders, Marshaller marshaller, Unmarshaller unmarshaller, + DestinationProvider destinationProvider, Class transformerFactoryClass, WebServiceMessageFactory messageFactory) { this.detectHttpMessageSender = detectHttpMessageSender; this.interceptors = interceptors; @@ -118,11 +114,9 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see HttpWebServiceMessageSenderBuilder */ - public WebServiceTemplateBuilder detectHttpMessageSender( - boolean detectHttpMessageSender) { - return new WebServiceTemplateBuilder(detectHttpMessageSender, this.interceptors, - this.internalCustomizers, this.customizers, this.messageSenders, - this.marshaller, this.unmarshaller, this.destinationProvider, + public WebServiceTemplateBuilder detectHttpMessageSender(boolean detectHttpMessageSender) { + return new WebServiceTemplateBuilder(detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } @@ -137,8 +131,7 @@ public class WebServiceTemplateBuilder { * @see #additionalMessageSenders(WebServiceMessageSender...) * @see #detectHttpMessageSender(boolean) */ - public WebServiceTemplateBuilder messageSenders( - WebServiceMessageSender... messageSenders) { + public WebServiceTemplateBuilder messageSenders(WebServiceMessageSender... messageSenders) { Assert.notNull(messageSenders, "MessageSenders must not be null"); return messageSenders(Arrays.asList(messageSenders)); } @@ -154,14 +147,11 @@ public class WebServiceTemplateBuilder { * @see #additionalMessageSenders(Collection) * @see #detectHttpMessageSender(boolean) */ - public WebServiceTemplateBuilder messageSenders( - Collection messageSenders) { + public WebServiceTemplateBuilder messageSenders(Collection messageSenders) { Assert.notNull(messageSenders, "MessageSenders must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders.set(messageSenders), this.marshaller, - this.unmarshaller, this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders.set(messageSenders), this.marshaller, this.unmarshaller, + this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } /** @@ -171,8 +161,7 @@ public class WebServiceTemplateBuilder { * @return a new builder instance. * @see #messageSenders(WebServiceMessageSender...) */ - public WebServiceTemplateBuilder additionalMessageSenders( - WebServiceMessageSender... messageSenders) { + public WebServiceTemplateBuilder additionalMessageSenders(WebServiceMessageSender... messageSenders) { Assert.notNull(messageSenders, "MessageSenders must not be null"); return additionalMessageSenders(Arrays.asList(messageSenders)); } @@ -187,11 +176,9 @@ public class WebServiceTemplateBuilder { public WebServiceTemplateBuilder additionalMessageSenders( Collection messageSenders) { Assert.notNull(messageSenders, "MessageSenders must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders.add(messageSenders), this.marshaller, - this.unmarshaller, this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders.add(messageSenders), this.marshaller, this.unmarshaller, + this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } /** @@ -215,13 +202,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see #additionalInterceptors(Collection) */ - public WebServiceTemplateBuilder interceptors( - Collection interceptors) { + public WebServiceTemplateBuilder interceptors(Collection interceptors) { Assert.notNull(interceptors, "Interceptors must not be null"); return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - append(Collections.emptySet(), interceptors), - this.internalCustomizers, this.customizers, this.messageSenders, - this.marshaller, this.unmarshaller, this.destinationProvider, + append(Collections.emptySet(), interceptors), this.internalCustomizers, + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } @@ -232,8 +217,7 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see #interceptors(ClientInterceptor...) */ - public WebServiceTemplateBuilder additionalInterceptors( - ClientInterceptor... interceptors) { + public WebServiceTemplateBuilder additionalInterceptors(ClientInterceptor... interceptors) { Assert.notNull(interceptors, "Interceptors must not be null"); return additionalInterceptors(Arrays.asList(interceptors)); } @@ -245,14 +229,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see #interceptors(Collection) */ - public WebServiceTemplateBuilder additionalInterceptors( - Collection interceptors) { + public WebServiceTemplateBuilder additionalInterceptors(Collection interceptors) { Assert.notNull(interceptors, "Interceptors must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - append(this.interceptors, interceptors), this.internalCustomizers, - this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, append(this.interceptors, interceptors), + this.internalCustomizers, this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, + this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } /** @@ -264,8 +245,7 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see #additionalCustomizers(WebServiceTemplateCustomizer...) */ - public WebServiceTemplateBuilder customizers( - WebServiceTemplateCustomizer... customizers) { + public WebServiceTemplateBuilder customizers(WebServiceTemplateCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); return customizers(Arrays.asList(customizers)); } @@ -279,14 +259,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see #additionalCustomizers(Collection) */ - public WebServiceTemplateBuilder customizers( - Collection customizers) { + public WebServiceTemplateBuilder customizers(Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, - append(Collections.emptySet(), customizers), - this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + append(Collections.emptySet(), customizers), this.messageSenders, + this.marshaller, this.unmarshaller, this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } @@ -298,8 +275,7 @@ public class WebServiceTemplateBuilder { * @return a new builder instance * @see #customizers(WebServiceTemplateCustomizer...) */ - public WebServiceTemplateBuilder additionalCustomizers( - WebServiceTemplateCustomizer... customizers) { + public WebServiceTemplateBuilder additionalCustomizers(WebServiceTemplateCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); return additionalCustomizers(Arrays.asList(customizers)); } @@ -315,11 +291,9 @@ public class WebServiceTemplateBuilder { public WebServiceTemplateBuilder additionalCustomizers( Collection customizers) { Assert.notNull(customizers, "Customizers must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, - append(this.customizers, customizers), this.messageSenders, - this.marshaller, this.unmarshaller, this.destinationProvider, - this.transformerFactoryClass, this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + append(this.customizers, customizers), this.messageSenders, this.marshaller, this.unmarshaller, + this.destinationProvider, this.transformerFactoryClass, this.messageFactory); } /** @@ -329,15 +303,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance. * @see WebServiceTemplate#setCheckConnectionForFault(boolean) */ - public WebServiceTemplateBuilder setCheckConnectionForFault( - boolean checkConnectionForFault) { - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, - append(this.internalCustomizers, - new CheckConnectionFaultCustomizer(checkConnectionForFault)), - this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + public WebServiceTemplateBuilder setCheckConnectionForFault(boolean checkConnectionForFault) { + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, + append(this.internalCustomizers, new CheckConnectionFaultCustomizer(checkConnectionForFault)), + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, + this.transformerFactoryClass, this.messageFactory); } /** @@ -347,15 +317,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance. * @see WebServiceTemplate#setCheckConnectionForError(boolean) */ - public WebServiceTemplateBuilder setCheckConnectionForError( - boolean checkConnectionForError) { - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, - append(this.internalCustomizers, - new CheckConnectionForErrorCustomizer(checkConnectionForError)), - this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + public WebServiceTemplateBuilder setCheckConnectionForError(boolean checkConnectionForError) { + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, + append(this.internalCustomizers, new CheckConnectionForErrorCustomizer(checkConnectionForError)), + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, + this.transformerFactoryClass, this.messageFactory); } /** @@ -364,13 +330,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance. * @see WebServiceTemplate#setMessageFactory(WebServiceMessageFactory) **/ - public WebServiceTemplateBuilder setWebServiceMessageFactory( - WebServiceMessageFactory messageFactory) { + public WebServiceTemplateBuilder setWebServiceMessageFactory(WebServiceMessageFactory messageFactory) { Assert.notNull(messageFactory, "MessageFactory must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, + this.transformerFactoryClass, messageFactory); } /** @@ -380,11 +344,9 @@ public class WebServiceTemplateBuilder { * @see WebServiceTemplate#setUnmarshaller(Unmarshaller) **/ public WebServiceTemplateBuilder setUnmarshaller(Unmarshaller unmarshaller) { - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders, this.marshaller, unmarshaller, - this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders, this.marshaller, unmarshaller, this.destinationProvider, + this.transformerFactoryClass, this.messageFactory); } /** @@ -394,11 +356,9 @@ public class WebServiceTemplateBuilder { * @see WebServiceTemplate#setMarshaller(Marshaller) **/ public WebServiceTemplateBuilder setMarshaller(Marshaller marshaller) { - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders, marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders, marshaller, this.unmarshaller, this.destinationProvider, + this.transformerFactoryClass, this.messageFactory); } /** @@ -407,15 +367,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance. * @see WebServiceTemplate#setFaultMessageResolver(FaultMessageResolver) */ - public WebServiceTemplateBuilder setFaultMessageResolver( - FaultMessageResolver faultMessageResolver) { - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, - append(this.internalCustomizers, - new FaultMessageResolverCustomizer(faultMessageResolver)), - this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, this.transformerFactoryClass, - this.messageFactory); + public WebServiceTemplateBuilder setFaultMessageResolver(FaultMessageResolver faultMessageResolver) { + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, + append(this.internalCustomizers, new FaultMessageResolverCustomizer(faultMessageResolver)), + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, + this.transformerFactoryClass, this.messageFactory); } /** @@ -426,10 +382,9 @@ public class WebServiceTemplateBuilder { */ public WebServiceTemplateBuilder setTransformerFactoryClass( Class transformerFactoryClass) { - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders, this.marshaller, this.unmarshaller, - this.destinationProvider, transformerFactoryClass, this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, + transformerFactoryClass, this.messageFactory); } /** @@ -454,13 +409,11 @@ public class WebServiceTemplateBuilder { * @return a new builder instance. * @see WebServiceTemplate#setDestinationProvider(DestinationProvider) */ - public WebServiceTemplateBuilder setDestinationProvider( - DestinationProvider destinationProvider) { + public WebServiceTemplateBuilder setDestinationProvider(DestinationProvider destinationProvider) { Assert.notNull(destinationProvider, "DestinationProvider must not be null"); - return new WebServiceTemplateBuilder(this.detectHttpMessageSender, - this.interceptors, this.internalCustomizers, this.customizers, - this.messageSenders, this.marshaller, this.unmarshaller, - destinationProvider, this.transformerFactoryClass, this.messageFactory); + return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, + this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, destinationProvider, + this.transformerFactoryClass, this.messageFactory); } /** @@ -484,8 +437,7 @@ public class WebServiceTemplateBuilder { * @see #configure(WebServiceTemplate) */ public T build(Class webServiceTemplateClass) { - Assert.notNull(webServiceTemplateClass, - "WebServiceTemplateClass must not be null"); + Assert.notNull(webServiceTemplateClass, "WebServiceTemplateClass must not be null"); return configure(BeanUtils.instantiateClass(webServiceTemplateClass)); } @@ -505,8 +457,7 @@ public class WebServiceTemplateBuilder { map.from(this.marshaller).to(webServiceTemplate::setMarshaller); map.from(this.unmarshaller).to(webServiceTemplate::setUnmarshaller); map.from(this.destinationProvider).to(webServiceTemplate::setDestinationProvider); - map.from(this.transformerFactoryClass) - .to(webServiceTemplate::setTransformerFactoryClass); + map.from(this.transformerFactoryClass).to(webServiceTemplate::setTransformerFactoryClass); map.from(this.messageFactory).to(webServiceTemplate::setMessageFactory); if (!CollectionUtils.isEmpty(this.interceptors)) { Set merged = new LinkedHashSet<>(this.interceptors); @@ -528,18 +479,15 @@ public class WebServiceTemplateBuilder { } } - private void configureMessageSenders( - T webServiceTemplate) { + private void configureMessageSenders(T webServiceTemplate) { if (this.messageSenders.isOnlyAdditional() && this.detectHttpMessageSender) { - Set merged = append( - this.messageSenders.getMessageSenders(), + Set merged = append(this.messageSenders.getMessageSenders(), new HttpWebServiceMessageSenderBuilder().build()); - webServiceTemplate - .setMessageSenders(merged.toArray(new WebServiceMessageSender[0])); + webServiceTemplate.setMessageSenders(merged.toArray(new WebServiceMessageSender[0])); } else if (!CollectionUtils.isEmpty(this.messageSenders.getMessageSenders())) { - webServiceTemplate.setMessageSenders(this.messageSenders.getMessageSenders() - .toArray(new WebServiceMessageSender[0])); + webServiceTemplate + .setMessageSenders(this.messageSenders.getMessageSenders().toArray(new WebServiceMessageSender[0])); } } @@ -567,8 +515,7 @@ public class WebServiceTemplateBuilder { this(true, Collections.emptySet()); } - private WebServiceMessageSenders(boolean onlyAdditional, - Set messageSenders) { + private WebServiceMessageSenders(boolean onlyAdditional, Set messageSenders) { this.onlyAdditional = onlyAdditional; this.messageSenders = messageSenders; } @@ -581,16 +528,12 @@ public class WebServiceTemplateBuilder { return this.messageSenders; } - public WebServiceMessageSenders set( - Collection messageSenders) { - return new WebServiceMessageSenders(false, - new LinkedHashSet<>(messageSenders)); + public WebServiceMessageSenders set(Collection messageSenders) { + return new WebServiceMessageSenders(false, new LinkedHashSet<>(messageSenders)); } - public WebServiceMessageSenders add( - Collection messageSenders) { - return new WebServiceMessageSenders(this.onlyAdditional, - append(this.messageSenders, messageSenders)); + public WebServiceMessageSenders add(Collection messageSenders) { + return new WebServiceMessageSenders(this.onlyAdditional, append(this.messageSenders, messageSenders)); } } @@ -599,8 +542,7 @@ public class WebServiceTemplateBuilder { * {@link WebServiceTemplateCustomizer} to set * {@link WebServiceTemplate#checkConnectionForFault checkConnectionForFault }. */ - private static final class CheckConnectionFaultCustomizer - implements WebServiceTemplateCustomizer { + private static final class CheckConnectionFaultCustomizer implements WebServiceTemplateCustomizer { private final boolean checkConnectionFault; @@ -619,8 +561,7 @@ public class WebServiceTemplateBuilder { * {@link WebServiceTemplateCustomizer} to set * {@link WebServiceTemplate#checkConnectionForError checkConnectionForError }. */ - private static final class CheckConnectionForErrorCustomizer - implements WebServiceTemplateCustomizer { + private static final class CheckConnectionForErrorCustomizer implements WebServiceTemplateCustomizer { private final boolean checkConnectionForError; @@ -639,13 +580,11 @@ public class WebServiceTemplateBuilder { * {@link WebServiceTemplateCustomizer} to set * {@link WebServiceTemplate#faultMessageResolver faultMessageResolver }. */ - private static final class FaultMessageResolverCustomizer - implements WebServiceTemplateCustomizer { + private static final class FaultMessageResolverCustomizer implements WebServiceTemplateCustomizer { private final FaultMessageResolver faultMessageResolver; - private FaultMessageResolverCustomizer( - FaultMessageResolver faultMessageResolver) { + private FaultMessageResolverCustomizer(FaultMessageResolver faultMessageResolver) { this.faultMessageResolver = faultMessageResolver; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index f8e0e43926d..580292fe436 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java @@ -105,12 +105,11 @@ public class BannerTests { this.context = application.run(); Banner printedBanner = (Banner) this.context.getBean("springBootBanner"); assertThat(printedBanner).hasFieldOrPropertyWithValue("banner", banner); - verify(banner).printBanner(any(Environment.class), - this.sourceClassCaptor.capture(), any(PrintStream.class)); + verify(banner).printBanner(any(Environment.class), this.sourceClassCaptor.capture(), any(PrintStream.class)); reset(banner); printedBanner.printBanner(this.context.getEnvironment(), null, System.out); - verify(banner).printBanner(any(Environment.class), - eq(this.sourceClassCaptor.getValue()), any(PrintStream.class)); + verify(banner).printBanner(any(Environment.class), eq(this.sourceClassCaptor.getValue()), + any(PrintStream.class)); } @Test @@ -130,8 +129,7 @@ public class BannerTests { static class DummyBanner implements Banner { @Override - public void printBanner(Environment environment, Class sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class sourceClass, PrintStream out) { out.println("My Banner"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java index b096dcc8e29..02203e8af3c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,16 +48,14 @@ public class BeanDefinitionLoaderTests { @Test public void loadClass() { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadXmlResource() { - ClassPathResource resource = new ClassPathResource("sample-beans.xml", - getClass()); + ClassPathResource resource = new ClassPathResource("sample-beans.xml", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myXmlComponent")).isTrue(); @@ -66,8 +64,7 @@ public class BeanDefinitionLoaderTests { @Test public void loadGroovyResource() { - ClassPathResource resource = new ClassPathResource("sample-beans.groovy", - getClass()); + ClassPathResource resource = new ClassPathResource("sample-beans.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); @@ -76,8 +73,7 @@ public class BeanDefinitionLoaderTests { @Test public void loadGroovyResourceWithNamespace() { - ClassPathResource resource = new ClassPathResource("sample-namespace.groovy", - getClass()); + ClassPathResource resource = new ClassPathResource("sample-namespace.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); @@ -86,16 +82,14 @@ public class BeanDefinitionLoaderTests { @Test public void loadPackage() { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getPackage()); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadClassName() { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getName()); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getName()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @@ -118,8 +112,7 @@ public class BeanDefinitionLoaderTests { @Test public void loadPackageName() { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getPackage().getName()); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage().getName()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @@ -136,8 +129,8 @@ public class BeanDefinitionLoaderTests { @Test public void loadPackageAndClassDoesNotDoubleAdd() { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getPackage(), MyComponent.class); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage(), + MyComponent.class); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 58459fb726f..2eb536ec217 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -32,13 +32,11 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException */ public class DefaultApplicationArgumentsTests { - private static final String[] ARGS = new String[] { "--foo=bar", "--foo=baz", - "--debug", "spring", "boot" }; + private static final String[] ARGS = new String[] { "--foo=bar", "--foo=baz", "--debug", "spring", "boot" }; @Test public void argumentsMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new DefaultApplicationArguments((String[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new DefaultApplicationArguments((String[]) null)) .withMessageContaining("Args must not be null"); } @@ -66,8 +64,7 @@ public class DefaultApplicationArgumentsTests { @Test public void getOptionValues() { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); - assertThat(arguments.getOptionValues("foo")) - .isEqualTo(Arrays.asList("bar", "baz")); + assertThat(arguments.getOptionValues("foo")).isEqualTo(Arrays.asList("bar", "baz")); assertThat(arguments.getOptionValues("debug")).isEmpty(); assertThat(arguments.getOptionValues("spring")).isNull(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java index 61a5b6da7e1..9d08c2e2c99 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,39 +40,32 @@ import static org.mockito.Mockito.mock; */ public class EnvironmentConverterTests { - private final EnvironmentConverter environmentConverter = new EnvironmentConverter( - getClass().getClassLoader()); + private final EnvironmentConverter environmentConverter = new EnvironmentConverter(getClass().getClassLoader()); @Test public void convertedEnvironmentHasSameActiveProfiles() { AbstractEnvironment originalEnvironment = new MockEnvironment(); originalEnvironment.setActiveProfiles("activeProfile1", "activeProfile2"); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(originalEnvironment, - StandardEnvironment.class); - assertThat(convertedEnvironment.getActiveProfiles()) - .containsExactly("activeProfile1", "activeProfile2"); + .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); + assertThat(convertedEnvironment.getActiveProfiles()).containsExactly("activeProfile1", "activeProfile2"); } @Test public void convertedEnvironmentHasSameConversionService() { AbstractEnvironment originalEnvironment = new MockEnvironment(); - ConfigurableConversionService conversionService = mock( - ConfigurableConversionService.class); + ConfigurableConversionService conversionService = mock(ConfigurableConversionService.class); originalEnvironment.setConversionService(conversionService); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(originalEnvironment, - StandardEnvironment.class); - assertThat(convertedEnvironment.getConversionService()) - .isEqualTo(conversionService); + .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); + assertThat(convertedEnvironment.getConversionService()).isEqualTo(conversionService); } @Test public void envClassSameShouldReturnEnvironmentUnconverted() { StandardEnvironment standardEnvironment = new StandardEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardEnvironment, - StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isSameAs(standardEnvironment); } @@ -80,8 +73,7 @@ public class EnvironmentConverterTests { public void standardServletEnvironmentIsConverted() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, - StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardServletEnvironment); } @@ -89,16 +81,13 @@ public class EnvironmentConverterTests { public void servletPropertySourcesAreNotCopiedOverIfNotWebEnvironment() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, - StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardServletEnvironment); Set names = new HashSet<>(); - for (PropertySource propertySource : convertedEnvironment - .getPropertySources()) { + for (PropertySource propertySource : convertedEnvironment.getPropertySources()) { names.add(propertySource.getName()); } - assertThat(names).doesNotContain( - StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, + assertThat(names).doesNotContain(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME, StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME); } @@ -107,8 +96,7 @@ public class EnvironmentConverterTests { public void envClassSameShouldReturnEnvironmentUnconvertedEvenForWeb() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, - StandardServletEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardServletEnvironment.class); assertThat(convertedEnvironment).isSameAs(standardServletEnvironment); } @@ -116,16 +104,13 @@ public class EnvironmentConverterTests { public void servletPropertySourcesArePresentWhenTypeToConvertIsWeb() { StandardEnvironment standardEnvironment = new StandardEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardEnvironment, - StandardServletEnvironment.class); + .convertEnvironmentIfNecessary(standardEnvironment, StandardServletEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardEnvironment); Set names = new HashSet<>(); - for (PropertySource propertySource : convertedEnvironment - .getPropertySources()) { + for (PropertySource propertySource : convertedEnvironment.getPropertySources()) { names.add(propertySource.getName()); } - assertThat(names).contains( - StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, + assertThat(names).contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index b48d50436a1..8dc1d96b85a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class ExitCodeGeneratorsTests { @Test public void addWhenGeneratorIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ExitCodeGenerators().add(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ExitCodeGenerators().add(null)) .withMessageContaining("Generator must not be null"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java index af7cffbe1ae..7665e556da1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,32 +61,28 @@ public class ImageBannerTests { @Test public void printBannerShouldResetForegroundAndBackground() { String banner = printBanner("black-and-white.gif"); - String expected = AnsiOutput.encode(AnsiColor.DEFAULT) - + AnsiOutput.encode(AnsiBackground.DEFAULT); + String expected = AnsiOutput.encode(AnsiColor.DEFAULT) + AnsiOutput.encode(AnsiBackground.DEFAULT); assertThat(banner).startsWith(expected); } @Test public void printBannerWhenInvertedShouldResetForegroundAndBackground() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); - String expected = AnsiOutput.encode(AnsiColor.DEFAULT) - + AnsiOutput.encode(AnsiBackground.BLACK); + String expected = AnsiOutput.encode(AnsiColor.DEFAULT) + AnsiOutput.encode(AnsiBackground.BLACK); assertThat(banner).startsWith(expected); } @Test public void printBannerShouldPrintWhiteAsBrightWhiteHighLuminance() { String banner = printBanner("black-and-white.gif"); - String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) - + HIGH_LUMINANCE_CHARACTER; + String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) + HIGH_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @Test public void printBannerWhenInvertedShouldPrintWhiteAsBrightWhiteLowLuminance() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); - String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) - + LOW_LUMINANCE_CHARACTER; + String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) + LOW_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @@ -117,8 +113,7 @@ public class ImageBannerTests { @Test public void printBannerShouldRenderGradient() { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); - String banner = printBanner("gradient.gif", "spring.banner.image.width=10", - "spring.banner.image.margin=0"); + String banner = printBanner("gradient.gif", "spring.banner.image.width=10", "spring.banner.image.margin=0"); assertThat(banner).contains("@#8&o:*. "); } @@ -130,8 +125,7 @@ public class ImageBannerTests { @Test public void printBannerWhenHasHeightPropertyShouldSetHeight() { - String banner = printBanner("large.gif", "spring.banner.image.width=20", - "spring.banner.image.height=30"); + String banner = printBanner("large.gif", "spring.banner.image.width=20", "spring.banner.image.height=30"); assertThat(getBannerHeight(banner)).isEqualTo(30); } @@ -189,8 +183,7 @@ public class ImageBannerTests { private String printBanner(String path, String... properties) { ImageBanner banner = new ImageBanner(new ClassPathResource(path, getClass())); ConfigurableEnvironment environment = new MockEnvironment(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - properties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, properties); ByteArrayOutputStream out = new ByteArrayOutputStream(); banner.printBanner(environment, getClass(), new PrintStream(out)); return out.toString(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java index 8ae0f72e083..1161b3b4d48 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java @@ -53,8 +53,7 @@ public class OverrideSourcesTests { @Test public void primaryBeanInjectedProvingSourcesNotOverridden() { - this.context = SpringApplication.run( - new Class[] { MainConfiguration.class, TestConfiguration.class }, + this.context = SpringApplication.run(new Class[] { MainConfiguration.class, TestConfiguration.class }, new String[] { "--spring.main.web-application-type=none", "--spring.main.allow-bean-definition-overriding=true", "--spring.main.sources=org.springframework.boot.OverrideSourcesTests.MainConfiguration" }); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java index 3f9b978a38d..2bd7ff65313 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java @@ -48,13 +48,10 @@ public class ReproTests { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application.run( - "--spring.config.name=enableprofileviaapplicationproperties", + this.context = application.run("--spring.config.name=enableprofileviaapplicationproperties", "--spring.profiles.active=dev"); - assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("dev"))) - .isTrue(); - assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("a"))) - .isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("dev"))).isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("a"))).isTrue(); } @Test @@ -167,12 +164,10 @@ public class ReproTests { assertVersionProperty(this.context, "A", "C", "A"); } - private void assertVersionProperty(ConfigurableApplicationContext context, - String expectedVersion, String... expectedActiveProfiles) { - assertThat(context.getEnvironment().getActiveProfiles()) - .isEqualTo(expectedActiveProfiles); - assertThat(context.getEnvironment().getProperty("version")).as("version mismatch") - .isEqualTo(expectedVersion); + private void assertVersionProperty(ConfigurableApplicationContext context, String expectedVersion, + String... expectedActiveProfiles) { + assertThat(context.getEnvironment().getActiveProfiles()).isEqualTo(expectedActiveProfiles); + assertThat(context.getEnvironment().getProperty("version")).as("version mismatch").isEqualTo(expectedVersion); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java index 581c5da0b5b..b90c2f930d6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,7 @@ public class ResourceBannerTests { @Test public void renderFormattedVersions() { Resource resource = new ByteArrayResource( - "banner ${a}${spring-boot.formatted-version}${application.formatted-version}" - .getBytes()); + "banner ${a}${spring-boot.formatted-version}${application.formatted-version}".getBytes()); String banner = printBanner(resource, "10.2", "2.0", null); assertThat(banner).startsWith("banner 1 (v10.2) (v2.0)"); } @@ -75,16 +74,14 @@ public class ResourceBannerTests { @Test public void renderWithoutFormattedVersions() { Resource resource = new ByteArrayResource( - "banner ${a}${spring-boot.formatted-version}${application.formatted-version}" - .getBytes()); + "banner ${a}${spring-boot.formatted-version}${application.formatted-version}".getBytes()); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("banner 1"); } @Test public void renderWithColors() { - Resource resource = new ByteArrayResource( - "${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); + Resource resource = new ByteArrayResource("${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("\u001B[31mThis is red.\u001B[0m"); @@ -92,8 +89,7 @@ public class ResourceBannerTests { @Test public void renderWithColorsButDisabled() { - Resource resource = new ByteArrayResource( - "${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); + Resource resource = new ByteArrayResource("${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("This is red."); @@ -101,24 +97,21 @@ public class ResourceBannerTests { @Test public void renderWithTitle() { - Resource resource = new ByteArrayResource( - "banner ${application.title} ${a}".getBytes()); + Resource resource = new ByteArrayResource("banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, "title"); assertThat(banner).startsWith("banner title 1"); } @Test public void renderWithoutTitle() { - Resource resource = new ByteArrayResource( - "banner ${application.title} ${a}".getBytes()); + Resource resource = new ByteArrayResource("banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("banner 1"); } - private String printBanner(Resource resource, String bootVersion, - String applicationVersion, String applicationTitle) { - ResourceBanner banner = new MockResourceBanner(resource, bootVersion, - applicationVersion, applicationTitle); + private String printBanner(Resource resource, String bootVersion, String applicationVersion, + String applicationTitle) { + ResourceBanner banner = new MockResourceBanner(resource, bootVersion, applicationVersion, applicationTitle); ConfigurableEnvironment environment = new MockEnvironment(); Map source = Collections.singletonMap("a", "1"); environment.getPropertySources().addLast(new MapPropertySource("map", source)); @@ -135,8 +128,7 @@ public class ResourceBannerTests { private final String applicationTitle; - MockResourceBanner(Resource resource, String bootVersion, - String applicationVersion, String applicationTitle) { + MockResourceBanner(Resource resource, String bootVersion, String applicationVersion, String applicationTitle) { super(resource); this.bootVersion = bootVersion; this.applicationVersion = applicationVersion; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java index 6be37b1a050..07f58c2bcf4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java @@ -46,14 +46,12 @@ public class SimpleMainTests { @Test public void emptyApplicationContext() throws Exception { - assertThatIllegalArgumentException() - .isThrownBy(() -> SpringApplication.main(getArgs())); + assertThatIllegalArgumentException().isThrownBy(() -> SpringApplication.main(getArgs())); } @Test public void basePackageScan() throws Exception { - SpringApplication - .main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); + SpringApplication.main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); assertThat(getOutput()).contains(SPRING_STARTUP); } @@ -71,19 +69,15 @@ public class SimpleMainTests { @Test public void mixedContext() throws Exception { - SpringApplication.main(getArgs(getClass().getName(), - "org/springframework/boot/sample-beans.xml")); + SpringApplication.main(getArgs(getClass().getName(), "org/springframework/boot/sample-beans.xml")); assertThat(getOutput()).contains(SPRING_STARTUP); } private String[] getArgs(String... args) { - List list = new ArrayList<>( - Arrays.asList("--spring.main.web-application-type=none", - "--spring.main.show-banner=OFF", - "--spring.main.register-shutdownHook=false")); + List list = new ArrayList<>(Arrays.asList("--spring.main.web-application-type=none", + "--spring.main.show-banner=OFF", "--spring.main.register-shutdownHook=false")); if (args.length > 0) { - list.add("--spring.main.sources=" - + StringUtils.arrayToCommaDelimitedString(args)); + list.add("--spring.main.sources=" + StringUtils.arrayToCommaDelimitedString(args)); } return StringUtils.toStringArray(list); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java index 6357e62e36b..fb5cbf075c3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java @@ -49,8 +49,7 @@ public class SpringApplicationNoWebTests { @Test public void detectWebApplicationTypeToNone() { SpringApplication application = new SpringApplication(ExampleConfig.class); - assertThat(application.getWebApplicationType()) - .isEqualTo(WebApplicationType.NONE); + assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.NONE); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index 5f0089dbb3c..70461eeec23 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -171,22 +171,20 @@ public class SpringApplicationTests { @Test public void sourcesMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringApplication((Class[]) null).run()) + assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication((Class[]) null).run()) .withMessageContaining("PrimarySources must not be null"); } @Test public void sourcesMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringApplication().run()) + assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication().run()) .withMessageContaining("Sources must not be empty"); } @Test public void sourcesMustBeAccessible() { - assertThatIllegalArgumentException().isThrownBy( - () -> new SpringApplication(InaccessibleConfiguration.class).run()) + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringApplication(InaccessibleConfiguration.class).run()) .withMessageContaining("No visible constructors"); } @@ -194,8 +192,7 @@ public class SpringApplicationTests { public void customBanner() { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application - .run("--spring.banner.location=classpath:test-banner.txt"); + this.context = application.run("--spring.banner.location=classpath:test-banner.txt"); assertThat(this.output.toString()).startsWith("Running a Test!"); } @@ -203,8 +200,7 @@ public class SpringApplicationTests { public void customBannerWithProperties() { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application.run( - "--spring.banner.location=classpath:test-banner-with-placeholder.txt", + this.context = application.run("--spring.banner.location=classpath:test-banner-with-placeholder.txt", "--test.property=123456"); assertThat(this.output.toString()).containsPattern("Running a Test!\\s+123456"); } @@ -237,8 +233,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); - assertThat(this.output.toString()).contains( - "No active profile set, falling back to default profiles: default"); + assertThat(this.output.toString()).contains("No active profile set, falling back to default profiles: default"); } @Test @@ -246,8 +241,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.active=myprofiles"); - assertThat(this.output.toString()) - .contains("The following profiles are active: myprofile"); + assertThat(this.output.toString()).contains("The following profiles are active: myprofile"); } @Test @@ -264,20 +258,17 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); - String property = System - .getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); + String property = System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); assertThat(property).isEqualTo("true"); } @Test public void disableIgnoreBeanInfoProperty() { - System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, - "false"); + System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, "false"); SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); - String property = System - .getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); + String property = System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); assertThat(property).isEqualTo("false"); } @@ -286,8 +277,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.config.name=bindtoapplication"); - assertThat(application).hasFieldOrPropertyWithValue("bannerMode", - Banner.Mode.OFF); + assertThat(application).hasFieldOrPropertyWithValue("bannerMode", Banner.Mode.OFF); } @Test @@ -296,8 +286,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); - assertThat(application).hasFieldOrPropertyWithValue("bannerMode", - Banner.Mode.OFF); + assertThat(application).hasFieldOrPropertyWithValue("bannerMode", Banner.Mode.OFF); } @Test @@ -319,27 +308,22 @@ public class SpringApplicationTests { @Test public void specificWebApplicationContextClassDetectWebApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); - application.setApplicationContextClass( - AnnotationConfigServletWebApplicationContext.class); - assertThat(application.getWebApplicationType()) - .isEqualTo(WebApplicationType.SERVLET); + application.setApplicationContextClass(AnnotationConfigServletWebApplicationContext.class); + assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.SERVLET); } @Test public void specificReactiveApplicationContextClassDetectReactiveApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); - application.setApplicationContextClass( - AnnotationConfigReactiveWebApplicationContext.class); - assertThat(application.getWebApplicationType()) - .isEqualTo(WebApplicationType.REACTIVE); + application.setApplicationContextClass(AnnotationConfigReactiveWebApplicationContext.class); + assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.REACTIVE); } @Test public void nonWebNorReactiveApplicationContextClassDetectNoneApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(StaticApplicationContext.class); - assertThat(application.getWebApplicationType()) - .isEqualTo(WebApplicationType.NONE); + assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.NONE); } @Test @@ -347,8 +331,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); - application.setInitializers(Collections.singletonList( - (ApplicationContextInitializer) reference::set)); + application.setInitializers(Collections + .singletonList((ApplicationContextInitializer) reference::set)); this.context = application.run("--foo=bar"); assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults @@ -360,8 +344,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); - class ApplicationReadyEventListener - implements ApplicationListener { + class ApplicationReadyEventListener implements ApplicationListener { @Override public void onApplicationEvent(ApplicationReadyEvent event) { @@ -404,10 +387,8 @@ public class SpringApplicationTests { this.context = application.run(); InOrder inOrder = Mockito.inOrder(listener); inOrder.verify(listener).onApplicationEvent(isA(ApplicationStartingEvent.class)); - inOrder.verify(listener) - .onApplicationEvent(isA(ApplicationEnvironmentPreparedEvent.class)); - inOrder.verify(listener) - .onApplicationEvent(isA(ApplicationContextInitializedEvent.class)); + inOrder.verify(listener).onApplicationEvent(isA(ApplicationEnvironmentPreparedEvent.class)); + inOrder.verify(listener).onApplicationEvent(isA(ApplicationContextInitializedEvent.class)); inOrder.verify(listener).onApplicationEvent(isA(ApplicationPreparedEvent.class)); inOrder.verify(listener).onApplicationEvent(isA(ContextRefreshedEvent.class)); inOrder.verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); @@ -428,18 +409,15 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebApplicationType(WebApplicationType.SERVLET); this.context = application.run(); - assertThat(this.context) - .isInstanceOf(AnnotationConfigServletWebServerApplicationContext.class); + assertThat(this.context).isInstanceOf(AnnotationConfigServletWebServerApplicationContext.class); } @Test public void defaultApplicationContextForReactiveWeb() { - SpringApplication application = new SpringApplication( - ExampleReactiveWebConfig.class); + SpringApplication application = new SpringApplication(ExampleReactiveWebConfig.class); application.setWebApplicationType(WebApplicationType.REACTIVE); this.context = application.run(); - assertThat(this.context) - .isInstanceOf(AnnotationConfigReactiveWebServerApplicationContext.class); + assertThat(this.context).isInstanceOf(AnnotationConfigReactiveWebServerApplicationContext.class); } @Test @@ -447,24 +425,20 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebApplicationType(WebApplicationType.SERVLET); this.context = application.run(); - assertThat(this.context.getEnvironment()) - .isInstanceOf(StandardServletEnvironment.class); + assertThat(this.context.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); } @Test public void environmentForReactiveWeb() { - SpringApplication application = new SpringApplication( - ExampleReactiveWebConfig.class); + SpringApplication application = new SpringApplication(ExampleReactiveWebConfig.class); application.setWebApplicationType(WebApplicationType.REACTIVE); this.context = application.run(); - assertThat(this.context.getEnvironment()) - .isInstanceOf(StandardReactiveWebEnvironment.class); + assertThat(this.context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); } @Test public void customEnvironment() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); @@ -474,8 +448,7 @@ public class SpringApplicationTests { @Test public void customResourceLoader() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ResourceLoader resourceLoader = new DefaultResourceLoader(); application.setResourceLoader(resourceLoader); @@ -486,36 +459,31 @@ public class SpringApplicationTests { @Test public void customResourceLoaderFromConstructor() { ResourceLoader resourceLoader = new DefaultResourceLoader(); - TestSpringApplication application = new TestSpringApplication(resourceLoader, - ExampleWebConfig.class); + TestSpringApplication application = new TestSpringApplication(resourceLoader, ExampleWebConfig.class); this.context = application.run(); verify(application.getLoader()).setResourceLoader(resourceLoader); } @Test public void customBeanNameGenerator() { - TestSpringApplication application = new TestSpringApplication( - ExampleWebConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class); BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); application.setBeanNameGenerator(beanNameGenerator); this.context = application.run(); verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator); - Object actualGenerator = this.context - .getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); + Object actualGenerator = this.context.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); assertThat(actualGenerator).isSameAs(beanNameGenerator); } @Test public void customBeanNameGeneratorWithNonWebApplication() { - TestSpringApplication application = new TestSpringApplication( - ExampleWebConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class); application.setWebApplicationType(WebApplicationType.NONE); BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); application.setBeanNameGenerator(beanNameGenerator); this.context = application.run(); verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator); - Object actualGenerator = this.context - .getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); + Object actualGenerator = this.context.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); assertThat(actualGenerator).isSameAs(beanNameGenerator); } @@ -526,8 +494,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run("--foo=bar"); - assertThat(environment).has(matchingPropertySource( - CommandLinePropertySource.class, "commandLineArgs")); + assertThat(environment).has(matchingPropertySource(CommandLinePropertySource.class, "commandLineArgs")); } @Test @@ -535,24 +502,22 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addFirst(new MapPropertySource("commandLineArgs", - Collections.singletonMap("foo", "original"))); + environment.getPropertySources() + .addFirst(new MapPropertySource("commandLineArgs", Collections.singletonMap("foo", "original"))); application.setEnvironment(environment); this.context = application.run("--foo=bar", "--bar=foo"); - assertThat(environment).has( - matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); + assertThat(environment).has(matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); assertThat(environment.getProperty("bar")).isEqualTo("foo"); // New command line properties take precedence assertThat(environment.getProperty("foo")).isEqualTo("bar"); - CompositePropertySource composite = (CompositePropertySource) environment - .getPropertySources().get("commandLineArgs"); + CompositePropertySource composite = (CompositePropertySource) environment.getPropertySources() + .get("commandLineArgs"); assertThat(composite.getPropertySources()).hasSize(2); assertThat(composite.getPropertySources()).first().matches( (source) -> source.getName().equals("springApplicationCommandLineArgs"), "is named springApplicationCommandLineArgs"); - assertThat(composite.getPropertySources()).element(1).matches( - (source) -> source.getName().equals("commandLineArgs"), - "is named commandLineArgs"); + assertThat(composite.getPropertySources()).element(1) + .matches((source) -> source.getName().equals("commandLineArgs"), "is named commandLineArgs"); } @Test @@ -597,8 +562,7 @@ public class SpringApplicationTests { application.setEnvironment(environment); this.context = application.run(); // Active profile should win over default - assertThat(environment.getProperty("my.property")) - .isEqualTo("fromotherpropertiesfile"); + assertThat(environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); } @Test @@ -619,8 +583,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run("--foo=bar"); - assertThat(environment).doesNotHave( - matchingPropertySource(PropertySource.class, "commandLineArgs")); + assertThat(environment).doesNotHave(matchingPropertySource(PropertySource.class, "commandLineArgs")); } @Test @@ -657,58 +620,46 @@ public class SpringApplicationTests { @Test @SuppressWarnings("unchecked") - public void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished() - throws Exception { + public void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished() throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); ApplicationRunner applicationRunner = mock(ApplicationRunner.class); CommandLineRunner commandLineRunner = mock(CommandLineRunner.class); application.addInitializers((context) -> { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - beanFactory.registerSingleton("commandLineRunner", - (CommandLineRunner) (args) -> { - assertThat(SpringApplicationTests.this.output.toString()) - .contains("Started"); - commandLineRunner.run(args); - }); - beanFactory.registerSingleton("applicationRunner", - (ApplicationRunner) (args) -> { - assertThat(SpringApplicationTests.this.output.toString()) - .contains("Started"); - applicationRunner.run(args); - }); + beanFactory.registerSingleton("commandLineRunner", (CommandLineRunner) (args) -> { + assertThat(SpringApplicationTests.this.output.toString()).contains("Started"); + commandLineRunner.run(args); + }); + beanFactory.registerSingleton("applicationRunner", (ApplicationRunner) (args) -> { + assertThat(SpringApplicationTests.this.output.toString()).contains("Started"); + applicationRunner.run(args); + }); }); application.setWebApplicationType(WebApplicationType.NONE); - ApplicationListener eventListener = mock( - ApplicationListener.class); + ApplicationListener eventListener = mock(ApplicationListener.class); application.addListeners(eventListener); this.context = application.run(); - InOrder applicationRunnerOrder = Mockito.inOrder(eventListener, - applicationRunner); - applicationRunnerOrder.verify(applicationRunner) - .run(ArgumentMatchers.any(ApplicationArguments.class)); + InOrder applicationRunnerOrder = Mockito.inOrder(eventListener, applicationRunner); + applicationRunnerOrder.verify(applicationRunner).run(ArgumentMatchers.any(ApplicationArguments.class)); applicationRunnerOrder.verify(eventListener) .onApplicationEvent(ArgumentMatchers.any(ApplicationReadyEvent.class)); - InOrder commandLineRunnerOrder = Mockito.inOrder(eventListener, - commandLineRunner); + InOrder commandLineRunnerOrder = Mockito.inOrder(eventListener, commandLineRunner); commandLineRunnerOrder.verify(commandLineRunner).run(); commandLineRunnerOrder.verify(eventListener) .onApplicationEvent(ArgumentMatchers.any(ApplicationReadyEvent.class)); } @Test - public void applicationRunnerFailureCausesApplicationFailedEventToBePublished() - throws Exception { + public void applicationRunnerFailureCausesApplicationFailedEventToBePublished() throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") - ApplicationListener listener = mock( - ApplicationListener.class); + ApplicationListener listener = mock(ApplicationListener.class); application.addListeners(listener); ApplicationRunner runner = mock(ApplicationRunner.class); Exception failure = new Exception(); willThrow(failure).given(runner).run(isA(ApplicationArguments.class)); - application.addInitializers((context) -> context.getBeanFactory() - .registerSingleton("runner", runner)); + application.addInitializers((context) -> context.getBeanFactory().registerSingleton("runner", runner)); assertThatIllegalStateException().isThrownBy(application::run).withCause(failure); verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); @@ -716,19 +667,16 @@ public class SpringApplicationTests { } @Test - public void commandLineRunnerFailureCausesApplicationFailedEventToBePublished() - throws Exception { + public void commandLineRunnerFailureCausesApplicationFailedEventToBePublished() throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") - ApplicationListener listener = mock( - ApplicationListener.class); + ApplicationListener listener = mock(ApplicationListener.class); application.addListeners(listener); CommandLineRunner runner = mock(CommandLineRunner.class); Exception failure = new Exception(); willThrow(failure).given(runner).run(); - application.addInitializers((context) -> context.getBeanFactory() - .registerSingleton("runner", runner)); + application.addInitializers((context) -> context.getBeanFactory().registerSingleton("runner", runner)); assertThatIllegalStateException().isThrownBy(application::run).withCause(failure); verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); @@ -740,14 +688,11 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") - ApplicationListener listener = mock( - ApplicationListener.class); + ApplicationListener listener = mock(ApplicationListener.class); application.addListeners(listener); RuntimeException failure = new RuntimeException(); - willThrow(failure).given(listener) - .onApplicationEvent(isA(ApplicationReadyEvent.class)); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run) - .isEqualTo(failure); + willThrow(failure).given(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run).isEqualTo(failure); verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); } @@ -759,12 +704,10 @@ public class SpringApplicationTests { ExitCodeListener exitCodeListener = new ExitCodeListener(); application.addListeners(exitCodeListener); @SuppressWarnings("unchecked") - ApplicationListener listener = mock( - ApplicationListener.class); + ApplicationListener listener = mock(ApplicationListener.class); application.addListeners(listener); ExitStatusException failure = new ExitStatusException(); - willThrow(failure).given(listener) - .onApplicationEvent(isA(ApplicationReadyEvent.class)); + willThrow(failure).given(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run); verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); @@ -781,15 +724,13 @@ public class SpringApplicationTests { application.setUseMockLoader(true); this.context = application.run(); Set allSources = application.getAllSources(); - assertThat(allSources).contains(ExampleConfig.class, TestCommandLineRunner.class, - "a"); + assertThat(allSources).contains(ExampleConfig.class, TestCommandLineRunner.class, "a"); } @Test public void wildcardSources() { TestSpringApplication application = new TestSpringApplication(); - application.getSources().add( - "classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml"); + application.getSources().add("classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml"); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); } @@ -802,8 +743,7 @@ public class SpringApplicationTests { @Test public void runComponents() { - this.context = SpringApplication.run( - new Class[] { ExampleWebConfig.class, Object.class }, new String[0]); + this.context = SpringApplication.run(new Class[] { ExampleWebConfig.class, Object.class }, new String[0]); assertThat(this.context).isNotNull(); } @@ -824,16 +764,14 @@ public class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context).isNotNull(); - assertThat(SpringApplication.exit(this.context, (ExitCodeGenerator) () -> 2)) - .isEqualTo(2); + assertThat(SpringApplication.exit(this.context, (ExitCodeGenerator) () -> 2)).isEqualTo(2); assertThat(listener.getExitCode()).isEqualTo(2); } @Test public void exitWithExplicitCodeFromException() { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); - SpringApplication application = new SpringApplication( - ExitCodeCommandLineRunConfig.class) { + SpringApplication application = new SpringApplication(ExitCodeCommandLineRunConfig.class) { @Override SpringBootExceptionHandler getSpringBootExceptionHandler() { @@ -852,8 +790,7 @@ public class SpringApplicationTests { @Test public void exitWithExplicitCodeFromMappedException() { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); - SpringApplication application = new SpringApplication( - MappedExitCodeCommandLineRunConfig.class) { + SpringApplication application = new SpringApplication(MappedExitCodeCommandLineRunConfig.class) { @Override SpringBootExceptionHandler getSpringBootExceptionHandler() { @@ -872,8 +809,7 @@ public class SpringApplicationTests { @Test public void exceptionFromRefreshIsHandledGracefully() { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); - SpringApplication application = new SpringApplication( - RefreshFailureConfig.class) { + SpringApplication application = new SpringApplication(RefreshFailureConfig.class) { @Override SpringBootExceptionHandler getSpringBootExceptionHandler() { @@ -885,19 +821,17 @@ public class SpringApplicationTests { application.addListeners(listener); application.setWebApplicationType(WebApplicationType.NONE); assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run); - ArgumentCaptor exceptionCaptor = ArgumentCaptor - .forClass(RuntimeException.class); + ArgumentCaptor exceptionCaptor = ArgumentCaptor.forClass(RuntimeException.class); verify(handler).registerLoggedException(exceptionCaptor.capture()); - assertThat(exceptionCaptor.getValue()) - .hasCauseInstanceOf(RefreshFailureException.class); + assertThat(exceptionCaptor.getValue()).hasCauseInstanceOf(RefreshFailureException.class); assertThat(this.output.toString()).doesNotContain("NullPointerException"); } @Test public void defaultCommandLineArgs() { SpringApplication application = new SpringApplication(ExampleConfig.class); - application.setDefaultProperties(StringUtils.splitArrayElementsIntoProperties( - new String[] { "baz=", "bar=spam" }, "=")); + application.setDefaultProperties( + StringUtils.splitArrayElementsIntoProperties(new String[] { "baz=", "bar=spam" }, "=")); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--bar=foo", "bucket", "crap"); assertThat(this.context).isInstanceOf(AnnotationConfigApplicationContext.class); @@ -907,8 +841,7 @@ public class SpringApplicationTests { @Test public void commandLineArgsApplyToSpringApplication() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.main.banner-mode=OFF"); assertThat(application.getBannerMode()).isEqualTo(Banner.Mode.OFF); @@ -925,8 +858,7 @@ public class SpringApplicationTests { @Test public void registerListener() { - SpringApplication application = new SpringApplication(ExampleConfig.class, - ListenerConfig.class); + SpringApplication application = new SpringApplication(ExampleConfig.class, ListenerConfig.class); application.setApplicationContextClass(SpyApplicationContext.class); Set events = new LinkedHashSet<>(); application.addListeners((ApplicationListener) events::add); @@ -938,8 +870,8 @@ public class SpringApplicationTests { @Test public void registerListenerWithCustomMulticaster() { - SpringApplication application = new SpringApplication(ExampleConfig.class, - ListenerConfig.class, Multicaster.class); + SpringApplication application = new SpringApplication(ExampleConfig.class, ListenerConfig.class, + Multicaster.class); application.setApplicationContextClass(SpyApplicationContext.class); Set events = new LinkedHashSet<>(); application.addListeners((ApplicationListener) events::add); @@ -951,10 +883,10 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") private void verifyTestListenerEvents() { - ApplicationListener listener = this.context - .getBean("testApplicationListener", ApplicationListener.class); - verifyListenerEvents(listener, ContextRefreshedEvent.class, - ApplicationStartedEvent.class, ApplicationReadyEvent.class); + ApplicationListener listener = this.context.getBean("testApplicationListener", + ApplicationListener.class); + verifyListenerEvents(listener, ContextRefreshedEvent.class, ApplicationStartedEvent.class, + ApplicationReadyEvent.class); } @SuppressWarnings("unchecked") @@ -972,40 +904,30 @@ public class SpringApplicationTests { ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); application.addListeners(listener); - assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(application::run); - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, - ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class, - ApplicationFailedEvent.class); + assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(application::run); + verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, + ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class, ApplicationFailedEvent.class); } @SuppressWarnings("unchecked") @Test public void applicationListenerFromApplicationIsCalledWhenContextFailsRefreshAfterListenerRegistration() { ApplicationListener listener = mock(ApplicationListener.class); - SpringApplication application = new SpringApplication( - BrokenPostConstructConfig.class); + SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.addListeners(listener); - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(application::run); - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, - ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class, - ApplicationFailedEvent.class); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(application::run); + verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, + ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class, ApplicationFailedEvent.class); } @SuppressWarnings("unchecked") @Test public void applicationListenerFromContextIsCalledWhenContextFailsRefreshBeforeListenerRegistration() { - final ApplicationListener listener = mock( - ApplicationListener.class); + final ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); - application.addInitializers((applicationContext) -> applicationContext - .addApplicationListener(listener)); - assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(application::run); + application.addInitializers((applicationContext) -> applicationContext.addApplicationListener(listener)); + assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(application::run); verifyListenerEvents(listener, ApplicationFailedEvent.class); } @@ -1013,13 +935,10 @@ public class SpringApplicationTests { @Test public void applicationListenerFromContextIsCalledWhenContextFailsRefreshAfterListenerRegistration() { ApplicationListener listener = mock(ApplicationListener.class); - SpringApplication application = new SpringApplication( - BrokenPostConstructConfig.class); + SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class); application.setWebApplicationType(WebApplicationType.NONE); - application.addInitializers((applicationContext) -> applicationContext - .addApplicationListener(listener)); - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(application::run); + application.addInitializers((applicationContext) -> applicationContext.addApplicationListener(listener)); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(application::run); verifyListenerEvents(listener, ApplicationFailedEvent.class); } @@ -1030,14 +949,12 @@ public class SpringApplicationTests { application.setRegisterShutdownHook(false); this.context = application.run(); SpyApplicationContext applicationContext = (SpyApplicationContext) this.context; - verify(applicationContext.getApplicationContext(), never()) - .registerShutdownHook(); + verify(applicationContext.getApplicationContext(), never()).registerShutdownHook(); } @Test public void headless() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); assertThat(System.getProperty("java.awt.headless")).isEqualTo("true"); @@ -1045,8 +962,7 @@ public class SpringApplicationTests { @Test public void headlessFalse() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setHeadless(false); this.context = application.run(); @@ -1056,8 +972,7 @@ public class SpringApplicationTests { @Test public void headlessSystemPropertyTakesPrecedence() { System.setProperty("java.awt.headless", "false"); - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); assertThat(System.getProperty("java.awt.headless")).isEqualTo("false"); @@ -1065,8 +980,7 @@ public class SpringApplicationTests { @Test public void getApplicationArgumentsBean() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--debug", "spring", "boot"); ApplicationArguments args = this.context.getBean(ApplicationArguments.class); @@ -1076,65 +990,51 @@ public class SpringApplicationTests { @Test public void webApplicationSwitchedOffInListener() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); - application.addListeners( - (ApplicationListener) (event) -> { - assertThat(event.getEnvironment()) - .isInstanceOf(StandardServletEnvironment.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment( - event.getEnvironment(), "foo=bar"); - event.getSpringApplication() - .setWebApplicationType(WebApplicationType.NONE); - }); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); + application.addListeners((ApplicationListener) (event) -> { + assertThat(event.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(event.getEnvironment(), "foo=bar"); + event.getSpringApplication().setWebApplicationType(WebApplicationType.NONE); + }); this.context = application.run(); - assertThat(this.context.getEnvironment()) - .isNotInstanceOf(StandardServletEnvironment.class); + assertThat(this.context.getEnvironment()).isNotInstanceOf(StandardServletEnvironment.class); assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bar"); - Iterator> iterator = this.context.getEnvironment() - .getPropertySources().iterator(); + Iterator> iterator = this.context.getEnvironment().getPropertySources().iterator(); assertThat(iterator.next().getName()).isEqualTo("configurationProperties"); - assertThat(iterator.next().getName()).isEqualTo( - TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + assertThat(iterator.next().getName()) + .isEqualTo(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); } @Test public void nonWebApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { - ConfigurableApplicationContext context = new SpringApplication( - ExampleConfig.class).run("--spring.main.web-application-type=none"); - assertThat(context).isNotInstanceOfAny(WebApplicationContext.class, - ReactiveWebApplicationContext.class); - assertThat(context.getEnvironment()) - .isNotInstanceOfAny(ConfigurableWebEnvironment.class); + ConfigurableApplicationContext context = new SpringApplication(ExampleConfig.class) + .run("--spring.main.web-application-type=none"); + assertThat(context).isNotInstanceOfAny(WebApplicationContext.class, ReactiveWebApplicationContext.class); + assertThat(context.getEnvironment()).isNotInstanceOfAny(ConfigurableWebEnvironment.class); } @Test public void webApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { - ConfigurableApplicationContext context = new SpringApplication( - ExampleWebConfig.class).run("--spring.main.web-application-type=servlet"); + ConfigurableApplicationContext context = new SpringApplication(ExampleWebConfig.class) + .run("--spring.main.web-application-type=servlet"); assertThat(context).isInstanceOf(WebApplicationContext.class); - assertThat(context.getEnvironment()) - .isInstanceOf(StandardServletEnvironment.class); + assertThat(context.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); } @Test public void reactiveApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { - ConfigurableApplicationContext context = new SpringApplication( - ExampleReactiveWebConfig.class) - .run("--spring.main.web-application-type=reactive"); + ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) + .run("--spring.main.web-application-type=reactive"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); - assertThat(context.getEnvironment()) - .isInstanceOf(StandardReactiveWebEnvironment.class); + assertThat(context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); } @Test public void environmentIsConvertedIfTypeDoesNotMatch() { - ConfigurableApplicationContext context = new SpringApplication( - ExampleReactiveWebConfig.class) - .run("--spring.profiles.active=withwebapplicationtype"); + ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) + .run("--spring.profiles.active=withwebapplicationtype"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); - assertThat(context.getEnvironment()) - .isInstanceOf(StandardReactiveWebEnvironment.class); + assertThat(context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); } @Test @@ -1143,8 +1043,7 @@ public class SpringApplicationTests { Thread thread = new Thread(group, "main") { @Override public void run() { - SpringApplication application = new SpringApplication( - FailingConfig.class); + SpringApplication application = new SpringApplication(FailingConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.run(); } @@ -1158,52 +1057,45 @@ public class SpringApplicationTests { @Test public void beanDefinitionOverridingIsDisabledByDefault() { - assertThatExceptionOfType(BeanDefinitionOverrideException.class).isThrownBy( - () -> new SpringApplication(ExampleConfig.class, OverrideConfig.class) - .run()); + assertThatExceptionOfType(BeanDefinitionOverrideException.class) + .isThrownBy(() -> new SpringApplication(ExampleConfig.class, OverrideConfig.class).run()); } @Test public void beanDefinitionOverridingCanBeEnabled() { - assertThat( - new SpringApplication(ExampleConfig.class, OverrideConfig.class) - .run("--spring.main.allow-bean-definition-overriding=true", - "--spring.main.web-application-type=none") - .getBean("someBean")).isEqualTo("override"); + assertThat(new SpringApplication(ExampleConfig.class, OverrideConfig.class) + .run("--spring.main.allow-bean-definition-overriding=true", "--spring.main.web-application-type=none") + .getBean("someBean")).isEqualTo("override"); } @Test public void lazyInitializationIsDisabledByDefault() { - assertThat(new SpringApplication(LazyInitializationConfig.class) - .run("--spring.main.web-application-type=none") + assertThat(new SpringApplication(LazyInitializationConfig.class).run("--spring.main.web-application-type=none") .getBean(AtomicInteger.class)).hasValue(1); } @Test public void lazyInitializationCanBeEnabled() { assertThat(new SpringApplication(LazyInitializationConfig.class) - .run("--spring.main.web-application-type=none", - "--spring.main.lazy-initialization=true") + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") .getBean(AtomicInteger.class)).hasValue(0); } @Test public void lazyInitializationShouldNotApplyToBeansThatAreExplicitlyNotLazy() { assertThat(new SpringApplication(NotLazyInitializationConfig.class) - .run("--spring.main.web-application-type=none", - "--spring.main.lazy-initialization=true") + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") .getBean(AtomicInteger.class)).hasValue(1); } - private Condition matchingPropertySource( - final Class propertySourceClass, final String name) { + private Condition matchingPropertySource(final Class propertySourceClass, + final String name) { return new Condition("has property source") { @Override public boolean matches(ConfigurableEnvironment value) { for (PropertySource source : value.getPropertySources()) { - if (propertySourceClass.isInstance(source) - && (name == null || name.equals(source.getName()))) { + if (propertySourceClass.isInstance(source) && (name == null || name.equals(source.getName()))) { return true; } } @@ -1213,8 +1105,7 @@ public class SpringApplicationTests { }; } - private Condition runTestRunnerBean( - final String name) { + private Condition runTestRunnerBean(final String name) { return new Condition("run testrunner bean") { @Override @@ -1235,8 +1126,7 @@ public class SpringApplicationTests { public static class SpyApplicationContext extends AnnotationConfigApplicationContext { - ConfigurableApplicationContext applicationContext = spy( - new AnnotationConfigApplicationContext()); + ConfigurableApplicationContext applicationContext = spy(new AnnotationConfigApplicationContext()); @Override public void registerShutdownHook() { @@ -1275,8 +1165,7 @@ public class SpringApplicationTests { } @Override - protected BeanDefinitionLoader createBeanDefinitionLoader( - BeanDefinitionRegistry registry, Object[] sources) { + protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { if (this.useMockLoader) { this.loader = mock(BeanDefinitionLoader.class); } @@ -1401,8 +1290,7 @@ public class SpringApplicationTests { @Bean public TestCommandLineRunner runnerC() { - return new TestCommandLineRunner(Ordered.LOWEST_PRECEDENCE, "runnerB", - "runnerA"); + return new TestCommandLineRunner(Ordered.LOWEST_PRECEDENCE, "runnerB", "runnerA"); } @Bean @@ -1508,8 +1396,7 @@ public class SpringApplicationTests { } - static class ExitStatusException extends RuntimeException - implements ExitCodeGenerator { + static class ExitStatusException extends RuntimeException implements ExitCodeGenerator { @Override public int getExitCode() { @@ -1538,8 +1425,7 @@ public class SpringApplicationTests { } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -1551,8 +1437,7 @@ public class SpringApplicationTests { public void markAsRan() { this.run = true; for (String name : this.expectedBefore) { - AbstractTestRunner bean = this.applicationContext.getBean(name, - AbstractTestRunner.class); + AbstractTestRunner bean = this.applicationContext.getBean(name, AbstractTestRunner.class); assertThat(bean.hasRun()).isTrue(); } } @@ -1563,8 +1448,7 @@ public class SpringApplicationTests { } - private static class TestCommandLineRunner extends AbstractTestRunner - implements CommandLineRunner { + private static class TestCommandLineRunner extends AbstractTestRunner implements CommandLineRunner { TestCommandLineRunner(int order, String... expectedBefore) { super(order, expectedBefore); @@ -1577,8 +1461,7 @@ public class SpringApplicationTests { } - private static class TestApplicationRunner extends AbstractTestRunner - implements ApplicationRunner { + private static class TestApplicationRunner extends AbstractTestRunner implements ApplicationRunner { TestApplicationRunner(int order, String... expectedBefore) { super(order, expectedBefore); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java index 527d36a1f00..e6c42a92978 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java @@ -34,17 +34,14 @@ public class SpringBootConfigurationTests { @Test public void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, - Configuration.class); + .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test public void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes( - NoBeanMethodProxyingSpringBootConfiguration.class, - Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java index e1e683d0a86..d7b9aefa122 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class SpringBootExceptionHandlerTests { private final UncaughtExceptionHandler parent = mock(UncaughtExceptionHandler.class); - private final SpringBootExceptionHandler handler = new SpringBootExceptionHandler( - this.parent); + private final SpringBootExceptionHandler handler = new SpringBootExceptionHandler(this.parent); @Test public void uncaughtExceptionDoesNotForwardLoggedErrorToParent() { @@ -50,8 +49,7 @@ public class SpringBootExceptionHandlerTests { @Test public void uncaughtExceptionForwardsLogConfigurationErrorToParent() { Thread thread = Thread.currentThread(); - Exception ex = new Exception( - "[stuff] Logback configuration error detected [stuff]"); + Exception ex = new Exception("[stuff] Logback configuration error detected [stuff]"); this.handler.registerLoggedException(ex); this.handler.uncaughtException(thread, ex); verify(this.parent).uncaughtException(thread, ex); @@ -60,8 +58,8 @@ public class SpringBootExceptionHandlerTests { @Test public void uncaughtExceptionForwardsWrappedLogConfigurationErrorToParent() { Thread thread = Thread.currentThread(); - Exception ex = new InvocationTargetException(new Exception( - "[stuff] Logback configuration error detected [stuff]", new Exception())); + Exception ex = new InvocationTargetException( + new Exception("[stuff] Logback configuration error detected [stuff]", new Exception())); this.handler.registerLoggedException(ex); this.handler.uncaughtException(thread, ex); verify(this.parent).uncaughtException(thread, ex); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java index e4f2eb668af..228130f8cfc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java @@ -41,8 +41,7 @@ public class StartUpLoggerTests { new StartupInfoLogger(getClass()).logStarting(this.log); ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); verify(this.log).info(captor.capture()); - assertThat(captor.getValue().toString()) - .startsWith("Starting " + getClass().getSimpleName()); + assertThat(captor.getValue().toString()).startsWith("Starting " + getClass().getSimpleName()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index 2d66119202c..bf508e3c330 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -76,8 +76,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { assertThat(isApplicationReady(objectName)).isFalse(); } catch (Exception ex) { - throw new IllegalStateException( - "Could not contact spring application admin bean", ex); + throw new IllegalStateException("Could not contact spring application admin bean", ex); } }); this.context = application.run(); @@ -86,17 +85,13 @@ public class SpringApplicationAdminMXBeanRegistrarTests { @Test public void eventsFromOtherContextsAreIgnored() throws MalformedObjectNameException { - SpringApplicationAdminMXBeanRegistrar registrar = new SpringApplicationAdminMXBeanRegistrar( - OBJECT_NAME); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + SpringApplicationAdminMXBeanRegistrar registrar = new SpringApplicationAdminMXBeanRegistrar(OBJECT_NAME); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); registrar.setApplicationContext(context); registrar.onApplicationReadyEvent( - new ApplicationReadyEvent(new SpringApplication(), null, - mock(ConfigurableApplicationContext.class))); + new ApplicationReadyEvent(new SpringApplication(), null, mock(ConfigurableApplicationContext.class))); assertThat(isApplicationReady(registrar)).isFalse(); - registrar.onApplicationReadyEvent( - new ApplicationReadyEvent(new SpringApplication(), null, context)); + registrar.onApplicationReadyEvent(new ApplicationReadyEvent(new SpringApplication(), null, context)); assertThat(isApplicationReady(registrar)).isTrue(); } @@ -140,8 +135,8 @@ public class SpringApplicationAdminMXBeanRegistrarTests { private String getProperty(ObjectName objectName, String key) { try { - return (String) this.mBeanServer.invoke(objectName, "getProperty", - new Object[] { key }, new String[] { String.class.getName() }); + return (String) this.mBeanServer.invoke(objectName, "getProperty", new Object[] { key }, + new String[] { String.class.getName() }); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java index c489e2547af..dde77b6244e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,8 @@ public class AnsiOutputTests { @Test public void encoding() { - String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", - AnsiStyle.NORMAL, "D", AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); + String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", AnsiStyle.NORMAL, "D", + AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); assertThat(encoded).isEqualTo("ABDEF"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java index e1d9e780c6a..ad07de91c05 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class AnsiPropertySourceTests { @Test public void getAnsiBackground() { - assertThat(this.source.getProperty("AnsiBackground.GREEN")) - .isEqualTo(AnsiBackground.GREEN); + assertThat(this.source.getProperty("AnsiBackground.GREEN")).isEqualTo(AnsiBackground.GREEN); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index 00c90470063..b39982d4b54 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -67,41 +67,36 @@ public class SpringApplicationBuilderTests { @Test public void profileAndProperties() { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .profiles("foo").properties("foo=bar"); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class).profiles("foo").properties("foo=bar"); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bucket"); - assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("foo"))) - .isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("foo"))).isTrue(); } @Test public void propertiesAsMap() { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .properties(Collections.singletonMap("bar", "foo")); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class).properties(Collections.singletonMap("bar", "foo")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @Test public void propertiesAsProperties() { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .properties(StringUtils.splitArrayElementsIntoProperties( - new String[] { "bar=foo" }, "=")); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class) + .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @Test public void propertiesWithRepeatSeparator() { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .properties("one=c:\\logging.file.name", "two=a:b", - "three:c:\\logging.file.name", "four:a:b"); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class) + .properties("one=c:\\logging.file.name", "two=a:b", "three:c:\\logging.file.name", "four:a:b"); this.context = application.run(); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.getProperty("one")).isEqualTo("c:\\logging.file.name"); @@ -112,8 +107,7 @@ public class SpringApplicationBuilderTests { @Test public void specificApplicationContextClass() { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class) + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); @@ -121,192 +115,155 @@ public class SpringApplicationBuilderTests { @Test public void parentContextCreationThatIsRunDirectly() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class); application.parent(ExampleConfig.class); this.context = application.run("foo.bar=baz"); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isFalse(); - assertThat(this.context.getParent().getBean(ApplicationArguments.class) - .getNonOptionArgs()).contains("foo.bar=baz"); - assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()) + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isFalse(); + assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()) .contains("foo.bar=baz"); + assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("foo.bar=baz"); } @Test public void parentContextCreationThatIsBuiltThenRun() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class); application.parent(ExampleConfig.class); this.context = application.build("a=alpha").run("b=bravo"); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isFalse(); - assertThat(this.context.getParent().getBean(ApplicationArguments.class) - .getNonOptionArgs()).contains("a=alpha"); - assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()) - .contains("b=bravo"); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isFalse(); + assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()).contains("a=alpha"); + assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("b=bravo"); } @Test public void parentContextCreationWithChildShutdown() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class) - .registerShutdownHook(true); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class).registerShutdownHook(true); application.parent(ExampleConfig.class); this.context = application.run(); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isTrue(); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isTrue(); } @Test public void contextWithClassLoader() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).contextClass(SpyApplicationContext.class); - ClassLoader classLoader = new URLClassLoader(new URL[0], - getClass().getClassLoader()); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .contextClass(SpyApplicationContext.class); + ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); this.context = application.run(); - assertThat(((SpyApplicationContext) this.context).getClassLoader()) - .isEqualTo(classLoader); + assertThat(((SpyApplicationContext) this.context).getClassLoader()).isEqualTo(classLoader); } @Test public void parentContextWithClassLoader() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class); - ClassLoader classLoader = new URLClassLoader(new URL[0], - getClass().getClassLoader()); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class); + ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); application.parent(ExampleConfig.class); this.context = application.run(); - assertThat(((SpyApplicationContext) this.context).getResourceLoader() - .getClassLoader()).isEqualTo(classLoader); + assertThat(((SpyApplicationContext) this.context).getResourceLoader().getClassLoader()).isEqualTo(classLoader); } @Test public void parentFirstCreation() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).child(ChildConfig.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .child(ChildConfig.class); application.contextClass(SpyApplicationContext.class); this.context = application.run(); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isFalse(); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isFalse(); } @Test public void parentFirstCreationWithProfileAndDefaultArgs() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).profiles("node").properties("transport=redis") - .child(ChildConfig.class).web(WebApplicationType.NONE); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") + .properties("transport=redis").child(ChildConfig.class).web(WebApplicationType.NONE); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node"))) - .isTrue(); - assertThat(this.context.getEnvironment().getProperty("transport")) - .isEqualTo("redis"); - assertThat(this.context.getParent().getEnvironment() - .acceptsProfiles(Profiles.of("node"))).isTrue(); - assertThat(this.context.getParent().getEnvironment().getProperty("transport")) - .isEqualTo("redis"); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node"))).isTrue(); + assertThat(this.context.getEnvironment().getProperty("transport")).isEqualTo("redis"); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("node"))).isTrue(); + assertThat(this.context.getParent().getEnvironment().getProperty("transport")).isEqualTo("redis"); // only defined in node profile assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("spam"); } @Test public void parentFirstWithDifferentProfile() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).profiles("node").properties("transport=redis") - .child(ChildConfig.class).profiles("admin") - .web(WebApplicationType.NONE); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") + .properties("transport=redis").child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); this.context = application.run(); - assertThat(this.context.getEnvironment() - .acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); - assertThat(this.context.getParent().getEnvironment() - .acceptsProfiles(Profiles.of("admin"))).isFalse(); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("admin"))).isFalse(); } @Test public void parentWithDifferentProfile() { - SpringApplicationBuilder shared = new SpringApplicationBuilder( - ExampleConfig.class).profiles("node").properties("transport=redis"); - SpringApplicationBuilder application = shared.child(ChildConfig.class) - .profiles("admin").web(WebApplicationType.NONE); + SpringApplicationBuilder shared = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") + .properties("transport=redis"); + SpringApplicationBuilder application = shared.child(ChildConfig.class).profiles("admin") + .web(WebApplicationType.NONE); shared.profiles("parent"); this.context = application.run(); - assertThat(this.context.getEnvironment() - .acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); - assertThat(this.context.getParent().getEnvironment() - .acceptsProfiles(Profiles.of("node", "parent"))).isTrue(); - assertThat(this.context.getParent().getEnvironment() - .acceptsProfiles(Profiles.of("admin"))).isFalse(); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("node", "parent"))).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("admin"))).isFalse(); } @Test public void parentFirstWithDifferentProfileAndExplicitEnvironment() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).environment(new StandardEnvironment()) - .profiles("node").properties("transport=redis") - .child(ChildConfig.class).profiles("admin") - .web(WebApplicationType.NONE); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .environment(new StandardEnvironment()).profiles("node").properties("transport=redis") + .child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); this.context = application.run(); - assertThat(this.context.getEnvironment() - .acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); // Now they share an Environment explicitly so there's no way to keep the profiles // separate - assertThat(this.context.getParent().getEnvironment() - .acceptsProfiles(Profiles.of("admin"))).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("admin"))).isTrue(); } @Test public void parentContextIdentical() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class); application.parent(ExampleConfig.class); application.contextClass(SpyApplicationContext.class); this.context = application.run(); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); } @Test public void initializersCreatedOnce() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).web(WebApplicationType.NONE); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(4); } @Test public void initializersCreatedOnceForChild() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).child(ChildConfig.class) - .web(WebApplicationType.NONE); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .child(ChildConfig.class).web(WebApplicationType.NONE); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); } @Test public void initializersIncludeDefaults() { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).web(WebApplicationType.NONE).initializers( - (ConfigurableApplicationContext applicationContext) -> { - }); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .web(WebApplicationType.NONE).initializers((ConfigurableApplicationContext applicationContext) -> { + }); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); } @Test public void sourcesWithBoundSources() { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .web(WebApplicationType.NONE).sources(ExampleConfig.class) - .properties("spring.main.sources=" + ChildConfig.class.getName()); + SpringApplicationBuilder application = new SpringApplicationBuilder().web(WebApplicationType.NONE) + .sources(ExampleConfig.class).properties("spring.main.sources=" + ChildConfig.class.getName()); this.context = application.run(); this.context.getBean(ExampleConfig.class); this.context.getBean(ChildConfig.class); @@ -324,8 +281,7 @@ public class SpringApplicationBuilderTests { public static class SpyApplicationContext extends AnnotationConfigApplicationContext { - private final ConfigurableApplicationContext applicationContext = spy( - new AnnotationConfigApplicationContext()); + private final ConfigurableApplicationContext applicationContext = spy(new AnnotationConfigApplicationContext()); private ResourceLoader resourceLoader; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java index 28b0b93d268..4cffb008609 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java @@ -53,8 +53,7 @@ public class CloudPlatformTests { @Test public void getActiveWhenHasVcapApplicationShouldReturnCloudFoundry() { - Environment environment = new MockEnvironment().withProperty("VCAP_APPLICATION", - "---"); + Environment environment = new MockEnvironment().withProperty("VCAP_APPLICATION", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); assertThat(platform.isActive(environment)).isTrue(); @@ -62,8 +61,7 @@ public class CloudPlatformTests { @Test public void getActiveWhenHasVcapServicesShouldReturnCloudFoundry() { - Environment environment = new MockEnvironment().withProperty("VCAP_SERVICES", - "---"); + Environment environment = new MockEnvironment().withProperty("VCAP_SERVICES", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); assertThat(platform.isActive(environment)).isTrue(); @@ -79,8 +77,7 @@ public class CloudPlatformTests { @Test public void getActiveWhenHasHcLandscapeShouldReturnSap() { - Environment environment = new MockEnvironment().withProperty("HC_LANDSCAPE", - "---"); + Environment environment = new MockEnvironment().withProperty("HC_LANDSCAPE", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.SAP); assertThat(platform.isActive(environment)).isTrue(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java index e19387b010b..1dfc56386c2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,22 +40,18 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { @Test public void testApplicationProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_APPLICATION={\"application_users\":[]," - + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "VCAP_APPLICATION={\"application_users\":[]," + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"foo\",\"uris\":[\"foo.cfapps.io\"]," - + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," - + "\"started_at_timestamp\":1369795079," + + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," + "\"started_at_timestamp\":1369795079," + "\"host\":\"0.0.0.0\",\"port\":61034," + "\"limits\":{\"mem\":128,\"disk\":1024,\"fds\":16384}," + "\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"dsyerenv\",\"uris\":[\"dsyerenv.cfapps.io\"]," - + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," - + "\"state_timestamp\":1369795079}"); + + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertThat( - this.context.getEnvironment().getProperty("vcap.application.instance_id")) - .isEqualTo("bb7935245adf3e650dfb7c58a06e9ece"); + assertThat(this.context.getEnvironment().getProperty("vcap.application.instance_id")) + .isEqualTo("bb7935245adf3e650dfb7c58a06e9ece"); } @Test @@ -63,14 +59,12 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION={\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\",\"instance_index\":0,\"uris\":[\"foo.cfapps.io\"]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertThat(this.context.getEnvironment().getProperty("vcap.application.uris[0]")) - .isEqualTo("foo.cfapps.io"); + assertThat(this.context.getEnvironment().getProperty("vcap.application.uris[0]")).isEqualTo("foo.cfapps.io"); } @Test public void testUnparseableApplicationProperties() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_APPLICATION:"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION:"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap")).isNull(); } @@ -82,14 +76,12 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"foo\",\"uris\":[\"foo.cfapps.io\"]," - + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," - + "\"started_at_timestamp\":1369795079," + + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," + "\"started_at_timestamp\":1369795079," + "\"host\":\"0.0.0.0\",\"port\":61034," + "\"limits\":{\"mem\":128,\"disk\":1024,\"fds\":16384}," + "\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"dsyerenv\",\"uris\":[\"dsyerenv.cfapps.io\"]," - + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," - + "\"state_timestamp\":1369795079}"); + + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap")).isNull(); } @@ -97,10 +89,8 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { @Test public void testServiceProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_SERVICES={\"rds-mysql-n/a\":[{" - + "\"name\":\"mysql\",\"label\":\"rds-mysql-n/a\"," - + "\"plan\":\"10mb\",\"credentials\":{" - + "\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," + "VCAP_SERVICES={\"rds-mysql-n/a\":[{" + "\"name\":\"mysql\",\"label\":\"rds-mysql-n/a\"," + + "\"plan\":\"10mb\",\"credentials\":{" + "\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," + "\"hostname\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," + "\"ssl\":true,\"location\":null," + "\"host\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," @@ -116,13 +106,11 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { @Test public void testServicePropertiesWithoutNA() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_SERVICES={\"rds-mysql\":[{" - + "\"name\":\"mysql\",\"label\":\"rds-mysql\",\"plan\":\"10mb\"," + "VCAP_SERVICES={\"rds-mysql\":[{" + "\"name\":\"mysql\",\"label\":\"rds-mysql\",\"plan\":\"10mb\"," + "\"credentials\":{\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," + "\"hostname\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," + "\"host\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," - + "\"port\":3306,\"user\":\"urpRuqTf8Cpe6\"," - + "\"username\":\"urpRuqTf8Cpe6\"," + + "\"port\":3306,\"user\":\"urpRuqTf8Cpe6\"," + "\"username\":\"urpRuqTf8Cpe6\"," + "\"password\":\"pxLsGVpsC9A5S\"}}]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap.services.mysql.name")).isEqualTo("mysql"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java index bae38b2e285..e91f799c93d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java @@ -51,9 +51,8 @@ import static org.mockito.Mockito.mock; */ public class ApplicationPidFileWriterTests { - private static final ApplicationPreparedEvent EVENT = new ApplicationPreparedEvent( - new SpringApplication(), new String[] {}, - mock(ConfigurableApplicationContext.class)); + private static final ApplicationPreparedEvent EVENT = new ApplicationPreparedEvent(new SpringApplication(), + new String[] {}, mock(ConfigurableApplicationContext.class)); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -86,8 +85,7 @@ public class ApplicationPidFileWriterTests { @Test public void overridePidFileWithSpring() throws Exception { File file = this.temporaryFolder.newFile(); - SpringApplicationEvent event = createPreparedEvent("spring.pid.file", - file.getAbsolutePath()); + SpringApplicationEvent event = createPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(contentOf(file)).isNotEmpty(); @@ -96,8 +94,7 @@ public class ApplicationPidFileWriterTests { @Test public void tryEnvironmentPreparedEvent() throws Exception { File file = this.temporaryFolder.newFile(); - SpringApplicationEvent event = createEnvironmentPreparedEvent("spring.pid.file", - file.getAbsolutePath()); + SpringApplicationEvent event = createEnvironmentPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(contentOf(file)).isEmpty(); @@ -109,8 +106,7 @@ public class ApplicationPidFileWriterTests { @Test public void tryReadyEvent() throws Exception { File file = this.temporaryFolder.newFile(); - SpringApplicationEvent event = createReadyEvent("spring.pid.file", - file.getAbsolutePath()); + SpringApplicationEvent event = createReadyEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(contentOf(file)).isEmpty(); @@ -124,8 +120,7 @@ public class ApplicationPidFileWriterTests { File file = this.temporaryFolder.newFile(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.setTriggerEventType(ApplicationStartingEvent.class); - listener.onApplicationEvent( - new ApplicationStartingEvent(new SpringApplication(), new String[] {})); + listener.onApplicationEvent(new ApplicationStartingEvent(new SpringApplication(), new String[] {})); assertThat(contentOf(file)).isNotEmpty(); } @@ -144,8 +139,7 @@ public class ApplicationPidFileWriterTests { file.setReadOnly(); System.setProperty("PID_FAIL_ON_WRITE_ERROR", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); - assertThatIllegalStateException() - .isThrownBy(() -> listener.onApplicationEvent(EVENT)) + assertThatIllegalStateException().isThrownBy(() -> listener.onApplicationEvent(EVENT)) .withMessageContaining("Cannot create pid file"); } @@ -153,38 +147,29 @@ public class ApplicationPidFileWriterTests { public void throwWhenPidFileIsReadOnlyWithSpring() throws Exception { File file = this.temporaryFolder.newFile(); file.setReadOnly(); - SpringApplicationEvent event = createPreparedEvent( - "spring.pid.fail-on-write-error", "true"); + SpringApplicationEvent event = createPreparedEvent("spring.pid.fail-on-write-error", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); - assertThatIllegalStateException() - .isThrownBy(() -> listener.onApplicationEvent(event)) + assertThatIllegalStateException().isThrownBy(() -> listener.onApplicationEvent(event)) .withMessageContaining("Cannot create pid file"); } - private SpringApplicationEvent createEnvironmentPreparedEvent(String propName, - String propValue) { + private SpringApplicationEvent createEnvironmentPreparedEvent(String propName, String propValue) { ConfigurableEnvironment environment = createEnvironment(propName, propValue); - return new ApplicationEnvironmentPreparedEvent(new SpringApplication(), - new String[] {}, environment); + return new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[] {}, environment); } - private SpringApplicationEvent createPreparedEvent(String propName, - String propValue) { + private SpringApplicationEvent createPreparedEvent(String propName, String propValue) { ConfigurableEnvironment environment = createEnvironment(propName, propValue); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); given(context.getEnvironment()).willReturn(environment); - return new ApplicationPreparedEvent(new SpringApplication(), new String[] {}, - context); + return new ApplicationPreparedEvent(new SpringApplication(), new String[] {}, context); } private SpringApplicationEvent createReadyEvent(String propName, String propValue) { ConfigurableEnvironment environment = createEnvironment(propName, propValue); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); given(context.getEnvironment()).willReturn(environment); - return new ApplicationReadyEvent(new SpringApplication(), new String[] {}, - context); + return new ApplicationReadyEvent(new SpringApplication(), new String[] {}, context); } private ConfigurableEnvironment createEnvironment(String propName, String propValue) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java index bd0ff2002c3..ecdd92eea0d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,16 +105,14 @@ public class ConfigurationWarningsApplicationContextInitializerTests { @Test public void logWarningIfScanningProblemPackages() { load(InRealButScanningProblemPackages.class); - assertThat(this.output.toString()) - .contains("Your ApplicationContext is unlikely to start due to a " - + "@ComponentScan of the default package, 'org.springframework'."); + assertThat(this.output.toString()).contains("Your ApplicationContext is unlikely to start due to a " + + "@ComponentScan of the default package, 'org.springframework'."); } private void load(Class configClass) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { - new TestConfigurationWarningsApplicationContextInitializer() - .initialize(context); + new TestConfigurationWarningsApplicationContextInitializer().initialize(context); context.register(configClass); context.refresh(); } @@ -140,8 +138,7 @@ public class ConfigurationWarningsApplicationContextInitializerTests { static class TestComponentScanPackageCheck extends ComponentScanPackageCheck { @Override - protected Set getComponentScanningPackages( - BeanDefinitionRegistry registry) { + protected Set getComponentScanningPackages(BeanDefinitionRegistry registry) { Set scannedPackages = super.getComponentScanningPackages(registry); Set result = new LinkedHashSet<>(); for (String scannedPackage : scannedPackages) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java index ad4ca5cb7f1..0bee82cfd66 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class ContextIdApplicationContextInitializerTests { @Test public void singleContextWithCustomName() { - ConfigurableApplicationContext context = createContext(null, - "spring.application.name=test"); + ConfigurableApplicationContext context = createContext(null, "spring.application.name=test"); assertThat(context.getId()).isEqualTo("test"); } @@ -88,8 +87,7 @@ public class ContextIdApplicationContextInitializerTests { assertThat(createContext(parent).getId()).isEqualTo("application"); } - private ConfigurableApplicationContext createContext( - ConfigurableApplicationContext parent, String... properties) { + private ConfigurableApplicationContext createContext(ConfigurableApplicationContext parent, String... properties) { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, properties); if (parent != null) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java index 383fd2e812c..825b01e3189 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java @@ -47,8 +47,7 @@ public class FileEncodingApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.mandatory_file_encoding=FOO"); ConfigurationPropertySources.attach(this.environment); - assertThatIllegalStateException() - .isThrownBy(() -> this.initializer.onApplicationEvent(this.event)); + assertThatIllegalStateException().isThrownBy(() -> this.initializer.onApplicationEvent(this.event)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index d54050a6121..574f72e2ea7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java @@ -51,10 +51,8 @@ public class TypeExcludeFilterTests { @Test public void loadsTypeExcludeFilters() { this.context = new AnnotationConfigApplicationContext(); - this.context.getBeanFactory().registerSingleton("filter1", - new WithoutMatchOverrideFilter()); - this.context.getBeanFactory().registerSingleton("filter2", - new SampleTypeExcludeFilter()); + this.context.getBeanFactory().registerSingleton("filter1", new WithoutMatchOverrideFilter()); + this.context.getBeanFactory().registerSingleton("filter2", new SampleTypeExcludeFilter()); this.context.register(Config.class); this.context.refresh(); assertThat(this.context.getBean(ExampleComponent.class)).isNotNull(); @@ -64,8 +62,7 @@ public class TypeExcludeFilterTests { @Configuration(proxyBeanMethods = false) @ComponentScan(basePackageClasses = SampleTypeExcludeFilter.class, - excludeFilters = @Filter(type = FilterType.CUSTOM, - classes = SampleTypeExcludeFilter.class)) + excludeFilters = @Filter(type = FilterType.CUSTOM, classes = SampleTypeExcludeFilter.class)) static class Config { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java index 03d47c6a436..f87968d360f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java @@ -43,8 +43,7 @@ public class ConfigurationsTests { @Test public void createWhenClassesIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new TestConfigurations(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new TestConfigurations(null)) .withMessageContaining("Classes must not be null"); } @@ -52,22 +51,18 @@ public class ConfigurationsTests { public void createShouldSortClasses() { TestSortedConfigurations configurations = new TestSortedConfigurations( Arrays.asList(OutputStream.class, InputStream.class)); - assertThat(configurations.getClasses()).containsExactly(InputStream.class, - OutputStream.class); + assertThat(configurations.getClasses()).containsExactly(InputStream.class, OutputStream.class); } @Test public void getClassesShouldMergeByClassAndSort() { - Configurations c1 = new TestSortedConfigurations( - Arrays.asList(OutputStream.class, InputStream.class)); - Configurations c2 = new TestConfigurations( - Collections.singletonList(Short.class)); - Configurations c3 = new TestSortedConfigurations( - Arrays.asList(String.class, Integer.class)); + Configurations c1 = new TestSortedConfigurations(Arrays.asList(OutputStream.class, InputStream.class)); + Configurations c2 = new TestConfigurations(Collections.singletonList(Short.class)); + Configurations c3 = new TestSortedConfigurations(Arrays.asList(String.class, Integer.class)); Configurations c4 = new TestConfigurations(Arrays.asList(Long.class, Byte.class)); Class[] classes = Configurations.getClasses(c1, c2, c3, c4); - assertThat(classes).containsExactly(Short.class, Long.class, Byte.class, - InputStream.class, Integer.class, OutputStream.class, String.class); + assertThat(classes).containsExactly(Short.class, Long.class, Byte.class, InputStream.class, Integer.class, + OutputStream.class, String.class); } @Order(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java index a9141c09966..ec9a44ee182 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,10 +32,8 @@ public class UserConfigurationsTests { @Test public void ofShouldCreateUnorderedConfigurations() { - UserConfigurations configurations = UserConfigurations.of(OutputStream.class, - InputStream.class); - assertThat(Configurations.getClasses(configurations)) - .containsExactly(OutputStream.class, InputStream.class); + UserConfigurations configurations = UserConfigurations.of(OutputStream.class, InputStream.class); + assertThat(Configurations.getClasses(configurations)).containsExactly(OutputStream.class, InputStream.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java index 1dcc289e041..4ae5811b23b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java @@ -83,8 +83,7 @@ public class AnsiOutputApplicationListenerTests { @Test public void disabledViaApplicationProperties() { ConfigurableEnvironment environment = new StandardEnvironment(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - "spring.config.name=ansi"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "spring.config.name=ansi"); SpringApplication application = new SpringApplication(Config.class); application.setEnvironment(environment); application.setWebApplicationType(WebApplicationType.NONE); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index 093b0b8368c..ae0ada2498e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -101,8 +101,7 @@ public class ConfigFileApplicationListenerTests { @Override public Resource getResource(String location) { if (location.equals("classpath:/custom.properties")) { - return new ByteArrayResource("the.property: fromcustom".getBytes(), - location) { + return new ByteArrayResource("the.property: fromcustom".getBytes(), location) { @Override public String getFilename() { return location; @@ -143,8 +142,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoPropertiesFile() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.location=" - + "classpath:application.properties,classpath:testproperties.properties"); + "spring.config.location=" + "classpath:application.properties,classpath:testproperties.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); @@ -153,8 +151,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoPropertiesFilesWithProfiles() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.location=classpath:enableprofile.properties," - + "classpath:enableother.properties"); + "spring.config.location=classpath:enableprofile.properties," + "classpath:enableother.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("other"); String property = this.environment.getProperty("my.property"); @@ -188,8 +185,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoPropertiesFilesWithProfilesAndSwitchOneOffFromSpecificLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.name=enabletwoprofiles", - "spring.config.location=classpath:enableprofile.properties"); + "spring.config.name=enabletwoprofiles", "spring.config.location=classpath:enableprofile.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("myprofile"); String property = this.environment.getProperty("the.property"); @@ -219,8 +215,7 @@ public class ConfigFileApplicationListenerTests { @Test public void moreSpecificLocationTakesPrecedenceOverRoot() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.name=specific"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.name=specific"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); assertThat(property).isEqualTo("specific"); @@ -229,8 +224,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoOfThreePropertiesFile() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.location=classpath:application.properties," - + "classpath:testproperties.properties," + "spring.config.location=classpath:application.properties," + "classpath:testproperties.properties," + "classpath:nonexistent.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -292,8 +286,8 @@ public class ConfigFileApplicationListenerTests { @Test public void commandLineWins() { - this.environment.getPropertySources().addFirst( - new SimpleCommandLinePropertySource("--the.property=fromcommandline")); + this.environment.getPropertySources() + .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -311,9 +305,8 @@ public class ConfigFileApplicationListenerTests { @Test public void defaultPropertyAsFallback() { - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", - Collections.singletonMap("my.fallback", (Object) "foo"))); + this.environment.getPropertySources().addLast( + new MapPropertySource("defaultProperties", Collections.singletonMap("my.fallback", (Object) "foo"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.fallback"); assertThat(property).isEqualTo("foo"); @@ -321,9 +314,8 @@ public class ConfigFileApplicationListenerTests { @Test public void defaultPropertyAsFallbackDuringFileParsing() { - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", Collections - .singletonMap("spring.config.name", (Object) "testproperties"))); + this.environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", + Collections.singletonMap("spring.config.name", (Object) "testproperties"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); @@ -332,9 +324,8 @@ public class ConfigFileApplicationListenerTests { @Test public void activeProfilesFromDefaultPropertiesShouldNotTakePrecedence() { this.initializer.setSearchNames("enableprofile"); - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", - Collections.singletonMap("spring.profiles.active", "dev"))); + this.environment.getPropertySources().addLast( + new MapPropertySource("defaultProperties", Collections.singletonMap("spring.profiles.active", "dev"))); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("myprofile"); } @@ -343,12 +334,10 @@ public class ConfigFileApplicationListenerTests { public void includedProfilesFromDefaultPropertiesShouldNotTakePrecedence() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=morespecific"); - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", - Collections.singletonMap("spring.profiles.include", "dev"))); + this.environment.getPropertySources().addLast( + new MapPropertySource("defaultProperties", Collections.singletonMap("spring.profiles.include", "dev"))); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "morespecific", "yetmorespecific"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "morespecific", "yetmorespecific"); } @Test @@ -356,8 +345,7 @@ public class ConfigFileApplicationListenerTests { Map source = new HashMap<>(); source.put("spring.profiles.include", "other"); source.put("spring.profiles.active", "dev"); - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", source)); + this.environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", source)); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("other", "dev"); } @@ -366,10 +354,8 @@ public class ConfigFileApplicationListenerTests { public void activeFromDefaultPropertiesShouldNotApplyIfProfilesHaveBeenActivatedBefore() { Map source = new HashMap<>(); source.put("spring.profiles.active", "dev"); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=other"); - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", source)); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other"); + this.environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", source)); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("other"); } @@ -434,25 +420,22 @@ public class ConfigFileApplicationListenerTests { @Test public void profilesAddedToEnvironmentAndViaProperty() { // External profile takes precedence over profile added via the environment - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=other"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromotherpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); validateProfilePrecedence(null, "dev", "other"); } @Test public void profilesAddedToEnvironmentViaActiveAndIncludeProperty() { // Active profile property takes precedence - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=dev", "spring.profiles.include=other"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev", + "spring.profiles.include=other"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("other", "dev"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromdevpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); validateProfilePrecedence(null, "other", "dev"); } @@ -461,74 +444,62 @@ public class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.include=dev,simple"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "simple", - "other"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "simple", "other"); validateProfilePrecedence("dev", "simple", "other"); } @Test public void profilesAddedToEnvironmentAndViaPropertyDuplicate() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=dev,other"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev,other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromotherpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); validateProfilePrecedence(null, "dev", "other"); } @Test public void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=other,dev"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other,dev"); this.environment.addActiveProfile("other"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromdevpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); validateProfilePrecedence(null, "other", "dev"); } @Test public void postProcessorsAreOrderedCorrectly() { TestConfigFileApplicationListener testListener = new TestConfigFileApplicationListener(); - testListener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - this.application, new String[0], this.environment)); + testListener.onApplicationEvent( + new ApplicationEnvironmentPreparedEvent(this.application, new String[0], this.environment)); } private void validateProfilePrecedence(String... profiles) { - ApplicationPreparedEvent event = new ApplicationPreparedEvent( - new SpringApplication(), new String[0], + ApplicationPreparedEvent event = new ApplicationPreparedEvent(new SpringApplication(), new String[0], new AnnotationConfigApplicationContext()); withDebugLogging(() -> this.initializer.onApplicationEvent(event)); String log = this.out.toString(); // First make sure that each profile got processed only once for (String profile : profiles) { - String reason = "Wrong number of occurrences for profile '" + profile - + "' --> " + log; - assertThat(StringUtils.countOccurrencesOf(log, createLogForProfile(profile))) - .as(reason).isEqualTo(1); + String reason = "Wrong number of occurrences for profile '" + profile + "' --> " + log; + assertThat(StringUtils.countOccurrencesOf(log, createLogForProfile(profile))).as(reason).isEqualTo(1); } // Make sure the order of loading is the right one for (String profile : profiles) { String line = createLogForProfile(profile); int index = log.indexOf(line); - assertThat(index) - .as("Loading profile '" + profile + "' not found in '" + log + "'") - .isNotEqualTo(-1); + assertThat(index).as("Loading profile '" + profile + "' not found in '" + log + "'").isNotEqualTo(-1); log = log.substring(index + line.length()); } } private void withDebugLogging(Runnable runnable) { LoggerContext loggingContext = (LoggerContext) LogManager.getContext(false); - org.apache.logging.log4j.core.config.Configuration configuration = loggingContext - .getConfiguration(); + org.apache.logging.log4j.core.config.Configuration configuration = loggingContext.getConfiguration(); configuration.addLogger(ConfigFileApplicationListener.class.getName(), - new LoggerConfig(ConfigFileApplicationListener.class.getName(), - Level.DEBUG, true)); + new LoggerConfig(ConfigFileApplicationListener.class.getName(), Level.DEBUG, true)); loggingContext.updateLoggers(); try { runnable.run(); @@ -543,9 +514,8 @@ public class ConfigFileApplicationListenerTests { String suffix = (profile != null) ? "-" + profile : ""; String string = ".properties)"; return "Loaded config file '" - + new File(this.buildOutput.getTestResourcesLocation(), - "application" + suffix + ".properties").getAbsoluteFile().toURI() - .toString() + + new File(this.buildOutput.getTestResourcesLocation(), "application" + suffix + ".properties") + .getAbsoluteFile().toURI().toString() + "' (classpath:/application" + suffix + string; } @@ -625,12 +595,9 @@ public class ConfigFileApplicationListenerTests { String property = this.environment.getProperty("my.property"); assertThat(this.environment.getActiveProfiles()).contains("dev"); assertThat(property).isEqualTo("fromdevprofile"); - List names = StreamSupport - .stream(this.environment.getPropertySources().spliterator(), false) - .map(org.springframework.core.env.PropertySource::getName) - .collect(Collectors.toList()); - assertThat(names).contains( - "applicationConfig: [classpath:/testsetprofiles.yml] (document #0)", + List names = StreamSupport.stream(this.environment.getPropertySources().spliterator(), false) + .map(org.springframework.core.env.PropertySource::getName).collect(Collectors.toList()); + assertThat(names).contains("applicationConfig: [classpath:/testsetprofiles.yml] (document #0)", "applicationConfig: [classpath:/testsetprofiles.yml] (document #1)"); } @@ -638,30 +605,26 @@ public class ConfigFileApplicationListenerTests { public void yamlSetsMultiProfiles() { this.initializer.setSearchNames("testsetmultiprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "healthcheck"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test public void yamlSetsMultiProfilesWhenListProvided() { this.initializer.setSearchNames("testsetmultiprofileslist"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "healthcheck"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test public void yamlSetsMultiProfilesWithWhitespace() { this.initializer.setSearchNames("testsetmultiprofileswhitespace"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "healthcheck"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test public void yamlProfileCanBeChanged() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=prod"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=prod"); this.initializer.setSearchNames("testsetprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("prod"); @@ -670,8 +633,7 @@ public class ConfigFileApplicationListenerTests { @Test public void specificNameAndProfileFromExistingSource() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=specificprofile", - "spring.config.name=specificfile"); + "spring.profiles.active=specificprofile", "spring.config.name=specificfile"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); assertThat(property).isEqualTo("fromspecificpropertiesfile"); @@ -685,11 +647,11 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); - assertThat(this.environment).has(matchingPropertySource( - "applicationConfig: " + "[classpath:specificlocation.properties]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: " + "[classpath:specificlocation.properties]")); // The default property source is not there - assertThat(this.environment).doesNotHave(matchingPropertySource( - "applicationConfig: " + "[classpath:/application.properties]")); + assertThat(this.environment) + .doesNotHave(matchingPropertySource("applicationConfig: " + "[classpath:/application.properties]")); assertThat(this.environment.getProperty("foo")).isNull(); } @@ -701,11 +663,11 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); - assertThat(this.environment).has(matchingPropertySource( - "applicationConfig: " + "[classpath:specificlocation.properties]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: " + "[classpath:specificlocation.properties]")); // The default property source is still there - assertThat(this.environment).has(matchingPropertySource( - "applicationConfig: " + "[classpath:/application.properties]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: " + "[classpath:/application.properties]")); assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } @@ -715,8 +677,7 @@ public class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [" + location + "]")); + assertThat(this.environment).has(matchingPropertySource("applicationConfig: [" + location + "]")); } @Test @@ -725,20 +686,18 @@ public class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment).has( - matchingPropertySource("applicationConfig: [file:" + location + "]")); + assertThat(this.environment).has(matchingPropertySource("applicationConfig: [file:" + location + "]")); } @Test public void absoluteResourceDefaultsToFile() { - String location = new File("src/test/resources/specificlocation.properties") - .getAbsolutePath().replace("\\", "/"); + String location = new File("src/test/resources/specificlocation.properties").getAbsolutePath().replace("\\", + "/"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [file:" - + location.replace(File.separatorChar, '/') + "]")); + assertThat(this.environment).has( + matchingPropertySource("applicationConfig: [file:" + location.replace(File.separatorChar, '/') + "]")); } @Test @@ -750,31 +709,28 @@ public class ConfigFileApplicationListenerTests { assertThat(property).isEqualTo("fromspecificlocation"); property = context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromapplicationproperties"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[specificlocation.properties]")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[specificlocation.properties]")); context.close(); } @Test public void propertySourceAnnotationWithPlaceholder() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "source.location=specificlocation"); - SpringApplication application = new SpringApplication( - WithPropertySourcePlaceholders.class); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "source.location=specificlocation"); + SpringApplication application = new SpringApplication(WithPropertySourcePlaceholders.class); application.setEnvironment(this.environment); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[specificlocation.properties]")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[specificlocation.properties]")); context.close(); } @Test public void propertySourceAnnotationWithName() { - SpringApplication application = new SpringApplication( - WithPropertySourceAndName.class); + SpringApplication application = new SpringApplication(WithPropertySourceAndName.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); @@ -785,50 +741,45 @@ public class ConfigFileApplicationListenerTests { @Test public void propertySourceAnnotationInProfile() { - SpringApplication application = new SpringApplication( - WithPropertySourceInProfile.class); + SpringApplication application = new SpringApplication(WithPropertySourceInProfile.class); application.setWebApplicationType(WebApplicationType.NONE); - ConfigurableApplicationContext context = application - .run("--spring.profiles.active=myprofile"); + ConfigurableApplicationContext context = application.run("--spring.profiles.active=myprofile"); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[enableprofile.properties]")); - assertThat(context.getEnvironment()).doesNotHave(matchingPropertySource( - "classpath:/" + "enableprofile-myprofile.properties")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[enableprofile.properties]")); + assertThat(context.getEnvironment()) + .doesNotHave(matchingPropertySource("classpath:/" + "enableprofile-myprofile.properties")); context.close(); } @Test public void propertySourceAnnotationAndNonActiveProfile() { - SpringApplication application = new SpringApplication( - WithPropertySourceAndProfile.class); + SpringApplication application = new SpringApplication(WithPropertySourceAndProfile.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromapplicationproperties"); - assertThat(context.getEnvironment()).doesNotHave(matchingPropertySource( - "classpath:" + "/enableprofile-myprofile.properties")); + assertThat(context.getEnvironment()) + .doesNotHave(matchingPropertySource("classpath:" + "/enableprofile-myprofile.properties")); context.close(); } @Test public void propertySourceAnnotationMultipleLocations() { - SpringApplication application = new SpringApplication( - WithPropertySourceMultipleLocations.class); + SpringApplication application = new SpringApplication(WithPropertySourceMultipleLocations.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frommorepropertiesfile"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[specificlocation.properties]")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[specificlocation.properties]")); context.close(); } @Test public void propertySourceAnnotationMultipleLocationsAndName() { - SpringApplication application = new SpringApplication( - WithPropertySourceMultipleLocationsAndName.class); + SpringApplication application = new SpringApplication(WithPropertySourceMultipleLocationsAndName.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); @@ -848,8 +799,8 @@ public class ConfigFileApplicationListenerTests { assertThat(environment).has(matchingProfile("morespecific")); assertThat(environment).has(matchingProfile("yetmorespecific")); assertThat(environment).doesNotHave(matchingProfile("missing")); - assertThat(this.out.toString()).contains( - "The following profiles are active: includeprofile,specific,morespecific,yetmorespecific"); + assertThat(this.out.toString()) + .contains("The following profiles are active: includeprofile,specific,morespecific,yetmorespecific"); } @Test @@ -857,8 +808,7 @@ public class ConfigFileApplicationListenerTests { // gh-340 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application - .run("--spring.profiles.active=activeprofilewithsubdoc"); + this.context = application.run("--spring.profiles.active=activeprofilewithsubdoc"); String property = this.context.getEnvironment().getProperty("foobar"); assertThat(property).isEqualTo("baz"); } @@ -868,8 +818,8 @@ public class ConfigFileApplicationListenerTests { // gh-4132 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application.run( - "--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); + this.context = application + .run("--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); String property = this.context.getEnvironment().getProperty("foobar"); assertThat(property).isEqualTo("baz"); } @@ -898,12 +848,10 @@ public class ConfigFileApplicationListenerTests { public void customDefaultProfileAndActive() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application.run("--spring.profiles.default=customdefault", - "--spring.profiles.active=dev"); + this.context = application.run("--spring.profiles.default=customdefault", "--spring.profiles.active=dev"); String property = this.context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromdevpropertiesfile"); - assertThat(this.context.getEnvironment().containsProperty("customdefault")) - .isFalse(); + assertThat(this.context.getEnvironment().containsProperty("customdefault")).isFalse(); } @Test @@ -911,8 +859,7 @@ public class ConfigFileApplicationListenerTests { // gh-5998 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application.run("--spring.config.name=customprofile", - "--spring.profiles.default=customdefault"); + this.context = application.run("--spring.config.name=customprofile", "--spring.profiles.default=customdefault"); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.containsProperty("customprofile")).isTrue(); assertThat(environment.containsProperty("customprofile-specific")).isTrue(); @@ -924,12 +871,10 @@ public class ConfigFileApplicationListenerTests { public void additionalProfilesCanBeIncludedFromAnyPropertySource() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - this.context = application.run("--spring.profiles.active=myprofile", - "--spring.profiles.include=dev"); + this.context = application.run("--spring.profiles.active=myprofile", "--spring.profiles.include=dev"); String property = this.context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromdevpropertiesfile"); - assertThat(this.context.getEnvironment().containsProperty("customdefault")) - .isFalse(); + assertThat(this.context.getEnvironment().containsProperty("customdefault")).isFalse(); } @Test @@ -945,13 +890,11 @@ public class ConfigFileApplicationListenerTests { public void activeProfilesCanBeConfiguredUsingPlaceholdersResolvedAgainstTheEnvironment() { Map source = new HashMap<>(); source.put("activeProfile", "testPropertySource"); - org.springframework.core.env.PropertySource propertySource = new MapPropertySource( - "test", source); + org.springframework.core.env.PropertySource propertySource = new MapPropertySource("test", source); this.environment.getPropertySources().addLast(propertySource); this.initializer.setSearchNames("testactiveprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()) - .containsExactly("testPropertySource"); + assertThat(this.environment.getActiveProfiles()).containsExactly("testPropertySource"); } @Test @@ -966,8 +909,7 @@ public class ConfigFileApplicationListenerTests { @Test public void lastAdditionalLocationWins() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.additional-location=classpath:override.properties," - + "classpath:some.properties"); + "spring.config.additional-location=classpath:override.properties," + "classpath:some.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getProperty("foo")).isEqualTo("spam"); assertThat(this.environment.getProperty("value")).isEqualTo("1234"); @@ -1019,10 +961,8 @@ public class ConfigFileApplicationListenerTests { assertThat(this.environment.getProperty("customloader1")).isEqualTo("true"); } - private Condition matchingPropertySource( - final String sourceName) { - return new Condition( - "environment containing property source " + sourceName) { + private Condition matchingPropertySource(final String sourceName) { + return new Condition("environment containing property source " + sourceName) { @Override public boolean matches(ConfigurableEnvironment value) { @@ -1080,37 +1020,32 @@ public class ConfigFileApplicationListenerTests { } @Configuration(proxyBeanMethods = false) - @PropertySource({ "classpath:/specificlocation.properties", - "classpath:/moreproperties.properties" }) + @PropertySource({ "classpath:/specificlocation.properties", "classpath:/moreproperties.properties" }) protected static class WithPropertySourceMultipleLocations { } @Configuration(proxyBeanMethods = false) - @PropertySource(value = { "classpath:/specificlocation.properties", - "classpath:/moreproperties.properties" }, name = "foo") + @PropertySource(value = { "classpath:/specificlocation.properties", "classpath:/moreproperties.properties" }, + name = "foo") protected static class WithPropertySourceMultipleLocationsAndName { } - private static class TestConfigFileApplicationListener - extends ConfigFileApplicationListener { + private static class TestConfigFileApplicationListener extends ConfigFileApplicationListener { @Override List loadPostProcessors() { - return new ArrayList<>(Collections - .singletonList(new LowestPrecedenceEnvironmentPostProcessor())); + return new ArrayList<>(Collections.singletonList(new LowestPrecedenceEnvironmentPostProcessor())); } } @Order(Ordered.LOWEST_PRECEDENCE) - private static class LowestPrecedenceEnvironmentPostProcessor - implements EnvironmentPostProcessor { + private static class LowestPrecedenceEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { assertThat(environment.getPropertySources()).hasSize(5); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java index 747b86a441e..1981d40b343 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java @@ -144,12 +144,10 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { assertThat(this.context.getEnvironment().getProperty("not-e")).isNull(); } - private void assertVersionProperty(ConfigurableApplicationContext context, - String expectedVersion, String... expectedActiveProfiles) { - assertThat(context.getEnvironment().getActiveProfiles()) - .isEqualTo(expectedActiveProfiles); - assertThat(context.getEnvironment().getProperty("version")).as("version mismatch") - .isEqualTo(expectedVersion); + private void assertVersionProperty(ConfigurableApplicationContext context, String expectedVersion, + String... expectedActiveProfiles) { + assertThat(context.getEnvironment().getActiveProfiles()).isEqualTo(expectedActiveProfiles); + assertThat(context.getEnvironment().getProperty("version")).as("version mismatch").isEqualTo(expectedVersion); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index 6efbdb532dc..33c6bc2e26d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ public class DelegatingApplicationContextInitializerTests { public void orderedInitialize() { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "context.initializer.classes=" + MockInitB.class.getName() + "," - + MockInitA.class.getName()); + "context.initializer.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); this.initializer.initialize(context); assertThat(context.getBeanFactory().getSingleton("a")).isEqualTo("a"); assertThat(context.getBeanFactory().getSingleton("b")).isEqualTo("b"); @@ -60,8 +59,7 @@ public class DelegatingApplicationContextInitializerTests { @Test public void emptyInitializers() { StaticApplicationContext context = new StaticApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "context.initializer.classes:"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes:"); this.initializer.initialize(context); } @@ -79,8 +77,7 @@ public class DelegatingApplicationContextInitializerTests { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + Object.class.getName()); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.initializer.initialize(context)); + assertThatIllegalArgumentException().isThrownBy(() -> this.initializer.initialize(context)); } @Test @@ -88,14 +85,12 @@ public class DelegatingApplicationContextInitializerTests { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + NotSuitableInit.class.getName()); - assertThatIllegalArgumentException() - .isThrownBy(() -> this.initializer.initialize(context)) + assertThatIllegalArgumentException().isThrownBy(() -> this.initializer.initialize(context)) .withMessageContaining("generic parameter"); } @Order(Ordered.HIGHEST_PRECEDENCE) - private static class MockInitA - implements ApplicationContextInitializer { + private static class MockInitA implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -105,20 +100,17 @@ public class DelegatingApplicationContextInitializerTests { } @Order(Ordered.LOWEST_PRECEDENCE) - private static class MockInitB - implements ApplicationContextInitializer { + private static class MockInitB implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { - assertThat(applicationContext.getBeanFactory().getSingleton("a")) - .isEqualTo("a"); + assertThat(applicationContext.getBeanFactory().getSingleton("a")).isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } } - private static class NotSuitableInit - implements ApplicationContextInitializer { + private static class NotSuitableInit implements ApplicationContextInitializer { @Override public void initialize(ConfigurableWebApplicationContext applicationContext) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java index e03c6cd922f..7d36faf2744 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,10 +52,9 @@ public class DelegatingApplicationListenerTests { @Test public void orderedInitialize() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "context.listener.classes=" + MockInitB.class.getName() + "," - + MockInitA.class.getName()); - this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - new SpringApplication(), new String[0], this.context.getEnvironment())); + "context.listener.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); + this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], + this.context.getEnvironment())); this.context.getBeanFactory().registerSingleton("testListener", this.listener); this.context.refresh(); assertThat(this.context.getBeanFactory().getSingleton("a")).isEqualTo("a"); @@ -64,16 +63,15 @@ public class DelegatingApplicationListenerTests { @Test public void noInitializers() { - this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - new SpringApplication(), new String[0], this.context.getEnvironment())); + this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], + this.context.getEnvironment())); } @Test public void emptyInitializers() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "context.listener.classes:"); - this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - new SpringApplication(), new String[0], this.context.getEnvironment())); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "context.listener.classes:"); + this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], + this.context.getEnvironment())); } @Order(Ordered.HIGHEST_PRECEDENCE) @@ -95,8 +93,7 @@ public class DelegatingApplicationListenerTests { public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event .getApplicationContext(); - assertThat(applicationContext.getBeanFactory().getSingleton("a")) - .isEqualTo("a"); + assertThat(applicationContext.getBeanFactory().getSingleton("a")).isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader1.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader1.java index b5df10887a3..344673b5d0a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader1.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader1.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ class TestPropertySourceLoader1 implements PropertySourceLoader { } @Override - public List> load(String name, Resource resource) - throws IOException { + public List> load(String name, Resource resource) throws IOException { Map map = Collections.singletonMap("customloader1", "true"); return Collections.singletonList(new MapPropertySource(name, map)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader2.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader2.java index d117a54105a..c072fb9c041 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader2.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestPropertySourceLoader2.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ class TestPropertySourceLoader2 implements PropertySourceLoader { } @Override - public List> load(String name, Resource resource) - throws IOException { + public List> load(String name, Resource resource) throws IOException { Map map = Collections.singletonMap("customloader2", "true"); return Collections.singletonList(new MapPropertySource(name, map)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java index eb7cae88753..30791addb27 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java @@ -22,8 +22,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) -@ComponentScan(basePackageClasses = { InDefaultPackageConfiguration.class, - InOrgSpringPackageConfiguration.class }) +@ComponentScan(basePackageClasses = { InDefaultPackageConfiguration.class, InOrgSpringPackageConfiguration.class }) public class InRealButScanningProblemPackages { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java index 7414b5cbe24..b7879020698 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,9 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; public class SampleTypeExcludeFilter extends TypeExcludeFilter { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - return metadataReader.getClassMetadata().getClassName() - .equals(ExampleFilteredComponent.class.getName()); + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + return metadataReader.getClassMetadata().getClassName().equals(ExampleFilteredComponent.class.getName()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java index cc3e9650443..89ffe1444f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ public class LoggingApplicationListenerIntegrationTests { @Test public void loggingSystemRegisteredInTheContext() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - SampleService.class).web(WebApplicationType.NONE).run()) { + try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) + .web(WebApplicationType.NONE).run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.loggingSystem).isNotNull(); } @@ -53,9 +53,8 @@ public class LoggingApplicationListenerIntegrationTests { @Test public void loggingPerformedDuringChildApplicationStartIsNotLost() { - new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) - .child(Config.class).web(WebApplicationType.NONE) - .listeners(new ApplicationListener() { + new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).child(Config.class) + .web(WebApplicationType.NONE).listeners(new ApplicationListener() { private final Logger logger = LoggerFactory.getLogger(getClass()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index 6e45b15caf9..128ab8ac754 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -96,11 +96,9 @@ public class LoggingApplicationListenerTests { private final LoggingApplicationListener initializer = new LoggingApplicationListener(); - private final LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder - .getSingleton().getLoggerFactory(); + private final LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); - private final ch.qos.logback.classic.Logger logger = this.loggerContext - .getLogger(getClass()); + private final ch.qos.logback.classic.Logger logger = this.loggerContext.getLogger(getClass()); private final SpringApplication springApplication = new SpringApplication(); @@ -110,8 +108,7 @@ public class LoggingApplicationListenerTests { @Before public void init() throws SecurityException, IOException { - LogManager.getLogManager().readConfiguration( - JavaLoggingSystem.class.getResourceAsStream("logging.properties")); + LogManager.getLogManager().readConfiguration(JavaLoggingSystem.class.getResourceAsStream("logging.properties")); multicastEvent(new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); this.logFile = new File(this.temp.getRoot(), "foo.log"); new File(tmpDir() + "/spring.log").delete(); @@ -139,8 +136,7 @@ public class LoggingApplicationListenerTests { } private String tmpDir() { - String path = this.context.getEnvironment() - .resolvePlaceholders("${java.io.tmpdir}"); + String path = this.context.getEnvironment().resolvePlaceholders("${java.io.tmpdir}"); path = path.replace("\\", "/"); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); @@ -150,8 +146,7 @@ public class LoggingApplicationListenerTests { @Test public void baseConfigLocation() { - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.outputCapture.expect(containsString("Hello world")); this.outputCapture.expect(not(containsString("???"))); this.outputCapture.expect(containsString("[junit-")); @@ -161,24 +156,20 @@ public class LoggingApplicationListenerTests { @Test public void overrideConfigLocation() { - addPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); - assertThat(output).contains("Hello world").doesNotContain("???") - .startsWith("null ").endsWith("BOOTBOOT"); + assertThat(output).contains("Hello world").doesNotContain("???").startsWith("null ").endsWith("BOOTBOOT"); } @Test public void overrideConfigDoesNotExist() { addPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); assertThatIllegalStateException().isThrownBy(() -> { - this.outputCapture.expect(containsString( - "Logging system failed to initialize using configuration from 'doesnotexist.xml'")); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.outputCapture.expect( + containsString("Logging system failed to initialize using configuration from 'doesnotexist.xml'")); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); }); } @@ -186,8 +177,7 @@ public class LoggingApplicationListenerTests { public void azureDefaultLoggingConfigDoesNotCauseAFailure() { addPropertiesToEnvironment(this.context, "logging.config=-Djava.util.logging.config.file=\"d:\\home\\site\\wwwroot\\bin\\apache-tomcat-7.0.52\\conf\\logging.properties\""); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("???"); @@ -197,8 +187,7 @@ public class LoggingApplicationListenerTests { @Test public void tomcatNopLoggingConfigDoesNotCauseAFailure() { addPropertiesToEnvironment(this.context, "LOGGING_CONFIG=-Dnop"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("???"); @@ -207,45 +196,37 @@ public class LoggingApplicationListenerTests { @Test public void overrideConfigBroken() { - addPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-broken.xml"); + addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-broken.xml"); assertThatIllegalStateException().isThrownBy(() -> { this.outputCapture.expect(containsString( "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'")); this.outputCapture.expect(containsString("ConsolAppender")); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); }); } @Test public void addLogFileProperty() { - addPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", + addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.file.name=" + this.logFile); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); String existingOutput = this.outputCapture.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()) - .trim(); + String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); assertThat(output).startsWith(this.logFile.getAbsolutePath()); } @Test @Deprecated public void addLogFilePropertyWithDeprecatedProperty() { - addPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", + addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.file=" + this.logFile); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); String existingOutput = this.outputCapture.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()) - .trim(); + String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); assertThat(output).startsWith(this.logFile.getAbsolutePath()); } @@ -253,8 +234,7 @@ public class LoggingApplicationListenerTests { public void addLogFilePropertyWithDefault() { assertThat(this.logFile).doesNotExist(); addPropertiesToEnvironment(this.context, "logging.file.name=" + this.logFile); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); assertThat(this.logFile).isFile(); @@ -265,8 +245,7 @@ public class LoggingApplicationListenerTests { public void addLogFilePropertyWithDefaultAndDeprecatedProperty() { assertThat(this.logFile).doesNotExist(); addPropertiesToEnvironment(this.context, "logging.file=" + this.logFile); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); assertThat(this.logFile).isFile(); @@ -274,41 +253,32 @@ public class LoggingApplicationListenerTests { @Test public void addLogPathProperty() { - addPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", + addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.file.path=" + this.temp.getRoot()); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); String existingOutput = this.outputCapture.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()) - .trim(); - assertThat(output).startsWith( - new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); + String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); + assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); } @Test public void addLogPathPropertyWithDeprecatedProperty() { - addPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", + addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.path=" + this.temp.getRoot()); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); String existingOutput = this.outputCapture.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()) - .trim(); - assertThat(output).startsWith( - new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); + String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); + assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); } @Test public void parseDebugArg() { addPropertiesToEnvironment(this.context, "debug"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -318,10 +288,8 @@ public class LoggingApplicationListenerTests { @Test public void parseDebugArgExpandGroups() { addPropertiesToEnvironment(this.context, "debug"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); - this.loggerContext.getLogger("org.springframework.boot.actuate.endpoint.web") - .debug("testdebugwebgroup"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); + this.loggerContext.getLogger("org.springframework.boot.actuate.endpoint.web").debug("testdebugwebgroup"); this.loggerContext.getLogger("org.hibernate.SQL").debug("testdebugsqlgroup"); assertThat(this.outputCapture.toString()).contains("testdebugwebgroup"); assertThat(this.outputCapture.toString()).contains("testdebugsqlgroup"); @@ -330,8 +298,7 @@ public class LoggingApplicationListenerTests { @Test public void parseTraceArg() { addPropertiesToEnvironment(this.context, "trace"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -350,8 +317,7 @@ public class LoggingApplicationListenerTests { private void disableDebugTraceArg(String... environment) { addPropertiesToEnvironment(this.context, environment); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); @@ -360,10 +326,8 @@ public class LoggingApplicationListenerTests { @Test public void parseLevels() { - addPropertiesToEnvironment(this.context, - "logging.level.org.springframework.boot=TRACE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=TRACE"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -372,10 +336,8 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsCaseInsensitive() { - addPropertiesToEnvironment(this.context, - "logging.level.org.springframework.boot=TrAcE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=TrAcE"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -384,10 +346,8 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsTrimsWhitespace() { - addPropertiesToEnvironment(this.context, - "logging.level.org.springframework.boot= trace "); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot= trace "); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -396,10 +356,8 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsWithPlaceholder() { - addPropertiesToEnvironment(this.context, "foo=TRACE", - "logging.level.org.springframework.boot=${foo}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "foo=TRACE", "logging.level.org.springframework.boot=${foo}"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -408,45 +366,35 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsFails() { - addPropertiesToEnvironment(this.context, - "logging.level.org.springframework.boot=GARBAGE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .contains("Cannot set level 'GARBAGE'"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").contains("Cannot set level 'GARBAGE'"); } @Test public void parseLevelsNone() { - addPropertiesToEnvironment(this.context, - "logging.level.org.springframework.boot=OFF"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=OFF"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.error("testaterror"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .doesNotContain("testaterror"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testaterror"); } @Test public void parseLevelsMapsFalseToOff() { - addPropertiesToEnvironment(this.context, - "logging.level.org.springframework.boot=false"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=false"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.error("testaterror"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .doesNotContain("testaterror"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testaterror"); } @Test public void parseArgsDisabled() { this.initializer.setParseArgs(false); addPropertiesToEnvironment(this.context, "debug"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); } @@ -455,10 +403,8 @@ public class LoggingApplicationListenerTests { public void parseArgsDoesntReplace() { this.initializer.setSpringBootLogging(LogLevel.ERROR); this.initializer.setParseArgs(false); - multicastEvent(new ApplicationStartingEvent(this.springApplication, - new String[] { "--debug" })); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[] { "--debug" })); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); } @@ -472,34 +418,26 @@ public class LoggingApplicationListenerTests { @Test public void defaultExceptionConversionWord() { - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect( - not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"))); - this.logger.info("Hello world", - new RuntimeException("Wrapper", new RuntimeException("Expected"))); + this.outputCapture.expect(not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"))); + this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); } @Test public void overrideExceptionConversionWord() { addPropertiesToEnvironment(this.context, "logging.exceptionConversionWord=%rEx"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect( - containsString("Wrapped by: java.lang.RuntimeException: Wrapper")); - this.logger.info("Hello world", - new RuntimeException("Wrapper", new RuntimeException("Expected"))); + this.outputCapture.expect(containsString("Wrapped by: java.lang.RuntimeException: Wrapper")); + this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); } @Test public void shutdownHookIsNotRegisteredByDefault() { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); - System.setProperty(LoggingSystem.class.getName(), - TestShutdownHandlerLoggingSystem.class.getName()); - multicastEvent(listener, - new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); + System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); + multicastEvent(listener, new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(listener.shutdownHook).isNull(); } @@ -507,24 +445,19 @@ public class LoggingApplicationListenerTests { @Test public void shutdownHookCanBeRegistered() throws Exception { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); - System.setProperty(LoggingSystem.class.getName(), - TestShutdownHandlerLoggingSystem.class.getName()); + System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); addPropertiesToEnvironment(this.context, "logging.register_shutdown_hook=true"); - multicastEvent(listener, - new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); + multicastEvent(listener, new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(listener.shutdownHook).isNotNull(); listener.shutdownHook.start(); - assertThat(TestShutdownHandlerLoggingSystem.shutdownLatch.await(30, - TimeUnit.SECONDS)).isTrue(); + assertThat(TestShutdownHandlerLoggingSystem.shutdownLatch.await(30, TimeUnit.SECONDS)).isTrue(); } @Test public void closingContextCleansUpLoggingSystem() { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - TestCleanupLoggingSystem.class.getName()); - multicastEvent( - new ApplicationStartingEvent(this.springApplication, new String[0])); + System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -534,10 +467,8 @@ public class LoggingApplicationListenerTests { @Test public void closingChildContextDoesNotCleanUpLoggingSystem() { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - TestCleanupLoggingSystem.class.getName()); - multicastEvent( - new ApplicationStartingEvent(this.springApplication, new String[0])); + System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -552,80 +483,58 @@ public class LoggingApplicationListenerTests { @Test public void systemPropertiesAreSetForLoggingConfiguration() { - addPropertiesToEnvironment(this.context, - "logging.exception-conversion-word=conversion", - "logging.file.name=" + this.logFile, "logging.file.path=path", - "logging.pattern.console=console", "logging.pattern.file=file", - "logging.pattern.level=level"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); - assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo("console"); - assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)) - .isEqualTo("file"); - assertThat(System.getProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD)) - .isEqualTo("conversion"); - assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo(this.logFile.getAbsolutePath()); - assertThat(System.getProperty(LoggingSystemProperties.LOG_LEVEL_PATTERN)) - .isEqualTo("level"); - assertThat(System.getProperty(LoggingSystemProperties.LOG_PATH)) - .isEqualTo("path"); + addPropertiesToEnvironment(this.context, "logging.exception-conversion-word=conversion", + "logging.file.name=" + this.logFile, "logging.file.path=path", "logging.pattern.console=console", + "logging.pattern.file=file", "logging.pattern.level=level"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); + assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).isEqualTo("console"); + assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).isEqualTo("file"); + assertThat(System.getProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD)).isEqualTo("conversion"); + assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)).isEqualTo(this.logFile.getAbsolutePath()); + assertThat(System.getProperty(LoggingSystemProperties.LOG_LEVEL_PATTERN)).isEqualTo("level"); + assertThat(System.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("path"); assertThat(System.getProperty(LoggingSystemProperties.PID_KEY)).isNotNull(); } @Test @Deprecated public void systemPropertiesAreSetForLoggingConfigurationWithDeprecatedProperties() { - addPropertiesToEnvironment(this.context, "logging.file=" + this.logFile, - "logging.path=path"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); - assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo(this.logFile.getAbsolutePath()); - assertThat(System.getProperty(LoggingSystemProperties.LOG_PATH)) - .isEqualTo("path"); + addPropertiesToEnvironment(this.context, "logging.file=" + this.logFile, "logging.path=path"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); + assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)).isEqualTo(this.logFile.getAbsolutePath()); + assertThat(System.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("path"); } @Test public void environmentPropertiesIgnoreUnresolvablePlaceholders() { // gh-7719 - addPropertiesToEnvironment(this.context, - "logging.pattern.console=console ${doesnotexist}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${doesnotexist}"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) .isEqualTo("console ${doesnotexist}"); } @Test public void environmentPropertiesResolvePlaceholders() { - addPropertiesToEnvironment(this.context, - "logging.pattern.console=console ${pid}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${pid}"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo(this.context.getEnvironment() - .getProperty("logging.pattern.console")); + .isEqualTo(this.context.getEnvironment().getProperty("logging.pattern.console")); } @Test public void logFilePropertiesCanReferenceSystemProperties() { - addPropertiesToEnvironment(this.context, "logging.file.name=" - + this.temp.getRoot().getAbsolutePath() + "${PID}.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, + "logging.file.name=" + this.temp.getRoot().getAbsolutePath() + "${PID}.log"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo(this.temp.getRoot().getAbsolutePath() - + new ApplicationPid().toString() + ".log"); + .isEqualTo(this.temp.getRoot().getAbsolutePath() + new ApplicationPid().toString() + ".log"); } @Test public void applicationFailedEventCleansUpLoggingSystem() { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - TestCleanupLoggingSystem.class.getName()); - multicastEvent( - new ApplicationStartingEvent(this.springApplication, new String[0])); + System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -636,14 +545,11 @@ public class LoggingApplicationListenerTests { @Test public void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() { - MutablePropertySources propertySources = this.context.getEnvironment() - .getPropertySources(); - propertySources.addFirst(new MapPropertySource("test1", - Collections.singletonMap("logging.level.ROOT", "DEBUG"))); - propertySources.addLast(new MapPropertySource("test2", - Collections.singletonMap("logging.level.root", "WARN"))); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); + propertySources + .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG"))); + propertySources.addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN"))); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); assertThat(this.outputCapture.toString()).contains("testatdebug"); } @@ -651,32 +557,27 @@ public class LoggingApplicationListenerTests { @Test public void loggingGroupsDefaultsAreApplied() { addPropertiesToEnvironment(this.context, "logging.level.web=TRACE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertTraceEnabled("org.springframework.core", false); assertTraceEnabled("org.springframework.core.codec", true); assertTraceEnabled("org.springframework.http", true); assertTraceEnabled("org.springframework.web", true); assertTraceEnabled("org.springframework.boot.actuate.endpoint.web", true); - assertTraceEnabled( - "org.springframework.boot.web.servlet.ServletContextInitializerBeans", - true); + assertTraceEnabled("org.springframework.boot.web.servlet.ServletContextInitializerBeans", true); } @Test public void loggingGroupsCanBeDefined() { - addPropertiesToEnvironment(this.context, - "logging.group.foo=com.foo.bar,com.foo.baz", "logging.level.foo=TRACE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + addPropertiesToEnvironment(this.context, "logging.group.foo=com.foo.bar,com.foo.baz", + "logging.level.foo=TRACE"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertTraceEnabled("com.foo", false); assertTraceEnabled("com.foo.bar", true); assertTraceEnabled("com.foo.baz", true); } private void assertTraceEnabled(String name, boolean expected) { - assertThat(this.loggerContext.getLogger(name).isTraceEnabled()) - .isEqualTo(expected); + assertThat(this.loggerContext.getLogger(name).isTraceEnabled()).isEqualTo(expected); } private void multicastEvent(ApplicationEvent event) { @@ -700,16 +601,14 @@ public class LoggingApplicationListenerTests { return false; } - private void addPropertiesToEnvironment(ConfigurableApplicationContext context, - String... pairs) { + private void addPropertiesToEnvironment(ConfigurableApplicationContext context, String... pairs) { ConfigurableEnvironment environment = context.getEnvironment(); Map properties = new HashMap<>(); for (String pair : pairs) { String[] split = pair.split("=", 2); properties.put(split[0], (split.length == 2) ? split[1] : ""); } - MapPropertySource propertySource = new MapPropertySource("logging-config", - properties); + MapPropertySource propertySource = new MapPropertySource("logging-config", properties); environment.getPropertySources().addFirst(propertySource); } @@ -728,13 +627,11 @@ public class LoggingApplicationListenerTests { } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { } @Override - protected void loadConfiguration( - LoggingInitializationContext initializationContext, String location, + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile) { } @@ -759,8 +656,7 @@ public class LoggingApplicationListenerTests { } - public static class TestLoggingApplicationListener - extends LoggingApplicationListener { + public static class TestLoggingApplicationListener extends LoggingApplicationListener { private Thread shutdownHook; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java index e948780badd..7905841fe57 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java @@ -47,10 +47,8 @@ public class ConfigurationPropertiesBeanRegistrarTests { private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @Test - public void typeWithDefaultConstructorShouldRegisterGenericBeanDefinition() - throws Exception { - this.registrar.registerBeanDefinitions( - getAnnotationMetadata(TestConfiguration.class), this.beanFactory); + public void typeWithDefaultConstructorShouldRegisterGenericBeanDefinition() throws Exception { + this.registrar.registerBeanDefinitions(getAnnotationMetadata(TestConfiguration.class), this.beanFactory); BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition( "foo-org.springframework.boot.context.properties.ConfigurationPropertiesBeanRegistrarTests$FooProperties"); assertThat(beanDefinition).isExactlyInstanceOf(GenericBeanDefinition.class); @@ -59,19 +57,15 @@ public class ConfigurationPropertiesBeanRegistrarTests { @Test public void typeWithOneConstructorWithParametersShouldRegisterConfigurationPropertiesBeanDefinition() throws Exception { - this.registrar.registerBeanDefinitions( - getAnnotationMetadata(TestConfiguration.class), this.beanFactory); + this.registrar.registerBeanDefinitions(getAnnotationMetadata(TestConfiguration.class), this.beanFactory); BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition( "bar-org.springframework.boot.context.properties.ConfigurationPropertiesBeanRegistrarTests$BarProperties"); - assertThat(beanDefinition) - .isExactlyInstanceOf(ConfigurationPropertiesBeanDefinition.class); + assertThat(beanDefinition).isExactlyInstanceOf(ConfigurationPropertiesBeanDefinition.class); } @Test - public void typeWithMultipleConstructorsShouldRegisterGenericBeanDefinition() - throws Exception { - this.registrar.registerBeanDefinitions( - getAnnotationMetadata(TestConfiguration.class), this.beanFactory); + public void typeWithMultipleConstructorsShouldRegisterGenericBeanDefinition() throws Exception { + this.registrar.registerBeanDefinitions(getAnnotationMetadata(TestConfiguration.class), this.beanFactory); BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition( "bing-org.springframework.boot.context.properties.ConfigurationPropertiesBeanRegistrarTests$BingProperties"); assertThat(beanDefinition).isExactlyInstanceOf(GenericBeanDefinition.class); @@ -80,38 +74,31 @@ public class ConfigurationPropertiesBeanRegistrarTests { @Test public void typeWithNoAnnotationShouldFail() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.registrar.registerBeanDefinitions( - getAnnotationMetadata(InvalidConfiguration.class), - this.beanFactory)) + .isThrownBy(() -> this.registrar + .registerBeanDefinitions(getAnnotationMetadata(InvalidConfiguration.class), this.beanFactory)) .withMessageContaining("No ConfigurationProperties annotation found") - .withMessageContaining( - ConfigurationPropertiesBeanRegistrar.class.getName()); + .withMessageContaining(ConfigurationPropertiesBeanRegistrar.class.getName()); } @Test - public void registrationWithDuplicatedTypeShouldRegisterSingleBeanDefinition() - throws IOException { + public void registrationWithDuplicatedTypeShouldRegisterSingleBeanDefinition() throws IOException { DefaultListableBeanFactory factory = spy(this.beanFactory); - this.registrar.registerBeanDefinitions( - getAnnotationMetadata(DuplicateConfiguration.class), factory); + this.registrar.registerBeanDefinitions(getAnnotationMetadata(DuplicateConfiguration.class), factory); verify(factory, times(1)).registerBeanDefinition(anyString(), any()); } @Test public void registrationWithNoTypeShouldNotRegisterAnything() throws IOException { DefaultListableBeanFactory factory = spy(this.beanFactory); - this.registrar.registerBeanDefinitions( - getAnnotationMetadata(EmptyConfiguration.class), factory); + this.registrar.registerBeanDefinitions(getAnnotationMetadata(EmptyConfiguration.class), factory); verifyZeroInteractions(factory); } private AnnotationMetadata getAnnotationMetadata(Class source) throws IOException { - return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()) - .getAnnotationMetadata(); + return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()).getAnnotationMetadata(); } - @EnableConfigurationProperties({ FooProperties.class, BarProperties.class, - BingProperties.class }) + @EnableConfigurationProperties({ FooProperties.class, BarProperties.class, BingProperties.class }) static class TestConfiguration { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java index 79528250711..610b043f2ec 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java @@ -52,13 +52,10 @@ public class ConfigurationPropertiesBindHandlerAdvisorTests { @Test public void loadWithoutConfigurationPropertiesBindHandlerAdvisor() { - load(WithoutConfigurationPropertiesBindHandlerAdvisor.class, - "foo.bar.default.content-type=text/plain", - "foo.bar.bindings.input.destination=d1", - "foo.bar.bindings.input.content-type=text/xml", + load(WithoutConfigurationPropertiesBindHandlerAdvisor.class, "foo.bar.default.content-type=text/plain", + "foo.bar.bindings.input.destination=d1", "foo.bar.bindings.input.content-type=text/xml", "foo.bar.bindings.output.destination=d2"); - BindingServiceProperties properties = this.context - .getBean(BindingServiceProperties.class); + BindingServiceProperties properties = this.context.getBean(BindingServiceProperties.class); BindingProperties input = properties.getBindings().get("input"); assertThat(input.getDestination()).isEqualTo("d1"); assertThat(input.getContentType()).isEqualTo("text/xml"); @@ -69,13 +66,10 @@ public class ConfigurationPropertiesBindHandlerAdvisorTests { @Test public void loadWithConfigurationPropertiesBindHandlerAdvisor() { - load(WithConfigurationPropertiesBindHandlerAdvisor.class, - "foo.bar.default.content-type=text/plain", - "foo.bar.bindings.input.destination=d1", - "foo.bar.bindings.input.content-type=text/xml", + load(WithConfigurationPropertiesBindHandlerAdvisor.class, "foo.bar.default.content-type=text/plain", + "foo.bar.bindings.input.destination=d1", "foo.bar.bindings.input.content-type=text/xml", "foo.bar.bindings.output.destination=d2"); - BindingServiceProperties properties = this.context - .getBean(BindingServiceProperties.class); + BindingServiceProperties properties = this.context.getBean(BindingServiceProperties.class); BindingProperties input = properties.getBindings().get("input"); assertThat(input.getDestination()).isEqualTo("d1"); assertThat(input.getContentType()).isEqualTo("text/xml"); @@ -84,16 +78,13 @@ public class ConfigurationPropertiesBindHandlerAdvisorTests { assertThat(output.getContentType()).isEqualTo("text/plain"); } - private AnnotationConfigApplicationContext load(Class configuration, - String... inlinedProperties) { + private AnnotationConfigApplicationContext load(Class configuration, String... inlinedProperties) { return load(new Class[] { configuration }, inlinedProperties); } - private AnnotationConfigApplicationContext load(Class[] configuration, - String... inlinedProperties) { + private AnnotationConfigApplicationContext load(Class[] configuration, String... inlinedProperties) { this.context.register(configuration); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - inlinedProperties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, inlinedProperties); this.context.refresh(); return this.context; } @@ -133,8 +124,7 @@ public class ConfigurationPropertiesBindHandlerAdvisorTests { } @Override - public Bindable onStart(ConfigurationPropertyName name, Bindable target, - BindContext context) { + public Bindable onStart(ConfigurationPropertyName name, Bindable target, BindContext context) { ConfigurationPropertyName defaultName = getDefaultName(name); if (defaultName != null) { BindResult result = context.getBinder().bind(defaultName, target); @@ -147,12 +137,10 @@ public class ConfigurationPropertiesBindHandlerAdvisorTests { } private ConfigurationPropertyName getDefaultName(ConfigurationPropertyName name) { - for (Map.Entry mapping : this.mappings - .entrySet()) { + for (Map.Entry mapping : this.mappings.entrySet()) { ConfigurationPropertyName from = mapping.getKey(); ConfigurationPropertyName to = mapping.getValue(); - if (name.getNumberOfElements() == from.getNumberOfElements() + 1 - && from.isParentOf(name)) { + if (name.getNumberOfElements() == from.getNumberOfElements() + 1 && from.isParentOf(name)) { return to; } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java index cc76cc8176b..67e7964dd23 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java @@ -50,10 +50,8 @@ public class ConfigurationPropertiesScanRegistrarTests { } @Test - public void registerBeanDefintionsShouldScanForConfigurationProperties() - throws IOException { - this.registrar.registerBeanDefinitions( - getAnnotationMetadata(ConfigurationPropertiesScanConfiguration.class), + public void registerBeanDefintionsShouldScanForConfigurationProperties() throws IOException { + this.registrar.registerBeanDefinitions(getAnnotationMetadata(ConfigurationPropertiesScanConfiguration.class), this.beanFactory); BeanDefinition bingDefinition = this.beanFactory.getBeanDefinition( "bing-org.springframework.boot.context.properties.scan.valid.ConfigurationPropertiesScanConfiguration$BingProperties"); @@ -63,8 +61,7 @@ public class ConfigurationPropertiesScanRegistrarTests { "bar-org.springframework.boot.context.properties.scan.valid.ConfigurationPropertiesScanConfiguration$BarProperties"); assertThat(bingDefinition).isExactlyInstanceOf(GenericBeanDefinition.class); assertThat(fooDefinition).isExactlyInstanceOf(GenericBeanDefinition.class); - assertThat(barDefinition) - .isExactlyInstanceOf(ConfigurationPropertiesBeanDefinition.class); + assertThat(barDefinition).isExactlyInstanceOf(ConfigurationPropertiesBeanDefinition.class); } @Test @@ -72,21 +69,18 @@ public class ConfigurationPropertiesScanRegistrarTests { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); this.registrar.registerBeanDefinitions( - getAnnotationMetadata( - ConfigurationPropertiesScanConfiguration.TestConfiguration.class), - beanFactory); + getAnnotationMetadata(ConfigurationPropertiesScanConfiguration.TestConfiguration.class), beanFactory); BeanDefinition fooDefinition = beanFactory.getBeanDefinition( "foo-org.springframework.boot.context.properties.scan.valid.ConfigurationPropertiesScanConfiguration$FooProperties"); assertThat(fooDefinition).isExactlyInstanceOf(GenericBeanDefinition.class); } @Test - public void scanWhenBasePackagesAndBasePackcageClassesProvidedShouldUseThat() - throws IOException { + public void scanWhenBasePackagesAndBasePackcageClassesProvidedShouldUseThat() throws IOException { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); - this.registrar.registerBeanDefinitions(getAnnotationMetadata( - ConfigurationPropertiesScanConfiguration.DifferentPackageConfiguration.class), + this.registrar.registerBeanDefinitions( + getAnnotationMetadata(ConfigurationPropertiesScanConfiguration.DifferentPackageConfiguration.class), beanFactory); assertThat(beanFactory.containsBeanDefinition( "foo-org.springframework.boot.context.properties.scan.valid.ConfigurationPropertiesScanConfiguration$FooProperties")) @@ -104,9 +98,8 @@ public class ConfigurationPropertiesScanRegistrarTests { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); assertThatExceptionOfType(InvalidConfigurationPropertiesException.class) - .isThrownBy(() -> this.registrar.registerBeanDefinitions( - getAnnotationMetadata(InvalidScanConfiguration.class), - beanFactory)) + .isThrownBy(() -> this.registrar + .registerBeanDefinitions(getAnnotationMetadata(InvalidScanConfiguration.class), beanFactory)) .withMessageContaining( "Found @Component and @ConfigurationProperties on org.springframework.boot.context.properties.scan.invalid.c.InvalidConfiguration$MyProperties."); } @@ -117,15 +110,13 @@ public class ConfigurationPropertiesScanRegistrarTests { beanFactory.setAllowBeanDefinitionOverriding(false); assertThatExceptionOfType(InvalidConfigurationPropertiesException.class) .isThrownBy(() -> this.registrar.registerBeanDefinitions( - getAnnotationMetadata(OtherInvalidScanConfiguration.class), - beanFactory)) + getAnnotationMetadata(OtherInvalidScanConfiguration.class), beanFactory)) .withMessageContaining( "Found @RestController and @ConfigurationProperties on org.springframework.boot.context.properties.scan.invalid.d.OtherInvalidConfiguration$MyControllerProperties."); } private AnnotationMetadata getAnnotationMetadata(Class source) throws IOException { - return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()) - .getAnnotationMetadata(); + return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()).getAnnotationMetadata(); } @ConfigurationPropertiesScan(basePackageClasses = InvalidConfiguration.class) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java index 7f478f26257..3e5a247dd51 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java @@ -74,8 +74,7 @@ public class ConfigurationPropertiesScanTests { DefaultResourceLoader resourceLoader = Mockito.mock(DefaultResourceLoader.class); this.context.setResourceLoader(resourceLoader); willCallRealMethod().given(resourceLoader).getClassLoader(); - given(resourceLoader.getResource("test")) - .willReturn(new ByteArrayResource("test".getBytes())); + given(resourceLoader.getResource("test")).willReturn(new ByteArrayResource("test".getBytes())); load(TestConfiguration.class); assertThat(this.context.containsBean( "resource-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyResourceProperties")) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java index ebdb9ac4c41..d0bf7c493c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java @@ -131,8 +131,7 @@ public class ConfigurationPropertiesTests { load(NestedConfiguration.class, "name=foo", "nested.name=bar"); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); - assertThat(this.context.getBean(NestedProperties.class).nested.name) - .isEqualTo("bar"); + assertThat(this.context.getBean(NestedProperties.class).nested.name).isEqualTo("bar"); } @Test @@ -150,16 +149,14 @@ public class ConfigurationPropertiesTests { load(NestedConfiguration.class); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); - assertThat(this.context.getBean(NestedProperties.class).nested.name) - .isEqualTo("bar"); + assertThat(this.context.getBean(NestedProperties.class).nested.name).isEqualTo("bar"); } @Test public void loadWhenHasIgnoreUnknownFieldsFalseAndNoUnknownFieldsShouldBind() { removeSystemProperties(); load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo"); - IgnoreUnknownFieldsFalseProperties bean = this.context - .getBean(IgnoreUnknownFieldsFalseProperties.class); + IgnoreUnknownFieldsFalseProperties bean = this.context.getBean(IgnoreUnknownFieldsFalseProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @@ -167,16 +164,14 @@ public class ConfigurationPropertiesTests { public void loadWhenHasIgnoreUnknownFieldsFalseAndUnknownFieldsShouldFail() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, - "name=foo", "bar=baz")) + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) .withCauseInstanceOf(BindException.class); } @Test public void loadWhenHasIgnoreInvalidFieldsTrueAndInvalidFieldsShouldBind() { load(IgnoreInvalidFieldsFalseProperties.class, "com.example.bar=spam"); - IgnoreInvalidFieldsFalseProperties bean = this.context - .getBean(IgnoreInvalidFieldsFalseProperties.class); + IgnoreInvalidFieldsFalseProperties bean = this.context.getBean(IgnoreInvalidFieldsFalseProperties.class); assertThat(bean.getBar()).isEqualTo(0); } @@ -190,8 +185,7 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenPropertiesHaveAnnotationOnBaseClassShouldBind() { load(AnnotationOnBaseClassConfiguration.class, "name=foo"); - AnnotationOnBaseClassProperties bean = this.context - .getBean(AnnotationOnBaseClassProperties.class); + AnnotationOnBaseClassProperties bean = this.context.getBean(AnnotationOnBaseClassProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @@ -223,24 +217,20 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingWithoutAndAnnotationShouldFail() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> load(WithoutAndAnnotationConfiguration.class, "name:foo")) + assertThatIllegalArgumentException().isThrownBy(() -> load(WithoutAndAnnotationConfiguration.class, "name:foo")) .withMessageContaining("No ConfigurationProperties annotation found"); } @Test public void loadWhenBindingWithoutAnnotationValueShouldBind() { load(WithoutAnnotationValueConfiguration.class, "name=foo"); - WithoutAnnotationValueProperties bean = this.context - .getBean(WithoutAnnotationValueProperties.class); + WithoutAnnotationValueProperties bean = this.context.getBean(WithoutAnnotationValueProperties.class); assertThat(bean.name).isEqualTo("foo"); } @Test public void loadWhenBindingWithDefaultsInXmlShouldBind() { - load(new Class[] { BasicConfiguration.class, - DefaultsInXmlConfiguration.class }); + load(new Class[] { BasicConfiguration.class, DefaultsInXmlConfiguration.class }); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("bar"); } @@ -254,39 +244,32 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingTwoBeansShouldBind() { - load(new Class[] { WithoutAnnotationValueConfiguration.class, - BasicConfiguration.class }); + load(new Class[] { WithoutAnnotationValueConfiguration.class, BasicConfiguration.class }); assertThat(this.context.getBean(BasicProperties.class)).isNotNull(); - assertThat(this.context.getBean(WithoutAnnotationValueProperties.class)) - .isNotNull(); + assertThat(this.context.getBean(WithoutAnnotationValueProperties.class)).isNotNull(); } @Test public void loadWhenBindingWithParentContextShouldBind() { - AnnotationConfigApplicationContext parent = load(BasicConfiguration.class, - "name=parent"); + AnnotationConfigApplicationContext parent = load(BasicConfiguration.class, "name=parent"); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); - load(new Class[] { BasicConfiguration.class, BasicPropertiesConsumer.class }, - "name=child"); + load(new Class[] { BasicConfiguration.class, BasicPropertiesConsumer.class }, "name=child"); assertThat(this.context.getBean(BasicProperties.class)).isNotNull(); assertThat(parent.getBean(BasicProperties.class)).isNotNull(); - assertThat(this.context.getBean(BasicPropertiesConsumer.class).getName()) - .isEqualTo("parent"); + assertThat(this.context.getBean(BasicPropertiesConsumer.class).getName()).isEqualTo("parent"); parent.close(); } @Test public void loadWhenBindingOnlyParentContextShouldBind() { - AnnotationConfigApplicationContext parent = load(BasicConfiguration.class, - "name=foo"); + AnnotationConfigApplicationContext parent = load(BasicConfiguration.class, "name=foo"); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); load(BasicPropertiesConsumer.class); assertThat(this.context.getBeanNamesForType(BasicProperties.class)).isEmpty(); assertThat(parent.getBeanNamesForType(BasicProperties.class)).hasSize(1); - assertThat(this.context.getBean(BasicPropertiesConsumer.class).getName()) - .isEqualTo("foo"); + assertThat(this.context.getBean(BasicPropertiesConsumer.class).getName()).isEqualTo("foo"); } @Test @@ -298,20 +281,18 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenPrefixedPropertiesDeclaredAsAnnotationValueShouldBind() { - load(PrefixPropertiesDeclaredAsAnnotationValueConfiguration.class, - "spring.foo.name=foo"); - PrefixProperties bean = this.context.getBean( - "spring.foo-" + PrefixProperties.class.getName(), PrefixProperties.class); + load(PrefixPropertiesDeclaredAsAnnotationValueConfiguration.class, "spring.foo.name=foo"); + PrefixProperties bean = this.context.getBean("spring.foo-" + PrefixProperties.class.getName(), + PrefixProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test public void loadWhenMultiplePrefixedPropertiesDeclaredAsAnnotationValueShouldBind() { - load(MultiplePrefixPropertiesDeclaredAsAnnotationValueConfiguration.class, - "spring.foo.name=foo", "spring.bar.name=bar"); + load(MultiplePrefixPropertiesDeclaredAsAnnotationValueConfiguration.class, "spring.foo.name=foo", + "spring.bar.name=bar"); PrefixProperties bean1 = this.context.getBean(PrefixProperties.class); - AnotherPrefixProperties bean2 = this.context - .getBean(AnotherPrefixProperties.class); + AnotherPrefixProperties bean2 = this.context.getBean(AnotherPrefixProperties.class); assertThat(((BasicProperties) bean1).name).isEqualTo("foo"); assertThat(((BasicProperties) bean2).name).isEqualTo("bar"); } @@ -320,14 +301,12 @@ public class ConfigurationPropertiesTests { public void loadWhenBindingToMapKeyWithPeriodShouldBind() { load(MapProperties.class, "mymap.key1.key2:value12", "mymap.key3:value3"); MapProperties bean = this.context.getBean(MapProperties.class); - assertThat(bean.mymap).containsOnly(entry("key3", "value3"), - entry("key1.key2", "value12")); + assertThat(bean.mymap).containsOnly(entry("key3", "value3"), entry("key1.key2", "value12")); } @Test public void loadWhenPrefixedPropertiesAreReplacedOnBeanMethodShouldBind() { - load(PrefixedPropertiesReplacedOnBeanMethodConfiguration.class, - "external.name=bar", "spam.name=foo"); + load(PrefixedPropertiesReplacedOnBeanMethodConfiguration.class, "external.name=bar", "spam.name=foo"); PrefixProperties bean = this.context.getBean(PrefixProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @@ -342,8 +321,7 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingToValidatedImplementationOfInterfaceShouldBind() { load(ValidatedImplementationConfiguration.class, "test.foo=bar"); - ValidatedImplementationProperties bean = this.context - .getBean(ValidatedImplementationProperties.class); + ValidatedImplementationProperties bean = this.context.getBean(ValidatedImplementationProperties.class); assertThat(bean.getFoo()).isEqualTo("bar"); } @@ -357,10 +335,8 @@ public class ConfigurationPropertiesTests { @Test public void loadWithPropertyPlaceholderShouldNotAlterPropertySourceOrder() { - load(WithPropertyPlaceholderWithLocalPropertiesValueConfiguration.class, - "com.example.bar=a"); - SimplePrefixedProperties bean = this.context - .getBean(SimplePrefixedProperties.class); + load(WithPropertyPlaceholderWithLocalPropertiesValueConfiguration.class, "com.example.bar=a"); + SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getBar()).isEqualTo("a"); } @@ -371,8 +347,7 @@ public class ConfigurationPropertiesTests { this.context.setEnvironment(environment); this.context.register(WithPostConstructConfiguration.class); this.context.refresh(); - WithPostConstructConfiguration bean = this.context - .getBean(WithPostConstructConfiguration.class); + WithPostConstructConfiguration bean = this.context.getBean(WithPostConstructConfiguration.class); assertThat(bean.initialized).isTrue(); } @@ -383,8 +358,7 @@ public class ConfigurationPropertiesTests { @Override protected void onRefresh() throws BeansException { - assertThat(WithFactoryBeanConfiguration.factoryBeanInitialized) - .as("Initialized too early").isFalse(); + assertThat(WithFactoryBeanConfiguration.factoryBeanInitialized).as("Initialized too early").isFalse(); super.onRefresh(); } @@ -395,8 +369,7 @@ public class ConfigurationPropertiesTests { beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); this.context.registerBeanDefinition("test", beanDefinition); this.context.refresh(); - assertThat(WithFactoryBeanConfiguration.factoryBeanInitialized) - .as("Not Initialized").isTrue(); + assertThat(WithFactoryBeanConfiguration.factoryBeanInitialized).as("Not Initialized").isTrue(); } @Test @@ -430,17 +403,15 @@ public class ConfigurationPropertiesTests { @Test public void loadShouldBindToCharArray() { load(WithCharArrayProperties.class, "test.chars=word"); - WithCharArrayProperties bean = this.context - .getBean(WithCharArrayProperties.class); + WithCharArrayProperties bean = this.context.getBean(WithCharArrayProperties.class); assertThat(bean.getChars()).isEqualTo("word".toCharArray()); } @Test public void loadWhenUsingRelaxedFormsAndOverrideShouldBind() { - load(WithRelaxedNamesProperties.class, "test.FOO_BAR=test1", "test.FOO_BAR=test2", - "test.BAR-B-A-Z=testa", "test.BAR-B-A-Z=testb"); - WithRelaxedNamesProperties bean = this.context - .getBean(WithRelaxedNamesProperties.class); + load(WithRelaxedNamesProperties.class, "test.FOO_BAR=test1", "test.FOO_BAR=test2", "test.BAR-B-A-Z=testa", + "test.BAR-B-A-Z=testb"); + WithRelaxedNamesProperties bean = this.context.getBean(WithRelaxedNamesProperties.class); assertThat(bean.getFooBar()).isEqualTo("test2"); assertThat(bean.getBarBAZ()).isEqualTo("testb"); } @@ -455,44 +426,37 @@ public class ConfigurationPropertiesTests { @Test public void loadShouldBindToMapWithNumericKey() { load(MapWithNumericKeyProperties.class, "sample.properties.1.name=One"); - MapWithNumericKeyProperties bean = this.context - .getBean(MapWithNumericKeyProperties.class); + MapWithNumericKeyProperties bean = this.context.getBean(MapWithNumericKeyProperties.class); assertThat(bean.getProperties().get("1").name).isEqualTo("One"); } @Test public void loadWhenUsingSystemPropertiesShouldBindToMap() { - this.context.getEnvironment().getPropertySources() - .addLast(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + this.context.getEnvironment().getPropertySources().addLast( + new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("TEST_MAP_FOO_BAR", "baz"))); load(WithComplexMapProperties.class); - WithComplexMapProperties bean = this.context - .getBean(WithComplexMapProperties.class); + WithComplexMapProperties bean = this.context.getBean(WithComplexMapProperties.class); assertThat(bean.getMap()).containsOnlyKeys("foo"); assertThat(bean.getMap().get("foo")).containsOnly(entry("bar", "baz")); } @Test public void loadWhenDotsInSystemEnvironmentPropertiesShouldBind() { - this.context.getEnvironment().getPropertySources() - .addLast(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + this.context.getEnvironment().getPropertySources().addLast( + new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("com.example.bar", "baz"))); load(SimplePrefixedProperties.class); - SimplePrefixedProperties bean = this.context - .getBean(SimplePrefixedProperties.class); + SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getBar()).isEqualTo("baz"); } @Test public void loadWhenOverridingPropertiesShouldBind() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); - sources.addFirst(new SystemEnvironmentPropertySource("system", - Collections.singletonMap("SPRING_FOO_NAME", "Jane"))); - sources.addLast(new MapPropertySource("test", - Collections.singletonMap("spring.foo.name", "John"))); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); + sources.addFirst( + new SystemEnvironmentPropertySource("system", Collections.singletonMap("SPRING_FOO_NAME", "Jane"))); + sources.addLast(new MapPropertySource("test", Collections.singletonMap("spring.foo.name", "John"))); load(PrefixConfiguration.class); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("Jane"); @@ -501,23 +465,21 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy( - () -> load(ValidatedJsr303Configuration.class, "description=")) + .isThrownBy(() -> load(ValidatedJsr303Configuration.class, "description=")) .withCauseInstanceOf(BindException.class); } @Test public void loadValidatedOnBeanMethodAndJsr303ConstraintDoesNotMatchShouldFail() { - assertThatExceptionOfType(ConfigurationPropertiesBindException.class).isThrownBy( - () -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) + assertThatExceptionOfType(ConfigurationPropertiesBindException.class) + .isThrownBy(() -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) .withCauseInstanceOf(BindException.class); } @Test public void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, - "properties.description=")) + .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, "properties.description=")) .withCauseInstanceOf(BindException.class); } @@ -531,62 +493,52 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenJsr303ConstraintMatchesShouldBind() { load(ValidatedJsr303Configuration.class, "description=foo"); - ValidatedJsr303Properties bean = this.context - .getBean(ValidatedJsr303Properties.class); + ValidatedJsr303Properties bean = this.context.getBean(ValidatedJsr303Properties.class); assertThat(bean.getDescription()).isEqualTo("foo"); } @Test public void loadWhenJsr303ConstraintDoesNotMatchAndNotValidatedAnnotationShouldBind() { load(NonValidatedJsr303Configuration.class, "name=foo"); - NonValidatedJsr303Properties bean = this.context - .getBean(NonValidatedJsr303Properties.class); + NonValidatedJsr303Properties bean = this.context.getBean(NonValidatedJsr303Properties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test public void loadWhenHasMultiplePropertySourcesPlaceholderConfigurerShouldLogWarning() { load(MultiplePropertySourcesPlaceholderConfigurerConfiguration.class); - assertThat(this.output.toString()).contains( - "Multiple PropertySourcesPlaceholderConfigurer beans registered"); + assertThat(this.output.toString()).contains("Multiple PropertySourcesPlaceholderConfigurer beans registered"); } @Test public void loadWhenOverridingPropertiesWithPlaceholderResolutionInEnvironmentShouldBindWithOverride() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); - sources.addFirst(new SystemEnvironmentPropertySource("system", - Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); + sources.addFirst( + new SystemEnvironmentPropertySource("system", Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); Map source = new HashMap<>(); source.put("com.example.bar", 5); source.put("com.example.foo", "${com.example.bar}"); sources.addLast(new MapPropertySource("test", source)); load(SimplePrefixedProperties.class); - SimplePrefixedProperties bean = this.context - .getBean(SimplePrefixedProperties.class); + SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getFoo()).isEqualTo(10); } @Test public void loadWhenHasUnboundElementsFromSystemEnvironmentShouldNotThrowException() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); - sources.addFirst(new MapPropertySource("test", - Collections.singletonMap("com.example.foo", 5))); - sources.addLast(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); + sources.addFirst(new MapPropertySource("test", Collections.singletonMap("com.example.foo", 5))); + sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("COM_EXAMPLE_OTHER", "10"))); load(SimplePrefixedProperties.class); - SimplePrefixedProperties bean = this.context - .getBean(SimplePrefixedProperties.class); + SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getFoo()).isEqualTo(5); } @Test public void loadShouldSupportRebindableConfigurationProperties() { // gh-9160 - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new LinkedHashMap<>(); source.put("example.one", "foo"); sources.addFirst(new MapPropertySource("test-source", source)); @@ -595,8 +547,7 @@ public class ConfigurationPropertiesTests { PrototypeBean first = this.context.getBean(PrototypeBean.class); assertThat(first.getOne()).isEqualTo("foo"); source.put("example.one", "bar"); - sources.addFirst(new MapPropertySource("extra", - Collections.singletonMap("example.two", "baz"))); + sources.addFirst(new MapPropertySource("extra", Collections.singletonMap("example.two", "baz"))); PrototypeBean second = this.context.getBean(PrototypeBean.class); assertThat(second.getOne()).isEqualTo("bar"); assertThat(second.getTwo()).isEqualTo("baz"); @@ -604,8 +555,7 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenHasPropertySourcesPlaceholderConfigurerShouldSupportRebindableConfigurationProperties() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new LinkedHashMap<>(); source.put("example.one", "foo"); sources.addFirst(new MapPropertySource("test-source", source)); @@ -615,8 +565,7 @@ public class ConfigurationPropertiesTests { PrototypeBean first = this.context.getBean(PrototypeBean.class); assertThat(first.getOne()).isEqualTo("foo"); source.put("example.one", "bar"); - sources.addFirst(new MapPropertySource("extra", - Collections.singletonMap("example.two", "baz"))); + sources.addFirst(new MapPropertySource("extra", Collections.singletonMap("example.two", "baz"))); PrototypeBean second = this.context.getBean(PrototypeBean.class); assertThat(second.getOne()).isEqualTo("bar"); assertThat(second.getTwo()).isEqualTo("baz"); @@ -625,16 +574,13 @@ public class ConfigurationPropertiesTests { @Test public void customProtocolResolverIsInvoked() { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.resource=application.properties"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.resource=application.properties"); ProtocolResolver protocolResolver = mock(ProtocolResolver.class); - given(protocolResolver.resolve(anyString(), any(ResourceLoader.class))) - .willReturn(null); + given(protocolResolver.resolve(anyString(), any(ResourceLoader.class))).willReturn(null); this.context.addProtocolResolver(protocolResolver); this.context.register(PropertiesWithResource.class); this.context.refresh(); - verify(protocolResolver).resolve(eq("application.properties"), - any(ResourceLoader.class)); + verify(protocolResolver).resolve(eq("application.properties"), any(ResourceLoader.class)); } @Test @@ -645,13 +591,11 @@ public class ConfigurationPropertiesTests { this.context.addProtocolResolver(new TestProtocolResolver()); this.context.register(PropertiesWithResource.class); this.context.refresh(); - Resource resource = this.context.getBean(PropertiesWithResource.class) - .getResource(); + Resource resource = this.context.getBean(PropertiesWithResource.class).getResource(); assertThat(resource).isNotNull(); assertThat(resource).isInstanceOf(ClassPathResource.class); assertThat(resource.exists()).isTrue(); - assertThat(((ClassPathResource) resource).getPath()) - .isEqualTo("application.properties"); + assertThat(((ClassPathResource) resource).getPath()).isEqualTo("application.properties"); } @Test @@ -665,15 +609,14 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> prepareConverterContext( - NonQualifiedConverterConfiguration.class, PersonProperties.class)) + .isThrownBy( + () -> prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.class)) .withCauseInstanceOf(BindException.class); } @Test public void loadShouldUseGenericConfigurationConverter() { - prepareConverterContext(GenericConverterConfiguration.class, - PersonProperties.class); + prepareConverterContext(GenericConverterConfiguration.class, PersonProperties.class); Person person = this.context.getBean(PersonProperties.class).getPerson(); assertThat(person.firstName).isEqualTo("John"); assertThat(person.lastName).isEqualTo("Smith"); @@ -681,10 +624,8 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> prepareConverterContext( - NonQualifiedGenericConverterConfiguration.class, - PersonProperties.class)) + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + () -> prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, PersonProperties.class)) .withCauseInstanceOf(BindException.class); } @@ -702,12 +643,10 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { - assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(WithCustomValidatorConfiguration.class)) + assertThatExceptionOfType(Exception.class).isThrownBy(() -> load(WithCustomValidatorConfiguration.class)) .satisfies((ex) -> { assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); }); } @@ -721,19 +660,16 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenConfigurationPropertiesIsAlsoValidatorShouldApplyValidator() { - assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ValidatorProperties.class)).satisfies((ex) -> { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); - }); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> load(ValidatorProperties.class)).satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test public void loadWhenSetterThrowsValidationExceptionShouldFail() { - assertThatExceptionOfType(BeanCreationException.class).isThrownBy( - () -> load(WithSetterThatThrowsValidationExceptionProperties.class, - "test.foo=spam")) + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam")) .withCauseInstanceOf(BindException.class); } @@ -741,8 +677,7 @@ public class ConfigurationPropertiesTests { public void loadWhenFailsShouldIncludeAnnotationDetails() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, - "name=foo", "bar=baz")) + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) .withMessageContaining("Could not bind properties to " + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); @@ -750,8 +685,7 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenHasCustomPropertyEditorShouldBind() { - this.context.getBeanFactory().registerCustomEditor(Person.class, - PersonPropertyEditor.class); + this.context.getBeanFactory().registerCustomEditor(Person.class, PersonPropertyEditor.class); load(PersonProperties.class, "test.person=boot,spring"); PersonProperties bean = this.context.getBean(PersonProperties.class); assertThat(bean.getPerson().firstName).isEqualTo("spring"); @@ -762,8 +696,7 @@ public class ConfigurationPropertiesTests { public void loadWhenBindingToListOfGenericClassShouldBind() { // gh-12166 load(ListOfGenericClassProperties.class, "test.list=java.lang.RuntimeException"); - ListOfGenericClassProperties bean = this.context - .getBean(ListOfGenericClassProperties.class); + ListOfGenericClassProperties bean = this.context.getBean(ListOfGenericClassProperties.class); assertThat(bean.getList()).containsExactly(RuntimeException.class); } @@ -790,16 +723,14 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenConfigurationPropertiesContainsMapWithPositiveAndNegativeIntegerKeys() { // gh-14136 - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new HashMap<>(); source.put("test.map.x.[-1].a", "baz"); source.put("test.map.x.1.a", "bar"); source.put("test.map.x.1.b", 1); sources.addLast(new MapPropertySource("test", source)); load(WithIntegerMapProperties.class); - WithIntegerMapProperties bean = this.context - .getBean(WithIntegerMapProperties.class); + WithIntegerMapProperties bean = this.context.getBean(WithIntegerMapProperties.class); Map x = bean.getMap().get("x"); assertThat(x.get(-1).getA()).isEqualTo("baz"); assertThat(x.get(-1).getB()).isEqualTo(0); @@ -817,15 +748,13 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingToConstructorParametersShouldBind() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new HashMap<>(); source.put("test.foo", "baz"); source.put("test.bar", "5"); sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterConfiguration.class); - ConstructorParameterProperties bean = this.context - .getBean(ConstructorParameterProperties.class); + ConstructorParameterProperties bean = this.context.getBean(ConstructorParameterProperties.class); assertThat(bean.getFoo()).isEqualTo("baz"); assertThat(bean.getBar()).isEqualTo(5); } @@ -833,8 +762,7 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingToConstructorParametersWithDefaultValuesShouldBind() { load(ConstructorParameterConfiguration.class); - ConstructorParameterProperties bean = this.context - .getBean(ConstructorParameterProperties.class); + ConstructorParameterProperties bean = this.context.getBean(ConstructorParameterProperties.class); assertThat(bean.getFoo()).isEqualTo("hello"); assertThat(bean.getBar()).isEqualTo(0); } @@ -842,11 +770,9 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingToConstructorParametersShouldValidate() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)) - .satisfies((ex) -> { + .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)).satisfies((ex) -> { assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); }); } @@ -856,21 +782,18 @@ public class ConfigurationPropertiesTests { BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("test"); bean.name = "override"; - this.context.getBean(ConfigurationPropertiesBindingPostProcessor.class) - .postProcessBeforeInitialization(bean, "does-not-exist"); + this.context.getBean(ConfigurationPropertiesBindingPostProcessor.class).postProcessBeforeInitialization(bean, + "does-not-exist"); assertThat(bean.name).isEqualTo("test"); } - private AnnotationConfigApplicationContext load(Class configuration, - String... inlinedProperties) { + private AnnotationConfigApplicationContext load(Class configuration, String... inlinedProperties) { return load(new Class[] { configuration }, inlinedProperties); } - private AnnotationConfigApplicationContext load(Class[] configuration, - String... inlinedProperties) { + private AnnotationConfigApplicationContext load(Class[] configuration, String... inlinedProperties) { this.context.register(configuration); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - inlinedProperties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, inlinedProperties); this.context.refresh(); return this.context; } @@ -880,8 +803,7 @@ public class ConfigurationPropertiesTests { * environment specific. */ private void removeSystemProperties() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); sources.remove("systemProperties"); sources.remove("systemEnvironment"); } @@ -993,8 +915,7 @@ public class ConfigurationPropertiesTests { } @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties({ PrefixProperties.class, - AnotherPrefixProperties.class }) + @EnableConfigurationProperties({ PrefixProperties.class, AnotherPrefixProperties.class }) static class MultiplePrefixPropertiesDeclaredAsAnnotationValueConfiguration { } @@ -1427,8 +1348,7 @@ public class ConfigurationPropertiesTests { static class ValidatedValidNestedJsr303Properties { @Valid - private List properties = Collections - .singletonList(new Jsr303Properties()); + private List properties = Collections.singletonList(new Jsr303Properties()); public List getProperties() { return this.properties; @@ -1494,8 +1414,7 @@ public class ConfigurationPropertiesTests { @ConfigurationProperties("test") @Validated - static class ValidatedImplementationProperties - implements InterfaceForValidatedImplementation { + static class ValidatedImplementationProperties implements InterfaceForValidatedImplementation { @NotNull private String foo; @@ -1924,8 +1843,7 @@ public class ConfigurationPropertiesTests { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { String[] content = StringUtils.split((String) source, " "); return new Person(content[0], content[1]); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java index f6e00ec453e..0861b238808 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java @@ -49,8 +49,7 @@ public class PropertyMapperTests { @Test public void fromValueAsIntShouldAdaptValue() { - Integer result = this.map.from("123").asInt(Long::valueOf) - .toInstance(Integer::valueOf); + Integer result = this.map.from("123").asInt(Long::valueOf).toInstance(Integer::valueOf); assertThat(result).isEqualTo(123); } @@ -61,15 +60,13 @@ public class PropertyMapperTests { @Test public void fromWhenSupplierIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.map.from((Supplier) null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.map.from((Supplier) null)) .withMessageContaining("Supplier must not be null"); } @Test public void toWhenConsumerIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.map.from(() -> "").to(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").to(null)) .withMessageContaining("Consumer must not be null"); } @@ -83,15 +80,13 @@ public class PropertyMapperTests { @Test public void asIntShouldAdaptSupplier() { - Integer result = this.map.from(() -> "123").asInt(Long::valueOf) - .toInstance(Integer::valueOf); + Integer result = this.map.from(() -> "123").asInt(Long::valueOf).toInstance(Integer::valueOf); assertThat(result).isEqualTo(123); } @Test public void asWhenAdapterIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.map.from(() -> "").as(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").as(null)) .withMessageContaining("Adapter must not be null"); } @@ -165,8 +160,7 @@ public class PropertyMapperTests { @Test public void whenInstanceOfWhenValueIsTargetTypeShouldMatch() { - Long result = this.map.from(123L).whenInstanceOf(Long.class) - .toInstance((value) -> value + 1); + Long result = this.map.from(123L).whenInstanceOf(Long.class).toInstance((value) -> value + 1); assertThat(result).isEqualTo(124L); } @@ -190,8 +184,8 @@ public class PropertyMapperTests { @Test public void whenWhenCombinedWithAsUsesSourceValue() { Count source = new Count<>(() -> "123"); - Long result = this.map.from(source).when("123"::equals).as(Integer::valueOf) - .when((v) -> v == 123).as(Integer::longValue).toInstance(Long::valueOf); + Long result = this.map.from(source).when("123"::equals).as(Integer::valueOf).when((v) -> v == 123) + .as(Integer::longValue).toInstance(Long::valueOf); assertThat(result).isEqualTo(123); assertThat(source.getCount()).isOne(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java index 794188450f9..9bb5df3e055 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java @@ -47,8 +47,7 @@ import static org.mockito.Mockito.mock; */ public class ArrayBinderTests { - private static final Bindable> INTEGER_LIST = Bindable - .listOf(Integer.class); + private static final Bindable> INTEGER_LIST = Bindable.listOf(Integer.class); private static final Bindable INTEGER_ARRAY = Bindable.of(Integer[].class); @@ -78,10 +77,10 @@ public class ArrayBinderTests { BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); this.binder.bind("foo", INTEGER_LIST, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), - eq(Bindable.of(Integer.class)), any(), eq(1)); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), - eq(INTEGER_LIST), any(), isA(List.class)); + inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), + any(), eq(1)); + inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(INTEGER_LIST), any(), + isA(List.class)); } @Test @@ -145,11 +144,10 @@ public class ArrayBinderTests { source.put("foo[1]", "1"); source.put("foo[3]", "3"); this.sources.add(source); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", INTEGER_ARRAY)) + assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", INTEGER_ARRAY)) .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex - .getCause()).getUnboundProperties(); + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); assertThat(unbound.size()).isEqualTo(1); ConfigurationProperty property = unbound.iterator().next(); assertThat(property.getName().toString()).isEqualTo("foo[3]"); @@ -192,8 +190,7 @@ public class ArrayBinderTests { Integer[] existing = new Integer[2]; existing[0] = 1000; existing[1] = 1001; - Integer[] result = this.binder - .bind("foo", INTEGER_ARRAY.withExistingValue(existing)).get(); + Integer[] result = this.binder.bind("foo", INTEGER_ARRAY.withExistingValue(existing)).get(); assertThat(result).containsExactly(1); } @@ -211,10 +208,10 @@ public class ArrayBinderTests { Bindable target = INTEGER_ARRAY; this.binder.bind("foo", target, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), - eq(Bindable.of(Integer.class)), any(), eq(1)); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), - eq(target), any(), isA(Integer[].class)); + inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), + any(), eq(1)); + inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), + isA(Integer[].class)); } @Test @@ -280,8 +277,8 @@ public class ArrayBinderTests { source.put("foo[0]", "java.lang.RuntimeException"); source.put("foo[1]", "java.lang.IllegalStateException"); this.sources.add(source); - assertThat(this.binder.bind("foo", Bindable.of(Class[].class)).get()) - .containsExactly(RuntimeException.class, IllegalStateException.class); + assertThat(this.binder.bind("foo", Bindable.of(Class[].class)).get()).containsExactly(RuntimeException.class, + IllegalStateException.class); } @Test @@ -290,8 +287,8 @@ public class ArrayBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "java.lang.RuntimeException,java.lang.IllegalStateException"); this.sources.add(source); - assertThat(this.binder.bind("foo", Bindable.of(Class[].class)).get()) - .containsExactly(RuntimeException.class, IllegalStateException.class); + assertThat(this.binder.bind("foo", Bindable.of(Class[].class)).get()).containsExactly(RuntimeException.class, + IllegalStateException.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java index 31aa9cc98d5..f82d5be1b3b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,19 +42,18 @@ public class BackCompatibilityBinderIntegrationTests { StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("FOO_ZK_NODES", "foo")); environment.getPropertySources().addFirst(propertySource); - ExampleCamelCaseBean result = Binder.get(environment) - .bind("foo", Bindable.of(ExampleCamelCaseBean.class)).get(); + ExampleCamelCaseBean result = Binder.get(environment).bind("foo", Bindable.of(ExampleCamelCaseBean.class)) + .get(); assertThat(result.getZkNodes()).isEqualTo("foo"); } @Test public void bindWhenUsingSystemEnvironmentToOverride() { MockEnvironment environment = new MockEnvironment(); - SystemEnvironmentPropertySource propertySource = new SystemEnvironmentPropertySource( - "override", Collections.singletonMap("foo.password", "test")); + SystemEnvironmentPropertySource propertySource = new SystemEnvironmentPropertySource("override", + Collections.singletonMap("foo.password", "test")); environment.getPropertySources().addFirst(propertySource); - PasswordProperties result = Binder.get(environment) - .bind("foo", Bindable.of(PasswordProperties.class)).get(); + PasswordProperties result = Binder.get(environment).bind("foo", Bindable.of(PasswordProperties.class)).get(); assertThat(result.getPassword()).isEqualTo("test"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java index 09ddc87383b..c71e941772b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ public class BindConverterTests { @Test public void createWhenConversionServiceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> BindConverter.get(null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> BindConverter.get(null, null)) .withMessageContaining("ConversionService must not be null"); } @@ -72,94 +71,78 @@ public class BindConverterTests { @Test public void createWhenPropertyEditorInitializerIsNotNullShouldUseToInitialize() { - BindConverter.get(ApplicationConversionService.getSharedInstance(), - this.propertyEditorInitializer); + BindConverter.get(ApplicationConversionService.getSharedInstance(), this.propertyEditorInitializer); verify(this.propertyEditorInitializer).accept(any(PropertyEditorRegistry.class)); } @Test public void canConvertWhenHasDefaultEditorShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); - assertThat(bindConverter.canConvert("java.lang.RuntimeException", - ResolvableType.forClass(Class.class))).isTrue(); + assertThat(bindConverter.canConvert("java.lang.RuntimeException", ResolvableType.forClass(Class.class))) + .isTrue(); } @Test public void canConvertWhenHasCustomEditorShouldReturnTrue() { - BindConverter bindConverter = getPropertyEditorOnlyBindConverter( - this::registerSampleTypeEditor); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClass(SampleType.class))).isTrue(); + BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); + assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType.class))).isTrue(); } @Test public void canConvertWhenHasEditorByConventionShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClass(ConventionType.class))).isTrue(); + assertThat(bindConverter.canConvert("test", ResolvableType.forClass(ConventionType.class))).isTrue(); } @Test public void canConvertWhenHasEditorForCollectionElementShouldReturnTrue() { - BindConverter bindConverter = getPropertyEditorOnlyBindConverter( - this::registerSampleTypeEditor); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClassWithGenerics(List.class, SampleType.class))) - .isTrue(); + BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); + assertThat(bindConverter.canConvert("test", ResolvableType.forClassWithGenerics(List.class, SampleType.class))) + .isTrue(); } @Test public void canConvertWhenHasEditorForArrayElementShouldReturnTrue() { - BindConverter bindConverter = getPropertyEditorOnlyBindConverter( - this::registerSampleTypeEditor); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClass(SampleType[].class))).isTrue(); + BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); + assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType[].class))).isTrue(); } @Test public void canConvertWhenConversionServiceCanConvertShouldReturnTrue() { BindConverter bindConverter = getBindConverter(new SampleTypeConverter()); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClass(SampleType.class))).isTrue(); + assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType.class))).isTrue(); } @Test public void canConvertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldReturnFalse() { - BindConverter bindConverter = BindConverter - .get(ApplicationConversionService.getSharedInstance(), null); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClass(SampleType.class))).isFalse(); + BindConverter bindConverter = BindConverter.get(ApplicationConversionService.getSharedInstance(), null); + assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType.class))).isFalse(); } @Test public void convertWhenHasDefaultEditorShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); - Class converted = bindConverter.convert("java.lang.RuntimeException", - ResolvableType.forClass(Class.class)); + Class converted = bindConverter.convert("java.lang.RuntimeException", ResolvableType.forClass(Class.class)); assertThat(converted).isEqualTo(RuntimeException.class); } @Test public void convertWhenHasCustomEditorShouldConvert() { - BindConverter bindConverter = getPropertyEditorOnlyBindConverter( - this::registerSampleTypeEditor); - SampleType converted = bindConverter.convert("test", - ResolvableType.forClass(SampleType.class)); + BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); + SampleType converted = bindConverter.convert("test", ResolvableType.forClass(SampleType.class)); assertThat(converted.getText()).isEqualTo("test"); } @Test public void convertWhenHasEditorByConventionShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); - ConventionType converted = bindConverter.convert("test", - ResolvableType.forClass(ConventionType.class)); + ConventionType converted = bindConverter.convert("test", ResolvableType.forClass(ConventionType.class)); assertThat(converted.getText()).isEqualTo("test"); } @Test public void convertWhenHasEditorForCollectionElementShouldConvert() { - BindConverter bindConverter = getPropertyEditorOnlyBindConverter( - this::registerSampleTypeEditor); + BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); List converted = bindConverter.convert("test", ResolvableType.forClassWithGenerics(List.class, SampleType.class)); assertThat(converted).hasSize(1); @@ -168,10 +151,8 @@ public class BindConverterTests { @Test public void convertWhenHasEditorForArrayElementShouldConvert() { - BindConverter bindConverter = getPropertyEditorOnlyBindConverter( - this::registerSampleTypeEditor); - SampleType[] converted = bindConverter.convert("test", - ResolvableType.forClass(SampleType[].class)); + BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); + SampleType[] converted = bindConverter.convert("test", ResolvableType.forClass(SampleType[].class)); assertThat(converted).isNotEmpty(); assertThat(converted[0].getText()).isEqualTo("test"); } @@ -179,43 +160,36 @@ public class BindConverterTests { @Test public void convertWhenConversionServiceCanConvertShouldConvert() { BindConverter bindConverter = getBindConverter(new SampleTypeConverter()); - SampleType converted = bindConverter.convert("test", - ResolvableType.forClass(SampleType.class)); + SampleType converted = bindConverter.convert("test", ResolvableType.forClass(SampleType.class)); assertThat(converted.getText()).isEqualTo("test"); } @Test public void convertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldThrowException() { - BindConverter bindConverter = BindConverter - .get(ApplicationConversionService.getSharedInstance(), null); + BindConverter bindConverter = BindConverter.get(ApplicationConversionService.getSharedInstance(), null); assertThatExceptionOfType(ConverterNotFoundException.class) - .isThrownBy(() -> bindConverter.convert("test", - ResolvableType.forClass(SampleType.class))); + .isThrownBy(() -> bindConverter.convert("test", ResolvableType.forClass(SampleType.class))); } @Test public void convertWhenConvertingToFileShouldExcludeFileEditor() { // For back compatibility we want true file conversion and not an accidental // classpath resource reference. See gh-12163 - BindConverter bindConverter = BindConverter.get(new GenericConversionService(), - null); + BindConverter bindConverter = BindConverter.get(new GenericConversionService(), null); File result = bindConverter.convert(".", ResolvableType.forClass(File.class)); assertThat(result.getPath()).isEqualTo("."); } @Test public void fallsBackToApplicationConversionService() { - BindConverter bindConverter = BindConverter.get(new GenericConversionService(), - null); - Duration result = bindConverter.convert("10s", - ResolvableType.forClass(Duration.class)); + BindConverter bindConverter = BindConverter.get(new GenericConversionService(), null); + Duration result = bindConverter.convert("10s", ResolvableType.forClass(Duration.class)); assertThat(result.getSeconds()).isEqualTo(10); } private BindConverter getPropertyEditorOnlyBindConverter( Consumer propertyEditorInitializer) { - return BindConverter.get(new ThrowingConversionService(), - propertyEditorInitializer); + return BindConverter.get(new ThrowingConversionService(), propertyEditorInitializer); } private BindConverter getBindConverter(Converter converter) { @@ -302,8 +276,7 @@ public class BindConverterTests { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { throw new AssertionError("Should not call conversion service"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java index 4dec10260ed..6cad4172c62 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -188,8 +188,7 @@ public class BindResultTests { BindResult result3 = BindResult.of("bar"); BindResult result4 = BindResult.of(null); assertThat(result1.hashCode()).isEqualTo(result2.hashCode()); - assertThat(result1).isEqualTo(result1).isEqualTo(result2).isNotEqualTo(result3) - .isNotEqualTo(result4); + assertThat(result1).isEqualTo(result1).isEqualTo(result2).isNotEqualTo(result3).isNotEqualTo(result4); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java index b6509eae16a..48be7b3f8dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java @@ -40,22 +40,19 @@ public class BindableTests { @Test public void ofClassWhenTypeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> Bindable.of((Class) null)) + assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((Class) null)) .withMessageContaining("Type must not be null"); } @Test public void ofTypeWhenTypeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> Bindable.of((ResolvableType) null)) + assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((ResolvableType) null)) .withMessageContaining("Type must not be null"); } @Test public void ofClassShouldSetType() { - assertThat(Bindable.of(String.class).getType()) - .isEqualTo(ResolvableType.forClass(String.class)); + assertThat(Bindable.of(String.class).getType()).isEqualTo(ResolvableType.forClass(String.class)); } @Test @@ -74,29 +71,25 @@ public class BindableTests { @Test public void ofClassWithExistingValueShouldSetTypeAndExistingValue() { - assertThat(Bindable.of(String.class).withExistingValue("foo").getValue().get()) - .isEqualTo("foo"); + assertThat(Bindable.of(String.class).withExistingValue("foo").getValue().get()).isEqualTo("foo"); } @Test public void ofTypeWithExistingValueShouldSetTypeAndExistingValue() { - assertThat(Bindable.of(ResolvableType.forClass(String.class)) - .withExistingValue("foo").getValue().get()).isEqualTo("foo"); + assertThat(Bindable.of(ResolvableType.forClass(String.class)).withExistingValue("foo").getValue().get()) + .isEqualTo("foo"); } @Test public void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)) - .withExistingValue(123)) - .withMessageContaining( - "ExistingValue must be an instance of " + String.class.getName()); + .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123)) + .withMessageContaining("ExistingValue must be an instance of " + String.class.getName()); } @Test public void ofTypeWhenPrimitiveWithExistingValueWrapperShouldNotThrowException() { - Bindable bindable = Bindable - .of(ResolvableType.forClass(int.class)).withExistingValue(123); + Bindable bindable = Bindable.of(ResolvableType.forClass(int.class)).withExistingValue(123); assertThat(bindable.getType().resolve()).isEqualTo(int.class); assertThat(bindable.getValue().get()).isEqualTo(123); } @@ -104,26 +97,22 @@ public class BindableTests { @Test public void getBoxedTypeWhenNotBoxedShouldReturnType() { Bindable bindable = Bindable.of(String.class); - assertThat(bindable.getBoxedType()) - .isEqualTo(ResolvableType.forClass(String.class)); + assertThat(bindable.getBoxedType()).isEqualTo(ResolvableType.forClass(String.class)); } @Test public void getBoxedTypeWhenPrimitiveShouldReturnBoxedType() { Bindable bindable = Bindable.of(int.class); assertThat(bindable.getType()).isEqualTo(ResolvableType.forClass(int.class)); - assertThat(bindable.getBoxedType()) - .isEqualTo(ResolvableType.forClass(Integer.class)); + assertThat(bindable.getBoxedType()).isEqualTo(ResolvableType.forClass(Integer.class)); } @Test public void getBoxedTypeWhenPrimitiveArrayShouldReturnBoxedType() { Bindable bindable = Bindable.of(int[].class); - assertThat(bindable.getType().getComponentType()) - .isEqualTo(ResolvableType.forClass(int.class)); + assertThat(bindable.getType().getComponentType()).isEqualTo(ResolvableType.forClass(int.class)); assertThat(bindable.getBoxedType().isArray()).isTrue(); - assertThat(bindable.getBoxedType().getComponentType()) - .isEqualTo(ResolvableType.forClass(Integer.class)); + assertThat(bindable.getBoxedType().getComponentType()).isEqualTo(ResolvableType.forClass(Integer.class)); } @Test @@ -134,47 +123,38 @@ public class BindableTests { @Test public void withAnnotationsShouldSetAnnotations() { Annotation annotation = mock(Annotation.class); - assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotations()) - .containsExactly(annotation); + assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotations()).containsExactly(annotation); } @Test public void getAnnotationWhenMatchShouldReturnAnnotation() { Test annotation = AnnotationUtils.synthesizeAnnotation(Test.class); - assertThat(Bindable.of(String.class).withAnnotations(annotation) - .getAnnotation(Test.class)).isSameAs(annotation); + assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotation(Test.class)) + .isSameAs(annotation); } @Test public void getAnnotationWhenNoMatchShouldReturnNull() { Test annotation = AnnotationUtils.synthesizeAnnotation(Test.class); - assertThat(Bindable.of(String.class).withAnnotations(annotation) - .getAnnotation(Bean.class)).isNull(); + assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotation(Bean.class)).isNull(); } @Test public void toStringShouldShowDetails() { - Annotation annotation = AnnotationUtils - .synthesizeAnnotation(TestAnnotation.class); - Bindable bindable = Bindable.of(String.class).withExistingValue("foo") - .withAnnotations(annotation); + Annotation annotation = AnnotationUtils.synthesizeAnnotation(TestAnnotation.class); + Bindable bindable = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); System.out.println(bindable.toString()); - assertThat(bindable.toString()).contains("type = java.lang.String, " - + "value = 'provided', annotations = array[" - + "@org.springframework.boot.context.properties.bind." - + "BindableTests$TestAnnotation()]"); + assertThat(bindable.toString()) + .contains("type = java.lang.String, " + "value = 'provided', annotations = array[" + + "@org.springframework.boot.context.properties.bind." + "BindableTests$TestAnnotation()]"); } @Test public void equalsAndHashCode() { - Annotation annotation = AnnotationUtils - .synthesizeAnnotation(TestAnnotation.class); - Bindable bindable1 = Bindable.of(String.class).withExistingValue("foo") - .withAnnotations(annotation); - Bindable bindable2 = Bindable.of(String.class).withExistingValue("foo") - .withAnnotations(annotation); - Bindable bindable3 = Bindable.of(String.class).withExistingValue("fof") - .withAnnotations(annotation); + Annotation annotation = AnnotationUtils.synthesizeAnnotation(TestAnnotation.class); + Bindable bindable1 = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); + Bindable bindable2 = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); + Bindable bindable3 = Bindable.of(String.class).withExistingValue("fof").withAnnotations(annotation); assertThat(bindable1.hashCode()).isEqualTo(bindable2.hashCode()); assertThat(bindable1).isEqualTo(bindable1).isEqualTo(bindable2); assertThat(bindable1).isEqualTo(bindable3); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java index a2ac94c24c8..0be36681c77 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,25 +76,20 @@ public class BinderTests { @Test public void createWhenSourcesIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> new Binder((Iterable) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new Binder((Iterable) null)) .withMessageContaining("Sources must not be null"); } @Test public void bindWhenNameIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, - Bindable.of(String.class), BindHandler.DEFAULT)) - .withMessageContaining("Name must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, + Bindable.of(String.class), BindHandler.DEFAULT)).withMessageContaining("Name must not be null"); } @Test public void bindWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), - null, BindHandler.DEFAULT)) + .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT)) .withMessageContaining("Target must not be null"); } @@ -140,8 +135,7 @@ public class BinderTests { StandardEnvironment environment = new StandardEnvironment(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "bar=23"); this.sources.add(new MockConfigurationPropertySource("foo", "1${bar}")); - this.binder = new Binder(this.sources, - new PropertySourcesPlaceholdersResolver(environment)); + this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); BindResult result = this.binder.bind("foo", Bindable.of(Integer.class)); assertThat(result.get()).isEqualTo(123); } @@ -150,19 +144,17 @@ public class BinderTests { public void bindToValueWithMissingPlaceholderShouldResolveToValueWithPlaceholder() { StandardEnvironment environment = new StandardEnvironment(); this.sources.add(new MockConfigurationPropertySource("foo", "${bar}")); - this.binder = new Binder(this.sources, - new PropertySourcesPlaceholdersResolver(environment)); + this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); BindResult result = this.binder.bind("foo", Bindable.of(String.class)); assertThat(result.get()).isEqualTo("${bar}"); } @Test public void bindToValueWithCustomPropertyEditorShouldReturnConvertedValue() { - this.binder = new Binder(this.sources, null, null, (registry) -> registry - .registerCustomEditor(JavaBean.class, new JavaBeanPropertyEditor())); + this.binder = new Binder(this.sources, null, null, + (registry) -> registry.registerCustomEditor(JavaBean.class, new JavaBeanPropertyEditor())); this.sources.add(new MockConfigurationPropertySource("foo", "123")); - BindResult result = this.binder.bind("foo", - Bindable.of(JavaBean.class)); + BindResult result = this.binder.bind("foo", Bindable.of(JavaBean.class)); assertThat(result.get().getValue()).isEqualTo("123"); } @@ -173,8 +165,7 @@ public class BinderTests { Bindable target = Bindable.of(Integer.class); this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), - eq(target), any(), eq(1)); + ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), eq(1)); } @Test @@ -186,8 +177,7 @@ public class BinderTests { @Test public void bindToJavaBeanWhenNonIterableShouldReturnPopulatedBean() { - MockConfigurationPropertySource source = new MockConfigurationPropertySource( - "foo.value", "bar"); + MockConfigurationPropertySource source = new MockConfigurationPropertySource("foo.value", "bar"); this.sources.add(source.nonIterable()); JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get(); assertThat(result.getValue()).isEqualTo("bar"); @@ -206,22 +196,20 @@ public class BinderTests { @Test public void bindToJavaBeanShouldTriggerOnSuccess() { - this.sources - .add(new MockConfigurationPropertySource("foo.value", "bar", "line1")); + this.sources.add(new MockConfigurationPropertySource("foo.value", "bar", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable target = Bindable.of(JavaBean.class); this.binder.bind("foo", target, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")), - eq(Bindable.of(String.class)), any(), eq("bar")); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), - eq(target), any(), isA(JavaBean.class)); + inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), + any(), eq("bar")); + inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), + isA(JavaBean.class)); } @Test public void bindWhenHasMalformedDateShouldThrowException() { - this.sources.add(new MockConfigurationPropertySource("foo", - "2014-04-01T01:30:00.000-05:00")); + this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); assertThatExceptionOfType(BindException.class) .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) .withCauseInstanceOf(ConversionFailedException.class); @@ -229,14 +217,10 @@ public class BinderTests { @Test public void bindWhenHasAnnotationsShouldChangeConvertedValue() { - this.sources.add(new MockConfigurationPropertySource("foo", - "2014-04-01T01:30:00.000-05:00")); + this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); DateTimeFormat annotation = AnnotationUtils.synthesizeAnnotation( - Collections.singletonMap("iso", DateTimeFormat.ISO.DATE_TIME), - DateTimeFormat.class, null); - LocalDate result = this.binder - .bind("foo", Bindable.of(LocalDate.class).withAnnotations(annotation)) - .get(); + Collections.singletonMap("iso", DateTimeFormat.ISO.DATE_TIME), DateTimeFormat.class, null); + LocalDate result = this.binder.bind("foo", Bindable.of(LocalDate.class).withAnnotations(annotation)).get(); assertThat(result.toString()).isEqualTo("2014-04-01"); } @@ -247,14 +231,12 @@ public class BinderTests { source.put("foo.items", "bar,baz"); this.sources.add(source); Bindable target = Bindable.of(JavaBean.class); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", target)) + assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", target)) .satisfies(this::noItemsSetterRequirements); } private void noItemsSetterRequirements(BindException ex) { - assertThat(ex.getCause().getMessage()) - .isEqualTo("No setter found for property: items"); + assertThat(ex.getCause().getMessage()).isEqualTo("No setter found for property: items"); assertThat(ex.getProperty()).isNull(); } @@ -268,10 +250,9 @@ public class BinderTests { } }).forEach(this.sources::add); - Validator validator = new SpringValidatorAdapter(Validation.byDefaultProvider() - .configure().buildValidatorFactory().getValidator()); - this.binder.bind("foo", Bindable.of(ResourceBean.class), - new ValidationBindHandler(validator)); + Validator validator = new SpringValidatorAdapter( + Validation.byDefaultProvider().configure().buildValidatorFactory().getValidator()); + this.binder.bind("foo", Bindable.of(ResourceBean.class), new ValidationBindHandler(validator)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java index db235e0c5ba..e31ee99826e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java @@ -48,11 +48,9 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ public class CollectionBinderTests { - private static final Bindable> INTEGER_LIST = Bindable - .listOf(Integer.class); + private static final Bindable> INTEGER_LIST = Bindable.listOf(Integer.class); - private static final Bindable> STRING_LIST = Bindable - .listOf(String.class); + private static final Bindable> STRING_LIST = Bindable.listOf(String.class); private static final Bindable> STRING_SET = Bindable.setOf(String.class); @@ -95,8 +93,8 @@ public class CollectionBinderTests { source.put("foo[1][0]", "3"); source.put("foo[1][1]", "4"); this.sources.add(source); - Bindable>> target = Bindable.of( - ResolvableType.forClassWithGenerics(List.class, INTEGER_LIST.getType())); + Bindable>> target = Bindable + .of(ResolvableType.forClassWithGenerics(List.class, INTEGER_LIST.getType())); List> result = this.binder.bind("foo", target).get(); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1, 2); @@ -121,11 +119,10 @@ public class CollectionBinderTests { source.put("foo[1]", "1"); source.put("foo[3]", "3"); this.sources.add(source); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", INTEGER_LIST)) + assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", INTEGER_LIST)) .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex - .getCause()).getUnboundProperties(); + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); assertThat(unbound).hasSize(1); ConfigurationProperty property = unbound.iterator().next(); assertThat(property.getName().toString()).isEqualTo("foo[3]"); @@ -141,10 +138,10 @@ public class CollectionBinderTests { source.put("foo[4].value", "4"); this.sources.add(source); Bindable> target = Bindable.listOf(JavaBean.class); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", target)).satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex - .getCause()).getUnboundProperties(); + assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", target)) + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); assertThat(unbound).hasSize(1); ConfigurationProperty property = unbound.iterator().next(); assertThat(property.getName().toString()).isEqualTo("foo[4].value"); @@ -187,8 +184,7 @@ public class CollectionBinderTests { List existing = new LinkedList<>(); existing.add(1000); existing.add(1001); - List result = this.binder - .bind("foo", INTEGER_LIST.withExistingValue(existing)).get(); + List result = this.binder.bind("foo", INTEGER_LIST.withExistingValue(existing)).get(); assertThat(result).isExactlyInstanceOf(LinkedList.class); assertThat(result).containsExactly(1); } @@ -198,20 +194,17 @@ public class CollectionBinderTests { this.sources.add(new MockConfigurationPropertySource("faf[0]", "1")); List existing = new LinkedList<>(); existing.add(1000); - BindResult> result = this.binder.bind("foo", - INTEGER_LIST.withExistingValue(existing)); + BindResult> result = this.binder.bind("foo", INTEGER_LIST.withExistingValue(existing)); assertThat(result.isBound()).isFalse(); } @Test public void bindToCollectionShouldRespectCollectionType() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1")); - ResolvableType type = ResolvableType.forClassWithGenerics(LinkedList.class, - Integer.class); + ResolvableType type = ResolvableType.forClassWithGenerics(LinkedList.class, Integer.class); Object defaultList = this.binder.bind("foo", INTEGER_LIST).get(); Object customList = this.binder.bind("foo", Bindable.of(type)).get(); - assertThat(customList).isExactlyInstanceOf(LinkedList.class) - .isNotInstanceOf(defaultList.getClass()); + assertThat(customList).isExactlyInstanceOf(LinkedList.class).isNotInstanceOf(defaultList.getClass()); } @Test @@ -231,10 +224,8 @@ public class CollectionBinderTests { @Test public void bindToCollectionWhenCommaListWithPlaceholdersShouldReturnPopulatedCollection() { StandardEnvironment environment = new StandardEnvironment(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - "bar=1,2,3"); - this.binder = new Binder(this.sources, - new PropertySourcesPlaceholdersResolver(environment)); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "bar=1,2,3"); + this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); this.sources.add(new MockConfigurationPropertySource("foo", "${bar}")); List result = this.binder.bind("foo", INTEGER_LIST).get(); assertThat(result).containsExactly(1, 2, 3); @@ -294,8 +285,7 @@ public class CollectionBinderTests { Bindable> target = Bindable.listOf(JavaBean.class); List result = this.binder.bind("foo", target).get(); assertThat(result).hasSize(3); - List values = result.stream().map(JavaBean::getValue) - .collect(Collectors.toList()); + List values = result.stream().map(JavaBean::getValue).collect(Collectors.toList()); assertThat(values).containsExactly("a", "b", "c"); } @@ -304,9 +294,7 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values", "a,b,c"); this.sources.add(source); - Set result = this.binder - .bind("foo.values", STRING_SET.withExistingValue(Collections.emptySet())) - .get(); + Set result = this.binder.bind("foo.values", STRING_SET.withExistingValue(Collections.emptySet())).get(); assertThat(result).hasSize(3); } @@ -315,8 +303,7 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items", "a,b,c"); this.sources.add(source); - ExampleCollectionBean result = this.binder - .bind("foo", ExampleCollectionBean.class).get(); + ExampleCollectionBean result = this.binder.bind("foo", ExampleCollectionBean.class).get(); assertThat(result.getItems()).hasSize(4); assertThat(result.getItems()).containsExactly("a", "b", "c", "d"); } @@ -349,8 +336,7 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items", "a,b,c,c"); this.sources.add(source); - ExampleCollectionBean result = this.binder - .bind("foo", ExampleCollectionBean.class).get(); + ExampleCollectionBean result = this.binder.bind("foo", ExampleCollectionBean.class).get(); assertThat(result.getItems()).hasSize(5); assertThat(result.getItems()).containsExactly("a", "b", "c", "c", "d"); } @@ -360,8 +346,7 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items-set", "a,b,c,c"); this.sources.add(source); - ExampleCollectionBean result = this.binder - .bind("foo", ExampleCollectionBean.class).get(); + ExampleCollectionBean result = this.binder.bind("foo", ExampleCollectionBean.class).get(); assertThat(result.getItemsSet()).hasSize(3); assertThat(result.getItemsSet()).containsExactly("a", "b", "c"); } @@ -373,8 +358,7 @@ public class CollectionBinderTests { source.put("foo.foos[0].value", "two"); source.put("foo.foos[1].value", "three"); this.sources.add(source); - Bindable target = Bindable - .of(BeanWithNestedCollection.class); + Bindable target = Bindable.of(BeanWithNestedCollection.class); BeanWithNestedCollection foo = this.binder.bind("foo", target).get(); assertThat(foo.getValue()).isEqualTo("one"); assertThat(foo.getFoos().get(0).getValue()).isEqualTo("two"); @@ -387,8 +371,7 @@ public class CollectionBinderTests { source.put("foo.value", "one"); source.put("foo.foos", ""); this.sources.add(source); - Bindable target = Bindable - .of(BeanWithNestedCollection.class); + Bindable target = Bindable.of(BeanWithNestedCollection.class); BeanWithNestedCollection foo = this.binder.bind("foo", target).get(); assertThat(foo.getValue()).isEqualTo("one"); assertThat(foo.getFoos()).isEmpty(); @@ -401,8 +384,8 @@ public class CollectionBinderTests { source.put("foo[0]", "java.lang.RuntimeException"); source.put("foo[1]", "java.lang.IllegalStateException"); this.sources.add(source); - assertThat(this.binder.bind("foo", Bindable.listOf(Class.class)).get()) - .containsExactly(RuntimeException.class, IllegalStateException.class); + assertThat(this.binder.bind("foo", Bindable.listOf(Class.class)).get()).containsExactly(RuntimeException.class, + IllegalStateException.class); } @Test @@ -411,8 +394,8 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "java.lang.RuntimeException,java.lang.IllegalStateException"); this.sources.add(source); - assertThat(this.binder.bind("foo", Bindable.listOf(Class.class)).get()) - .containsExactly(RuntimeException.class, IllegalStateException.class); + assertThat(this.binder.bind("foo", Bindable.listOf(Class.class)).get()).containsExactly(RuntimeException.class, + IllegalStateException.class); } @Test @@ -420,8 +403,7 @@ public class CollectionBinderTests { // gh-10702 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); this.sources.add(source.nonIterable()); - Bindable target = Bindable - .of(BeanWithNestedCollection.class); + Bindable target = Bindable.of(BeanWithNestedCollection.class); this.binder.bind("foo", target); } @@ -440,8 +422,7 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values", "a,b,c"); this.sources.add(source); - BeanWithGetterException result = this.binder - .bind("foo", Bindable.of(BeanWithGetterException.class)).get(); + BeanWithGetterException result = this.binder.bind("foo", Bindable.of(BeanWithGetterException.class)).get(); assertThat(result.getValues()).containsExactly("a", "b", "c"); } @@ -450,10 +431,8 @@ public class CollectionBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values[0]", "foo-bar,bar-baz"); this.sources.add(source); - BeanWithEnumSetCollection result = this.binder - .bind("foo", Bindable.of(BeanWithEnumSetCollection.class)).get(); - assertThat(result.getValues().get(0)).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + BeanWithEnumSetCollection result = this.binder.bind("foo", Bindable.of(BeanWithEnumSetCollection.class)).get(); + assertThat(result.getValues().get(0)).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } public static class ExampleCollectionBean { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java index dc97f3d5aaf..6ee166be757 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java @@ -52,8 +52,7 @@ public class ConstructorParametersBinderTests { source.put("foo.string-value", "foo"); source.put("foo.enum-value", "foo-bar"); this.sources.add(source); - ExampleValueBean bean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class)).get(); + ExampleValueBean bean = this.binder.bind("foo", Bindable.of(ExampleValueBean.class)).get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.isBooleanValue()).isTrue(); @@ -70,8 +69,8 @@ public class ConstructorParametersBinderTests { source.put("string-value", "foo"); source.put("enum-value", "foo-bar"); this.sources.add(source); - ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), - Bindable.of(ExampleValueBean.class)).get(); + ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), Bindable.of(ExampleValueBean.class)) + .get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.isBooleanValue()).isTrue(); @@ -84,8 +83,7 @@ public class ConstructorParametersBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.name", "test"); this.sources.add(source); - boolean bound = this.binder.bind("foo", Bindable.of(ExampleAbstractBean.class)) - .isBound(); + boolean bound = this.binder.bind("foo", Bindable.of(ExampleAbstractBean.class)).isBound(); assertThat(bound).isFalse(); } @@ -94,8 +92,7 @@ public class ConstructorParametersBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); this.sources.add(source); - boolean bound = this.binder - .bind("foo", Bindable.of(MultipleConstructorsBean.class)).isBound(); + boolean bound = this.binder.bind("foo", Bindable.of(MultipleConstructorsBean.class)).isBound(); assertThat(bound).isFalse(); } @@ -104,8 +101,7 @@ public class ConstructorParametersBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); this.sources.add(source); - boolean bound = this.binder.bind("foo", Bindable.of(DefaultConstructorBean.class)) - .isBound(); + boolean bound = this.binder.bind("foo", Bindable.of(DefaultConstructorBean.class)).isBound(); assertThat(bound).isFalse(); } @@ -116,8 +112,7 @@ public class ConstructorParametersBinderTests { source.put("foo.value-bean.long-value", "34"); source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); - ExampleNestedBean bean = this.binder - .bind("foo", Bindable.of(ExampleNestedBean.class)).get(); + ExampleNestedBean bean = this.binder.bind("foo", Bindable.of(ExampleNestedBean.class)).get(); assertThat(bean.getValueBean().getIntValue()).isEqualTo(123); assertThat(bean.getValueBean().getLongValue()).isEqualTo(34); assertThat(bean.getValueBean().isBooleanValue()).isFalse(); @@ -130,8 +125,7 @@ public class ConstructorParametersBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.string-value", "foo"); this.sources.add(source); - ExampleValueBean bean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class)).get(); + ExampleValueBean bean = this.binder.bind("foo", Bindable.of(ExampleValueBean.class)).get(); assertThat(bean.getIntValue()).isEqualTo(0); assertThat(bean.getLongValue()).isEqualTo(0); assertThat(bean.isBooleanValue()).isEqualTo(false); @@ -143,8 +137,7 @@ public class ConstructorParametersBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.string-value", "foo"); this.sources.add(source); - ExampleDefaultValueBean bean = this.binder - .bind("foo", Bindable.of(ExampleDefaultValueBean.class)).get(); + ExampleDefaultValueBean bean = this.binder.bind("foo", Bindable.of(ExampleDefaultValueBean.class)).get(); assertThat(bean.getIntValue()).isEqualTo(5); assertThat(bean.getStringsList()).containsOnly("a", "b", "c"); assertThat(bean.getCustomList()).containsOnly("x,y,z"); @@ -162,8 +155,8 @@ public class ConstructorParametersBinderTests { private final ExampleEnum enumValue; - public ExampleValueBean(int intValue, long longValue, boolean booleanValue, - String stringValue, ExampleEnum enumValue) { + public ExampleValueBean(int intValue, long longValue, boolean booleanValue, String stringValue, + ExampleEnum enumValue) { this.intValue = intValue; this.longValue = longValue; this.booleanValue = booleanValue; @@ -208,8 +201,7 @@ public class ConstructorParametersBinderTests { this(intValue, 23L, "hello"); } - public MultipleConstructorsBean(int intValue, long longValue, - String stringValue) { + public MultipleConstructorsBean(int intValue, long longValue, String stringValue) { } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java index 7c989dddced..120b08bd3dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java @@ -70,8 +70,7 @@ public class JavaBeanBinderTests { source.put("foo.string-value", "foo"); source.put("foo.enum-value", "foo-bar"); this.sources.add(source); - ExampleValueBean bean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class)).get(); + ExampleValueBean bean = this.binder.bind("foo", Bindable.of(ExampleValueBean.class)).get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.getStringValue()).isEqualTo("foo"); @@ -86,8 +85,8 @@ public class JavaBeanBinderTests { source.put("string-value", "foo"); source.put("enum-value", "foo-bar"); this.sources.add(source); - ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), - Bindable.of(ExampleValueBean.class)).get(); + ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), Bindable.of(ExampleValueBean.class)) + .get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.getStringValue()).isEqualTo("foo"); @@ -104,8 +103,7 @@ public class JavaBeanBinderTests { this.sources.add(source); ExampleValueBean bean = new ExampleValueBean(); ExampleValueBean boundBean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class).withExistingValue(bean)) - .get(); + .bind("foo", Bindable.of(ExampleValueBean.class).withExistingValue(bean)).get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); @@ -130,8 +128,7 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "999"); this.sources.add(source); - ExampleDefaultsBean bean = this.binder - .bind("foo", Bindable.of(ExampleDefaultsBean.class)).get(); + ExampleDefaultsBean bean = this.binder.bind("foo", Bindable.of(ExampleDefaultsBean.class)).get(); assertThat(bean.getFoo()).isEqualTo(123); assertThat(bean.getBar()).isEqualTo(999); } @@ -144,9 +141,7 @@ public class JavaBeanBinderTests { ExampleDefaultsBean bean = new ExampleDefaultsBean(); bean.setFoo(888); ExampleDefaultsBean boundBean = this.binder - .bind("foo", - Bindable.of(ExampleDefaultsBean.class).withExistingValue(bean)) - .get(); + .bind("foo", Bindable.of(ExampleDefaultsBean.class).withExistingValue(bean)).get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getFoo()).isEqualTo(888); assertThat(bean.getBar()).isEqualTo(999); @@ -158,10 +153,8 @@ public class JavaBeanBinderTests { source.put("foo.map.foo-bar", "1"); source.put("foo.map.bar-baz", "2"); this.sources.add(source); - ExampleMapBean bean = this.binder.bind("foo", Bindable.of(ExampleMapBean.class)) - .get(); - assertThat(bean.getMap()).containsExactly(entry(ExampleEnum.FOO_BAR, 1), - entry(ExampleEnum.BAR_BAZ, 2)); + ExampleMapBean bean = this.binder.bind("foo", Bindable.of(ExampleMapBean.class)).get(); + assertThat(bean.getMap()).containsExactly(entry(ExampleEnum.FOO_BAR, 1), entry(ExampleEnum.BAR_BAZ, 2)); } @Test @@ -170,10 +163,8 @@ public class JavaBeanBinderTests { source.put("foo.list[0]", "foo-bar"); source.put("foo.list[1]", "bar-baz"); this.sources.add(source); - ExampleListBean bean = this.binder.bind("foo", Bindable.of(ExampleListBean.class)) - .get(); - assertThat(bean.getList()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + ExampleListBean bean = this.binder.bind("foo", Bindable.of(ExampleListBean.class)).get(); + assertThat(bean.getList()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -183,8 +174,7 @@ public class JavaBeanBinderTests { source.put("foo.list[2]", "bar-baz"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy( - () -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) .withCauseInstanceOf(UnboundConfigurationPropertiesException.class); } @@ -194,10 +184,8 @@ public class JavaBeanBinderTests { source.put("foo.set[0]", "foo-bar"); source.put("foo.set[1]", "bar-baz"); this.sources.add(source); - ExampleSetBean bean = this.binder.bind("foo", Bindable.of(ExampleSetBean.class)) - .get(); - assertThat(bean.getSet()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + ExampleSetBean bean = this.binder.bind("foo", Bindable.of(ExampleSetBean.class)).get(); + assertThat(bean.getSet()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -206,10 +194,8 @@ public class JavaBeanBinderTests { source.put("foo.collection[0]", "foo-bar"); source.put("foo.collection[1]", "bar-baz"); this.sources.add(source); - ExampleCollectionBean bean = this.binder - .bind("foo", Bindable.of(ExampleCollectionBean.class)).get(); - assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + ExampleCollectionBean bean = this.binder.bind("foo", Bindable.of(ExampleCollectionBean.class)).get(); + assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -219,8 +205,7 @@ public class JavaBeanBinderTests { this.sources.add(source); ExampleCollectionBeanWithDelimiter bean = this.binder .bind("foo", Bindable.of(ExampleCollectionBeanWithDelimiter.class)).get(); - assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -229,10 +214,9 @@ public class JavaBeanBinderTests { source.put("foo.map.foo-bar", "1"); source.put("foo.map.bar-baz", "2"); this.sources.add(source); - ExampleMapBeanWithoutSetter bean = this.binder - .bind("foo", Bindable.of(ExampleMapBeanWithoutSetter.class)).get(); - assertThat(bean.getMap()).containsExactly(entry(ExampleEnum.FOO_BAR, 1), - entry(ExampleEnum.BAR_BAZ, 2)); + ExampleMapBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleMapBeanWithoutSetter.class)) + .get(); + assertThat(bean.getMap()).containsExactly(entry(ExampleEnum.FOO_BAR, 1), entry(ExampleEnum.BAR_BAZ, 2)); } @Test @@ -241,10 +225,9 @@ public class JavaBeanBinderTests { source.put("foo.list[0]", "foo-bar"); source.put("foo.list[1]", "bar-baz"); this.sources.add(source); - ExampleListBeanWithoutSetter bean = this.binder - .bind("foo", Bindable.of(ExampleListBeanWithoutSetter.class)).get(); - assertThat(bean.getList()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + ExampleListBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleListBeanWithoutSetter.class)) + .get(); + assertThat(bean.getList()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -253,10 +236,9 @@ public class JavaBeanBinderTests { source.put("foo.set[0]", "foo-bar"); source.put("foo.set[1]", "bar-baz"); this.sources.add(source); - ExampleSetBeanWithoutSetter bean = this.binder - .bind("foo", Bindable.of(ExampleSetBeanWithoutSetter.class)).get(); - assertThat(bean.getSet()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + ExampleSetBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleSetBeanWithoutSetter.class)) + .get(); + assertThat(bean.getSet()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -267,8 +249,7 @@ public class JavaBeanBinderTests { this.sources.add(source); ExampleCollectionBeanWithoutSetter bean = this.binder .bind("foo", Bindable.of(ExampleCollectionBeanWithoutSetter.class)).get(); - assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, - ExampleEnum.BAR_BAZ); + assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @Test @@ -277,8 +258,7 @@ public class JavaBeanBinderTests { source.put("foo.value-bean.int-value", "123"); source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); - ExampleNestedBean bean = this.binder - .bind("foo", Bindable.of(ExampleNestedBean.class)).get(); + ExampleNestedBean bean = this.binder.bind("foo", Bindable.of(ExampleNestedBean.class)).get(); assertThat(bean.getValueBean().getIntValue()).isEqualTo(123); assertThat(bean.getValueBean().getStringValue()).isEqualTo("foo"); } @@ -290,8 +270,7 @@ public class JavaBeanBinderTests { source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); ExampleNestedBeanWithoutSetterOrType bean = this.binder - .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetterOrType.class)) - .get(); + .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetterOrType.class)).get(); ExampleValueBean valueBean = (ExampleValueBean) bean.getValueBean(); assertThat(valueBean.getIntValue()).isEqualTo(123); assertThat(valueBean.getStringValue()).isEqualTo("foo"); @@ -316,8 +295,8 @@ public class JavaBeanBinderTests { source.put("foo.value-bean.int-value", "123"); source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); - ExampleNestedBeanWithoutSetter bean = this.binder - .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetter.class)).get(); + ExampleNestedBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleNestedBeanWithoutSetter.class)) + .get(); assertThat(bean.getValueBean().getIntValue()).isEqualTo(123); assertThat(bean.getValueBean().getStringValue()).isEqualTo("foo"); } @@ -327,8 +306,8 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.nested.foo", "bar"); this.sources.add(source); - assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder - .bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); } @Test @@ -348,8 +327,7 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("faf.int-value", "12"); this.sources.add(source); - BindResult bean = this.binder.bind("foo", - Bindable.of(ExampleValueBean.class)); + BindResult bean = this.binder.bind("foo", Bindable.of(ExampleValueBean.class)); assertThat(bean.isBound()).isFalse(); } @@ -370,11 +348,9 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "bar"); this.sources.add(source); - ExampleWithNonDefaultConstructor bean = new ExampleWithNonDefaultConstructor( - "faf"); - ExampleWithNonDefaultConstructor boundBean = this.binder.bind("foo", Bindable - .of(ExampleWithNonDefaultConstructor.class).withExistingValue(bean)) - .get(); + ExampleWithNonDefaultConstructor bean = new ExampleWithNonDefaultConstructor("faf"); + ExampleWithNonDefaultConstructor boundBean = this.binder + .bind("foo", Bindable.of(ExampleWithNonDefaultConstructor.class).withExistingValue(bean)).get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getValue()).isEqualTo("bar"); } @@ -385,8 +361,7 @@ public class JavaBeanBinderTests { source.put("foo.int-value", "123"); source.put("foo.long-value", "456"); this.sources.add(source); - ExampleSubclassBean bean = this.binder - .bind("foo", Bindable.of(ExampleSubclassBean.class)).get(); + ExampleSubclassBean bean = this.binder.bind("foo", Bindable.of(ExampleSubclassBean.class)).get(); assertThat(bean.getIntValue()).isEqualTo(123); assertThat(bean.getLongValue()).isEqualTo(456); } @@ -394,8 +369,8 @@ public class JavaBeanBinderTests { @Test public void bindToClassWhenPropertyCannotBeConvertedShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo.int-value", "foo")); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); } @Test @@ -407,8 +382,7 @@ public class JavaBeanBinderTests { source.put("foo.enum-value", "foo-bar"); this.sources.add(source); IgnoreErrorsBindHandler handler = new IgnoreErrorsBindHandler(); - ExampleValueBean bean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class), handler).get(); + ExampleValueBean bean = this.binder.bind("foo", Bindable.of(ExampleValueBean.class), handler).get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(0); assertThat(bean.getStringValue()).isEqualTo("foo"); @@ -420,18 +394,15 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "123"); this.sources.add(source); - ExampleMismatchBean bean = this.binder - .bind("foo", Bindable.of(ExampleMismatchBean.class)).get(); + ExampleMismatchBean bean = this.binder.bind("foo", Bindable.of(ExampleMismatchBean.class)).get(); assertThat(bean.getValue()).isEqualTo("123"); } @Test public void bindToClassShouldNotInvokeExtraMethods() { - MockConfigurationPropertySource source = new MockConfigurationPropertySource( - "foo.value", "123"); + MockConfigurationPropertySource source = new MockConfigurationPropertySource("foo.value", "123"); this.sources.add(source.nonIterable()); - ExampleWithThrowingGetters bean = this.binder - .bind("foo", Bindable.of(ExampleWithThrowingGetters.class)).get(); + ExampleWithThrowingGetters bean = this.binder.bind("foo", Bindable.of(ExampleWithThrowingGetters.class)).get(); assertThat(bean.getValue()).isEqualTo(123); } @@ -440,8 +411,7 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "123"); this.sources.add(source); - ExampleWithSelfReference bean = this.binder - .bind("foo", Bindable.of(ExampleWithSelfReference.class)).get(); + ExampleWithSelfReference bean = this.binder.bind("foo", Bindable.of(ExampleWithSelfReference.class)).get(); assertThat(bean.getValue()).isEqualTo(123); } @@ -462,8 +432,8 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.date", "2014-04-01"); this.sources.add(source); - ConverterAnnotatedExampleBean bean = this.binder - .bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)).get(); + ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) + .get(); assertThat(bean.getDate().toString()).isEqualTo("2014-04-01"); } @@ -473,8 +443,8 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "java.lang.RuntimeException"); this.sources.add(source); - ExampleWithPropertyEditorType bean = this.binder - .bind("foo", Bindable.of(ExampleWithPropertyEditorType.class)).get(); + ExampleWithPropertyEditorType bean = this.binder.bind("foo", Bindable.of(ExampleWithPropertyEditorType.class)) + .get(); assertThat(bean.getValue()).isEqualTo(RuntimeException.class); } @@ -483,8 +453,8 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.name", "something"); this.sources.add(source); - ExampleWithInvalidAccessors bean = this.binder - .bind("foo", Bindable.of(ExampleWithInvalidAccessors.class)).get(); + ExampleWithInvalidAccessors bean = this.binder.bind("foo", Bindable.of(ExampleWithInvalidAccessors.class)) + .get(); assertThat(bean.getName()).isEqualTo("something"); } @@ -494,8 +464,7 @@ public class JavaBeanBinderTests { source.put("foo.name", "invalid"); source.put("foo.counter", "42"); this.sources.add(source); - ExampleWithStaticAccessors bean = this.binder - .bind("foo", Bindable.of(ExampleWithStaticAccessors.class)).get(); + ExampleWithStaticAccessors bean = this.binder.bind("foo", Bindable.of(ExampleWithStaticAccessors.class)).get(); assertThat(ExampleWithStaticAccessors.name).isNull(); assertThat(bean.getCounter()).isEqualTo(42); } @@ -507,8 +476,7 @@ public class JavaBeanBinderTests { source.put("foo.integers[a].value", "1"); source.put("foo.booleans[b].value", "true"); this.sources.add(source); - ExampleWithGenericMap bean = this.binder - .bind("foo", Bindable.of(ExampleWithGenericMap.class)).get(); + ExampleWithGenericMap bean = this.binder.bind("foo", Bindable.of(ExampleWithGenericMap.class)).get(); assertThat(bean.getIntegers().get("a").getValue()).isEqualTo(1); assertThat(bean.getBooleans().get("b").getValue()).isEqualTo(true); } @@ -519,8 +487,8 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.property", "some string"); this.sources.add(source); - PropertyWithOverloadedSetter bean = this.binder - .bind("foo", Bindable.of(PropertyWithOverloadedSetter.class)).get(); + PropertyWithOverloadedSetter bean = this.binder.bind("foo", Bindable.of(PropertyWithOverloadedSetter.class)) + .get(); assertThat(bean.getProperty()).isEqualTo("some string"); } @@ -528,12 +496,10 @@ public class JavaBeanBinderTests { public void beanPropertiesPreferMatchingType() { // gh-16206 ResolvableType type = ResolvableType.forClass(PropertyWithOverloadedSetter.class); - Bean bean = new Bean( - type, type.resolve()) { + Bean bean = new Bean(type, type.resolve()) { @Override - protected void addProperties(Method[] declaredMethods, - Field[] declaredFields) { + protected void addProperties(Method[] declaredMethods, Field[] declaredFields) { // We override here because we need a specific order of the declared // methods and the JVM doesn't give us one int intSetter = -1; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java index a3d5af4f47d..bf096bea33c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,20 +61,18 @@ import static org.mockito.Mockito.mock; */ public class MapBinderTests { - private static final Bindable> STRING_STRING_MAP = Bindable - .mapOf(String.class, String.class); + private static final Bindable> STRING_STRING_MAP = Bindable.mapOf(String.class, String.class); - private static final Bindable> STRING_INTEGER_MAP = Bindable - .mapOf(String.class, Integer.class); + private static final Bindable> STRING_INTEGER_MAP = Bindable.mapOf(String.class, + Integer.class); - private static final Bindable> INTEGER_INTEGER_MAP = Bindable - .mapOf(Integer.class, Integer.class); + private static final Bindable> INTEGER_INTEGER_MAP = Bindable.mapOf(Integer.class, + Integer.class); - private static final Bindable> STRING_OBJECT_MAP = Bindable - .mapOf(String.class, Object.class); + private static final Bindable> STRING_OBJECT_MAP = Bindable.mapOf(String.class, Object.class); - private static final Bindable> STRING_ARRAY_MAP = Bindable - .mapOf(String.class, String[].class); + private static final Bindable> STRING_ARRAY_MAP = Bindable.mapOf(String.class, + String[].class); private List sources = new ArrayList<>(); @@ -126,8 +124,8 @@ public class MapBinderTests { @Test public void bindToMapShouldBindToMapValue() { - ResolvableType type = ResolvableType.forClassWithGenerics(Map.class, - ResolvableType.forClass(String.class), STRING_INTEGER_MAP.getType()); + ResolvableType type = ResolvableType.forClassWithGenerics(Map.class, ResolvableType.forClass(String.class), + STRING_INTEGER_MAP.getType()); MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar.baz", "1"); source.put("foo.bar.bin", "2"); @@ -146,8 +144,8 @@ public class MapBinderTests { public void bindToMapShouldBindNestedMapValue() { ResolvableType nestedType = ResolvableType.forClassWithGenerics(Map.class, ResolvableType.forClass(String.class), STRING_INTEGER_MAP.getType()); - ResolvableType type = ResolvableType.forClassWithGenerics(Map.class, - ResolvableType.forClass(String.class), nestedType); + ResolvableType type = ResolvableType.forClassWithGenerics(Map.class, ResolvableType.forClass(String.class), + nestedType); MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.nested.bar.baz", "1"); source.put("foo.nested.bar.bin", "2"); @@ -155,10 +153,8 @@ public class MapBinderTests { source.put("foo.nested.far.bin", "4"); source.put("faf.nested.far.bin", "x"); this.sources.add(source); - Bindable>>> target = Bindable - .of(type); - Map>> result = this.binder - .bind("foo", target).get(); + Bindable>>> target = Bindable.of(type); + Map>> result = this.binder.bind("foo", target).get(); Map> nested = result.get("nested"); assertThat(nested).hasSize(2); assertThat(nested.get("bar")).containsEntry("baz", 1).containsEntry("bin", 2); @@ -175,8 +171,7 @@ public class MapBinderTests { source.put("foo.nested.far.bin", "4"); source.put("faf.nested.far.bin", "x"); this.sources.add(source); - Map result = this.binder - .bind("foo", Bindable.mapOf(String.class, Object.class)).get(); + Map result = this.binder.bind("foo", Bindable.mapOf(String.class, Object.class)).get(); Map nested = (Map) result.get("nested"); assertThat(nested).hasSize(2); Map bar = (Map) nested.get("bar"); @@ -192,10 +187,8 @@ public class MapBinderTests { source.put("branch", "master"); source.put("foo", "bar"); this.sources.add(source); - Map result = this.binder - .bind("", Bindable.mapOf(String.class, Object.class)).get(); - assertThat(result.get("commit")) - .isEqualTo(Collections.singletonMap("id", "abcdefg")); + Map result = this.binder.bind("", Bindable.mapOf(String.class, Object.class)).get(); + assertThat(result.get("commit")).isEqualTo(Collections.singletonMap("id", "abcdefg")); assertThat(result.get("branch")).isEqualTo("master"); assertThat(result.get("foo")).isEqualTo("bar"); } @@ -235,8 +228,7 @@ public class MapBinderTests { map.put("foo.b-az", "2"); map.put("foo.ba-z", "3"); map.put("foo.bin", "4"); - MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource( - map); + MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource(map); this.sources.add(propertySource); Map result = this.binder.bind("foo", STRING_INTEGER_MAP).get(); assertThat(result).hasSize(4); @@ -252,8 +244,7 @@ public class MapBinderTests { Map existing = new HashMap<>(); existing.put("bar", 1000); existing.put("baz", 1001); - Bindable> target = STRING_INTEGER_MAP - .withExistingValue(existing); + Bindable> target = STRING_INTEGER_MAP.withExistingValue(existing); Map result = this.binder.bind("foo", target).get(); assertThat(result).isExactlyInstanceOf(HashMap.class); assertThat(result).hasSize(2); @@ -264,19 +255,16 @@ public class MapBinderTests { @Test public void bindToMapShouldRespectMapType() { this.sources.add(new MockConfigurationPropertySource("foo.bar", "1")); - ResolvableType type = ResolvableType.forClassWithGenerics(HashMap.class, - String.class, Integer.class); + ResolvableType type = ResolvableType.forClassWithGenerics(HashMap.class, String.class, Integer.class); Object defaultMap = this.binder.bind("foo", STRING_INTEGER_MAP).get(); Object customMap = this.binder.bind("foo", Bindable.of(type)).get(); - assertThat(customMap).isExactlyInstanceOf(HashMap.class) - .isNotInstanceOf(defaultMap.getClass()); + assertThat(customMap).isExactlyInstanceOf(HashMap.class).isNotInstanceOf(defaultMap.getClass()); } @Test public void bindToMapWhenNoValueShouldReturnUnbound() { this.sources.add(new MockConfigurationPropertySource("faf.bar", "1")); - BindResult> result = this.binder.bind("foo", - STRING_INTEGER_MAP); + BindResult> result = this.binder.bind("foo", STRING_INTEGER_MAP); assertThat(result.isBound()).isFalse(); } @@ -315,8 +303,8 @@ public class MapBinderTests { source.put("foo.bbb.ccc.ddd", "BAR_BAZ"); source.put("foo.ccc.ddd.eee", "bazboo"); this.sources.add(source); - Map result = this.binder - .bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)).get(); + Map result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)) + .get(); assertThat(result).hasSize(3); assertThat(result).containsEntry("aaa.bbb.ccc", ExampleEnum.FOO_BAR); assertThat(result).containsEntry("bbb.ccc.ddd", ExampleEnum.BAR_BAZ); @@ -327,13 +315,11 @@ public class MapBinderTests { public void bindToMapWithPlaceholdersShouldBeGreedyForScalars() { StandardEnvironment environment = new StandardEnvironment(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "foo=boo"); - MockConfigurationPropertySource source = new MockConfigurationPropertySource( - "foo.aaa.bbb.ccc", "baz-${foo}"); + MockConfigurationPropertySource source = new MockConfigurationPropertySource("foo.aaa.bbb.ccc", "baz-${foo}"); this.sources.add(source); - this.binder = new Binder(this.sources, - new PropertySourcesPlaceholdersResolver(environment)); - Map result = this.binder - .bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)).get(); + this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); + Map result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)) + .get(); assertThat(result).containsEntry("aaa.bbb.ccc", ExampleEnum.BAZ_BOO); } @@ -352,49 +338,43 @@ public class MapBinderTests { Bindable> target = STRING_INTEGER_MAP; this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), - eq(Bindable.of(Integer.class)), any(), eq(1)); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), - eq(target), any(), isA(Map.class)); + ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(Integer.class)), + any(), eq(1)); + ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Map.class)); } @Test public void bindToMapStringArrayShouldTriggerOnSuccess() { - this.sources - .add(new MockConfigurationPropertySource("foo.bar", "a,b,c", "line1")); + this.sources.add(new MockConfigurationPropertySource("foo.bar", "a,b,c", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable> target = STRING_ARRAY_MAP; this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); ArgumentCaptor array = ArgumentCaptor.forClass(String[].class); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), - eq(Bindable.of(String[].class)), any(), array.capture()); + ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(String[].class)), + any(), array.capture()); assertThat(array.getValue()).containsExactly("a", "b", "c"); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), - eq(target), any(), isA(Map.class)); + ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Map.class)); } @Test public void bindToMapNonScalarCollectionShouldPopulateMap() { Bindable> valueType = Bindable.listOf(JavaBean.class); - Bindable>> target = getMapBindable(String.class, - valueType.getType()); + Bindable>> target = getMapBindable(String.class, valueType.getType()); MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar[0].value", "a"); source.put("foo.bar[1].value", "b"); source.put("foo.bar[2].value", "c"); this.sources.add(source); Map> map = this.binder.bind("foo", target).get(); - List values = map.get("bar").stream().map(JavaBean::getValue) - .collect(Collectors.toList()); + List values = map.get("bar").stream().map(JavaBean::getValue).collect(Collectors.toList()); assertThat(values).containsExactly("a", "b", "c"); } @Test public void bindToPropertiesShouldBeEquivalentToMapOfStringString() { - this.sources - .add(new MockConfigurationPropertySource("foo.bar.baz", "1", "line1")); + this.sources.add(new MockConfigurationPropertySource("foo.bar.baz", "1", "line1")); Bindable target = Bindable.of(Properties.class); Properties properties = this.binder.bind("foo", target).get(); assertThat(properties.getProperty("bar.baz")).isEqualTo("1"); @@ -402,8 +382,7 @@ public class MapBinderTests { @Test public void bindToMapShouldNotTreatClassWithStringConstructorAsScalar() { - this.sources.add( - new MockConfigurationPropertySource("foo.bar.pattern", "1", "line1")); + this.sources.add(new MockConfigurationPropertySource("foo.bar.pattern", "1", "line1")); Bindable> target = Bindable.mapOf(String.class, Foo.class); Map map = this.binder.bind("foo", target).get(); assertThat(map.get("bar").getPattern()).isEqualTo("1"); @@ -432,8 +411,7 @@ public class MapBinderTests { @Test public void bindToMapStringCollectionWithDotKeysShouldPreserveDot() { Bindable> valueType = Bindable.listOf(String.class); - Bindable>> target = getMapBindable(String.class, - valueType.getType()); + Bindable>> target = getMapBindable(String.class, valueType.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo.bar.baz[0]", "a"); mockSource.put("foo.bar.baz[1]", "b"); @@ -447,26 +425,22 @@ public class MapBinderTests { @Test public void bindToMapNonScalarCollectionWithDotKeysShouldBind() { Bindable> valueType = Bindable.listOf(JavaBean.class); - Bindable>> target = getMapBindable(String.class, - valueType.getType()); + Bindable>> target = getMapBindable(String.class, valueType.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo.bar.baz[0].value", "a"); mockSource.put("foo.bar.baz[1].value", "b"); mockSource.put("foo.bar.baz[2].value", "c"); this.sources.add(mockSource); Map> map = this.binder.bind("foo", target).get(); - List values = map.get("bar.baz").stream().map(JavaBean::getValue) - .collect(Collectors.toList()); + List values = map.get("bar.baz").stream().map(JavaBean::getValue).collect(Collectors.toList()); assertThat(values).containsExactly("a", "b", "c"); } @Test public void bindToListOfMaps() { Bindable> listBindable = Bindable.listOf(Integer.class); - Bindable>> mapBindable = getMapBindable(String.class, - listBindable.getType()); - Bindable>>> target = getListBindable( - mapBindable.getType()); + Bindable>> mapBindable = getMapBindable(String.class, listBindable.getType()); + Bindable>>> target = getListBindable(mapBindable.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo[0].a", "1,2,3"); mockSource.put("foo[1].b", "4,5,6"); @@ -479,8 +453,7 @@ public class MapBinderTests { @Test public void bindToMapWithNumberKeyAndCommaSeparated() { Bindable> listBindable = Bindable.listOf(String.class); - Bindable>> target = getMapBindable(Integer.class, - listBindable.getType()); + Bindable>> target = getMapBindable(Integer.class, listBindable.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo[0]", "a,b,c"); mockSource.put("foo[1]", "e,f,g"); @@ -493,8 +466,7 @@ public class MapBinderTests { @Test public void bindToMapWithNumberKeyAndIndexed() { Bindable> listBindable = Bindable.listOf(Integer.class); - Bindable>> target = getMapBindable(Integer.class, - listBindable.getType()); + Bindable>> target = getMapBindable(Integer.class, listBindable.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo[0][0]", "8"); mockSource.put("foo[0][1]", "9"); @@ -559,8 +531,7 @@ public class MapBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "a,b"); this.sources.add(source); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", STRING_STRING_MAP)); + assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", STRING_STRING_MAP)); } @Test @@ -570,8 +541,7 @@ public class MapBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.[java.lang.RuntimeException]", "bar"); this.sources.add(source); - Map map = this.binder - .bind("foo", Bindable.mapOf(Class.class, String.class)).get(); + Map map = this.binder.bind("foo", Bindable.mapOf(Class.class, String.class)).get(); assertThat(map).containsExactly(entry(RuntimeException.class, "bar")); } @@ -582,8 +552,7 @@ public class MapBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "java.lang.RuntimeException"); this.sources.add(source); - Map map = this.binder - .bind("foo", Bindable.mapOf(String.class, Class.class)).get(); + Map map = this.binder.bind("foo", Bindable.mapOf(String.class, Class.class)).get(); assertThat(map).containsExactly(entry("bar", RuntimeException.class)); } @@ -615,13 +584,9 @@ public class MapBinderTests { source.put("foo.values.e", "f"); this.sources.add(source); Map result = this.binder - .bind("foo.values", - STRING_STRING_MAP - .withExistingValue(Collections.singletonMap("a", "b"))) - .get(); + .bind("foo.values", STRING_STRING_MAP.withExistingValue(Collections.singletonMap("a", "b"))).get(); assertThat(result).hasSize(3); - assertThat(result).containsExactly(entry("a", "b"), entry("c", "d"), - entry("e", "f")); + assertThat(result).containsExactly(entry("a", "b"), entry("c", "d"), entry("e", "f")); } @Test @@ -629,16 +594,13 @@ public class MapBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values.a", "b"); this.sources.add(source); - BeanWithGetterException result = this.binder - .bind("foo", Bindable.of(BeanWithGetterException.class)).get(); + BeanWithGetterException result = this.binder.bind("foo", Bindable.of(BeanWithGetterException.class)).get(); assertThat(result.getValues()).containsExactly(entry("a", "b")); } - private Bindable> getMapBindable(Class keyGeneric, - ResolvableType valueType) { + private Bindable> getMapBindable(Class keyGeneric, ResolvableType valueType) { ResolvableType keyType = ResolvableType.forClass(keyGeneric); - return Bindable - .of(ResolvableType.forClassWithGenerics(Map.class, keyType, valueType)); + return Bindable.of(ResolvableType.forClassWithGenerics(Map.class, keyType, valueType)); } private Bindable> getListBindable(ResolvableType type) { @@ -690,8 +652,7 @@ public class MapBinderTests { @Override public Map convert(String s) { - return StringUtils.commaDelimitedListToSet(s).stream() - .collect(Collectors.toMap((k) -> k, (k) -> "")); + return StringUtils.commaDelimitedListToSet(s).stream().collect(Collectors.toMap((k) -> k, (k) -> "")); } } @@ -734,8 +695,7 @@ public class MapBinderTests { } - public static class MyCustomWithDefaultConstructorMap - extends HashMap { + public static class MyCustomWithDefaultConstructorMap extends HashMap { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java index e1aea4bdd9e..bc4227d4c49 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class PropertySourcesPlaceholdersResolverTests { @Test public void placeholderResolverIfEnvironmentNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new PropertySourcesPlaceholdersResolver((Environment) null)) + .isThrownBy(() -> new PropertySourcesPlaceholdersResolver((Environment) null)) .withMessageContaining("Environment must not be null"); } @@ -73,8 +72,7 @@ public class PropertySourcesPlaceholdersResolverTests { @Test public void resolveIfHelperPresentShouldUseIt() { MutablePropertySources sources = getPropertySources(); - TestPropertyPlaceholderHelper helper = new TestPropertyPlaceholderHelper("$<", - ">"); + TestPropertyPlaceholderHelper helper = new TestPropertyPlaceholderHelper("$<", ">"); this.resolver = new PropertySourcesPlaceholdersResolver(sources, helper); Object resolved = this.resolver.resolvePlaceholders("$"); assertThat(resolved).isEqualTo("hello world"); @@ -90,8 +88,7 @@ public class PropertySourcesPlaceholdersResolverTests { static class TestPropertyPlaceholderHelper extends PropertyPlaceholderHelper { - TestPropertyPlaceholderHelper(String placeholderPrefix, - String placeholderSuffix) { + TestPropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) { super(placeholderPrefix, placeholderSuffix); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java index fa03b3e67dc..6fe8601dd63 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,14 +53,13 @@ public class IgnoreErrorsBindHandlerTests { @Test public void bindWhenNotIgnoringErrorsShouldFail() { - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.binder.bind("example", Bindable.of(Example.class))); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))); } @Test public void bindWhenIgnoringErrorsShouldBind() { - Example bound = this.binder.bind("example", Bindable.of(Example.class), - new IgnoreErrorsBindHandler()).get(); + Example bound = this.binder.bind("example", Bindable.of(Example.class), new IgnoreErrorsBindHandler()).get(); assertThat(bound.getFoo()).isEqualTo(0); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java index 92fd98742ae..a78d0507fae 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { @Test public void bindWhenTopLevelContextAndExceptionIgnorableShouldNotFail() { - this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler()); + this.binder.bind("example", Bindable.of(Example.class), new IgnoreTopLevelConverterNotFoundBindHandler()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java index 2d71ff56215..a6d84ceed11 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java @@ -51,9 +51,7 @@ public class NoUnboundElementsBindHandlerTests { source.put("example.baz", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - Example bound = this.binder - .bind(ConfigurationPropertyName.of("example"), Bindable.of(Example.class)) - .get(); + Example bound = this.binder.bind(ConfigurationPropertyName.of("example"), Bindable.of(Example.class)).get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -63,8 +61,8 @@ public class NoUnboundElementsBindHandlerTests { source.put("example.foo", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - Example bound = this.binder.bind("example", Bindable.of(Example.class), - new NoUnboundElementsBindHandler()).get(); + Example bound = this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()) + .get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -75,9 +73,8 @@ public class NoUnboundElementsBindHandlerTests { source.put("example.baz", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), - new NoUnboundElementsBindHandler())) + assertThatExceptionOfType(BindException.class).isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) .satisfies((ex) -> assertThat(ex.getCause().getMessage()) .contains("The elements [example.baz] were left unbound")); } @@ -89,8 +86,8 @@ public class NoUnboundElementsBindHandlerTests { source.put("other.baz", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - Example bound = this.binder.bind("example", Bindable.of(Example.class), - new NoUnboundElementsBindHandler()).get(); + Example bound = this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()) + .get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -101,10 +98,9 @@ public class NoUnboundElementsBindHandlerTests { source.put("example.other", "baz"); this.sources.add(source); this.binder = new Binder(this.sources); - NoUnboundElementsBindHandler handler = new NoUnboundElementsBindHandler( - BindHandler.DEFAULT, ((configurationPropertySource) -> false)); - Example bound = this.binder.bind("example", Bindable.of(Example.class), handler) - .get(); + NoUnboundElementsBindHandler handler = new NoUnboundElementsBindHandler(BindHandler.DEFAULT, + ((configurationPropertySource) -> false)); + Example bound = this.binder.bind("example", Bindable.of(Example.class), handler).get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -119,8 +115,7 @@ public class NoUnboundElementsBindHandlerTests { this.sources.add(source2); this.binder = new Binder(this.sources); NoUnboundElementsBindHandler handler = new NoUnboundElementsBindHandler(); - ExampleWithList bound = this.binder - .bind("example", Bindable.of(ExampleWithList.class), handler).get(); + ExampleWithList bound = this.binder.bind("example", Bindable.of(ExampleWithList.class), handler).get(); assertThat(bound.getFoo()).containsExactly("bar"); } @@ -130,9 +125,8 @@ public class NoUnboundElementsBindHandlerTests { source.put("example.foo[0]", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), - new NoUnboundElementsBindHandler())) + assertThatExceptionOfType(BindException.class).isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) .satisfies((ex) -> assertThat(ex.getCause().getMessage()) .contains("The elements [example.foo[0]] were left unbound")); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java index 8383c086836..e642842609f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ public class PackagePrivateBeanBindingTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "999"); this.sources.add(source); - ExamplePackagePrivateBean bean = this.binder - .bind(this.name, Bindable.of(ExamplePackagePrivateBean.class)).get(); + ExamplePackagePrivateBean bean = this.binder.bind(this.name, Bindable.of(ExamplePackagePrivateBean.class)) + .get(); assertThat(bean.getBar()).isEqualTo(999); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java index e500a6f2e85..d7de2ebbb86 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ public class BindValidationExceptionTests { @Test public void createWhenValidationErrorsIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new BindValidationException(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new BindValidationException(null)) .withMessageContaining("ValidationErrors must not be null"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java index 52a080f18ba..5476ebe4e15 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,8 @@ public class OriginTrackedFieldErrorTests { @Test public void toStringShouldAddOrigin() { - assertThat(OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN).toString()).isEqualTo( - "Field error in object 'foo' on field 'bar': rejected value [null]" + assertThat(OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN).toString()) + .isEqualTo("Field error in object 'foo' on field 'bar': rejected value [null]" + "; codes []; arguments []; default message [faf]; origin afile"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java index df52f43c808..fe4307c4440 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java @@ -73,8 +73,7 @@ public class ValidationBindHandlerTests { @Test public void bindShouldBindWithoutHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); - ExampleValidatedBean bean = this.binder - .bind("foo", Bindable.of(ExampleValidatedBean.class)).get(); + ExampleValidatedBean bean = this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class)).get(); assertThat(bean.getAge()).isEqualTo(4); } @@ -82,8 +81,7 @@ public class ValidationBindHandlerTests { public void bindShouldFailWithHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class), this.handler)) + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler)) .withCauseInstanceOf(BindValidationException.class); } @@ -91,17 +89,16 @@ public class ValidationBindHandlerTests { public void bindShouldValidateNestedProperties() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", 4)); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) + .isThrownBy( + () -> this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) .withCauseInstanceOf(BindValidationException.class); } @Test public void bindShouldFailWithAccessToOrigin() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4, "file")); - BindValidationException cause = bindAndExpectValidationError( - () -> this.binder.bind(ConfigurationPropertyName.of("foo"), - Bindable.of(ExampleValidatedBean.class), this.handler)); + BindValidationException cause = bindAndExpectValidationError(() -> this.binder + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedBean.class), this.handler)); ObjectError objectError = cause.getValidationErrors().getAllErrors().get(0); assertThat(Origin.from(objectError).toString()).isEqualTo("file"); } @@ -113,21 +110,18 @@ public class ValidationBindHandlerTests { source.put("foo.nested.age", "4"); source.put("faf.bar", "baz"); this.sources.add(source); - BindValidationException cause = bindAndExpectValidationError( - () -> this.binder.bind(ConfigurationPropertyName.of("foo"), - Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); - Set boundProperties = cause.getValidationErrors() - .getBoundProperties(); - assertThat(boundProperties).extracting((p) -> p.getName().toString()) - .contains("foo.nested.age", "foo.nested.name"); + BindValidationException cause = bindAndExpectValidationError(() -> this.binder.bind( + ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); + Set boundProperties = cause.getValidationErrors().getBoundProperties(); + assertThat(boundProperties).extracting((p) -> p.getName().toString()).contains("foo.nested.age", + "foo.nested.name"); } @Test public void bindShouldFailWithAccessToName() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", "4")); - BindValidationException cause = bindAndExpectValidationError( - () -> this.binder.bind(ConfigurationPropertyName.of("foo"), - Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); + BindValidationException cause = bindAndExpectValidationError(() -> this.binder.bind( + ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); assertThat(cause.getValidationErrors().getName().toString()).isEqualTo("foo"); assertThat(cause.getMessage()).contains("nested.age"); } @@ -136,22 +130,17 @@ public class ValidationBindHandlerTests { public void bindShouldFailIfExistingValueIsInvalid() { ExampleValidatedBean existingValue = new ExampleValidatedBean(); BindValidationException cause = bindAndExpectValidationError( - () -> this.binder.bind(ConfigurationPropertyName.of("foo"), Bindable - .of(ExampleValidatedBean.class).withExistingValue(existingValue), - this.handler)); - FieldError fieldError = (FieldError) cause.getValidationErrors().getAllErrors() - .get(0); + () -> this.binder.bind(ConfigurationPropertyName.of("foo"), + Bindable.of(ExampleValidatedBean.class).withExistingValue(existingValue), this.handler)); + FieldError fieldError = (FieldError) cause.getValidationErrors().getAllErrors().get(0); assertThat(fieldError.getField()).isEqualTo("age"); } @Test public void bindShouldValidateWithoutAnnotation() { ExampleNonValidatedBean existingValue = new ExampleNonValidatedBean(); - bindAndExpectValidationError( - () -> this.binder.bind(ConfigurationPropertyName.of("foo"), - Bindable.of(ExampleNonValidatedBean.class) - .withExistingValue(existingValue), - this.handler)); + bindAndExpectValidationError(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), + Bindable.of(ExampleNonValidatedBean.class).withExistingValue(existingValue), this.handler)); } @Test @@ -162,8 +151,7 @@ public class ValidationBindHandlerTests { this.sources.add(source); ExampleValidatedBeanWithGetterException existingValue = new ExampleValidatedBeanWithGetterException(); this.binder.bind(ConfigurationPropertyName.of("foo"), - Bindable.of(ExampleValidatedBeanWithGetterException.class) - .withExistingValue(existingValue), + Bindable.of(ExampleValidatedBeanWithGetterException.class).withExistingValue(existingValue), this.handler); } @@ -172,11 +160,8 @@ public class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy( - () -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class) - .withExistingValue(bean), - this.handler)) + .isThrownBy(() -> this.binder.bind("foo", + Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) .withCauseInstanceOf(ConverterNotFoundException.class); } @@ -187,11 +172,8 @@ public class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy( - () -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class) - .withExistingValue(bean), - this.handler)) + .isThrownBy(() -> this.binder.bind("foo", + Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) .withCauseInstanceOf(BindValidationException.class); } @@ -301,8 +283,8 @@ public class ValidationBindHandlerTests { static class TestHandler extends AbstractBindHandler { @Override - public Object onFailure(ConfigurationPropertyName name, Bindable target, - BindContext context, Exception error) throws Exception { + public Object onFailure(ConfigurationPropertyName name, Bindable target, BindContext context, + Exception error) throws Exception { return null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java index 5d7e668cdb0..7b6f6739bc0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java @@ -42,38 +42,31 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException */ public class ValidationErrorsTests { - private static final ConfigurationPropertyName NAME = ConfigurationPropertyName - .of("foo"); + private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("foo"); @Test public void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), - Collections.emptyList())) + .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), Collections.emptyList())) .withMessageContaining("Name must not be null"); } @Test public void createWhenBoundPropertiesIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> new ValidationErrors(NAME, null, Collections.emptyList())) + assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, null, Collections.emptyList())) .withMessageContaining("BoundProperties must not be null"); } @Test public void createWhenErrorsIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> new ValidationErrors(NAME, Collections.emptySet(), null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, Collections.emptySet(), null)) .withMessageContaining("Errors must not be null"); } @Test public void getNameShouldReturnName() { ConfigurationPropertyName name = NAME; - ValidationErrors errors = new ValidationErrors(name, Collections.emptySet(), - Collections.emptyList()); + ValidationErrors errors = new ValidationErrors(name, Collections.emptySet(), Collections.emptyList()); assertThat((Object) errors.getName()).isEqualTo(name); } @@ -81,8 +74,7 @@ public class ValidationErrorsTests { public void getBoundPropertiesShouldReturnBoundProperties() { Set boundProperties = new LinkedHashSet<>(); boundProperties.add(new ConfigurationProperty(NAME, "foo", null)); - ValidationErrors errors = new ValidationErrors(NAME, boundProperties, - Collections.emptyList()); + ValidationErrors errors = new ValidationErrors(NAME, boundProperties, Collections.emptyList()); assertThat(errors.getBoundProperties()).isEqualTo(boundProperties); } @@ -90,8 +82,7 @@ public class ValidationErrorsTests { public void getErrorsShouldReturnErrors() { List allErrors = new ArrayList<>(); allErrors.add(new ObjectError("foo", "bar")); - ValidationErrors errors = new ValidationErrors(NAME, Collections.emptySet(), - allErrors); + ValidationErrors errors = new ValidationErrors(NAME, Collections.emptySet(), allErrors); assertThat(errors.getAllErrors()).isEqualTo(allErrors); } @@ -99,8 +90,7 @@ public class ValidationErrorsTests { public void iteratorShouldIterateErrors() { List allErrors = new ArrayList<>(); allErrors.add(new ObjectError("foo", "bar")); - ValidationErrors errors = new ValidationErrors(NAME, Collections.emptySet(), - allErrors); + ValidationErrors errors = new ValidationErrors(NAME, Collections.emptySet(), allErrors); assertThat(errors.iterator()).toIterable().containsExactlyElementsOf(allErrors); } @@ -115,8 +105,8 @@ public class ValidationErrorsTests { boundProperties.add(new ConfigurationProperty(name2, "boot", origin2)); List allErrors = new ArrayList<>(); allErrors.add(new FieldError("objectname", "bar", "message")); - ValidationErrors errors = new ValidationErrors( - ConfigurationPropertyName.of("foo.baz"), boundProperties, allErrors); + ValidationErrors errors = new ValidationErrors(ConfigurationPropertyName.of("foo.baz"), boundProperties, + allErrors); assertThat(Origin.from(errors.getAllErrors().get(0))).isEqualTo(origin2); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/scan/valid/ConfigurationPropertiesScanConfiguration.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/scan/valid/ConfigurationPropertiesScanConfiguration.java index 06da868fe10..0da07c2f161 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/scan/valid/ConfigurationPropertiesScanConfiguration.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/scan/valid/ConfigurationPropertiesScanConfiguration.java @@ -29,14 +29,12 @@ import org.springframework.boot.context.properties.scan.valid.b.BScanConfigurati public class ConfigurationPropertiesScanConfiguration { @ConfigurationPropertiesScan - @EnableConfigurationProperties({ - ConfigurationPropertiesScanConfiguration.FooProperties.class }) + @EnableConfigurationProperties({ ConfigurationPropertiesScanConfiguration.FooProperties.class }) public static class TestConfiguration { } - @ConfigurationPropertiesScan( - basePackages = "org.springframework.boot.context.properties.scan.valid.a", + @ConfigurationPropertiesScan(basePackages = "org.springframework.boot.context.properties.scan.valid.a", basePackageClasses = BScanConfiguration.class) public static class DifferentPackageConfiguration { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AbstractPropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AbstractPropertyMapperTests.java index 098a76ed247..a66fb7eff85 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AbstractPropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AbstractPropertyMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ public abstract class AbstractPropertyMapperTests { protected abstract PropertyMapper getMapper(); protected final Iterator namesFromString(String name) { - return Arrays.stream(getMapper().map(name)) - .map((mapping) -> mapping.getConfigurationPropertyName().toString()) + return Arrays.stream(getMapper().map(name)).map((mapping) -> mapping.getConfigurationPropertyName().toString()) .iterator(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java index ea0c6e38a08..7c42a0d6d07 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,59 +57,45 @@ public class AliasedConfigurationPropertySourceTests { @Test public void containsDescendantOfWhenSourceReturnsUnknownShouldReturnUnknown() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.UNKNOWN); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.UNKNOWN); ConfigurationPropertySource aliased = source .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); - assertThat(aliased.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test public void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.PRESENT); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.PRESENT); given(source.containsDescendantOf(ConfigurationPropertyName.of("bar"))) .willReturn(ConfigurationPropertyState.UNKNOWN); ConfigurationPropertySource aliased = source .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); - assertThat(aliased.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.PRESENT); + assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); } @Test public void containsDescendantOfWhenAllAreAbsentShouldReturnAbsent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.ABSENT); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.ABSENT); given(source.containsDescendantOf(ConfigurationPropertyName.of("bar"))) .willReturn(ConfigurationPropertyState.ABSENT); - ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); - assertThat(aliased.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.ABSENT); + ConfigurationPropertySource aliased = source.withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); + assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); } @Test public void containsDescendantOfWhenAnyIsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.ABSENT); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.ABSENT); given(source.containsDescendantOf(ConfigurationPropertyName.of("bar"))) .willReturn(ConfigurationPropertyState.PRESENT); - ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); - assertThat(aliased.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.PRESENT); + ConfigurationPropertySource aliased = source.withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); + assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); } @Test @@ -123,8 +109,7 @@ public class AliasedConfigurationPropertySourceTests { } private Object getValue(ConfigurationPropertySource source, String name) { - ConfigurationProperty property = source - .getConfigurationProperty(ConfigurationPropertyName.of(name)); + ConfigurationProperty property = source.getConfigurationProperty(ConfigurationPropertyName.of(name)); return (property != null) ? property.getValue() : null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java index 0470f6b015f..fbd6074fc18 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class AliasedIterableConfigurationPropertySourceTests - extends AliasedConfigurationPropertySourceTests { +public class AliasedIterableConfigurationPropertySourceTests extends AliasedConfigurationPropertySourceTests { @Test public void streamShouldIncludeAliases() { @@ -36,10 +35,8 @@ public class AliasedIterableConfigurationPropertySourceTests source.put("foo.baz", "biff"); IterableConfigurationPropertySource aliased = source .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); - assertThat(aliased.stream()).containsExactly( - ConfigurationPropertyName.of("foo.bar"), - ConfigurationPropertyName.of("foo.bar1"), - ConfigurationPropertyName.of("foo.baz")); + assertThat(aliased.stream()).containsExactly(ConfigurationPropertyName.of("foo.bar"), + ConfigurationPropertyName.of("foo.bar1"), ConfigurationPropertyName.of("foo.baz")); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java index 19b43372d02..d1a8b438aee 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,18 +31,15 @@ public class ConfigurationPropertyNameAliasesTests { @Test public void createWithStringWhenNullNameShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ConfigurationPropertyNameAliases((String) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationPropertyNameAliases((String) null)) .withMessageContaining("Name must not be null"); } @Test public void createWithStringShouldAddMapping() { - ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases( - "foo", "bar", "baz"); + ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), - ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -51,8 +48,7 @@ public class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), - ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -60,18 +56,16 @@ public class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), - ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test public void addAliasesFromNameShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); - aliases.addAliases(ConfigurationPropertyName.of("foo"), - ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + aliases.addAliases(ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), + ConfigurationPropertyName.of("baz")); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), - ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -80,8 +74,7 @@ public class ConfigurationPropertyNameAliasesTests { aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), - ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -113,8 +106,7 @@ public class ConfigurationPropertyNameAliasesTests { public void getNameForAliasWhenNotMappedShouldReturnNull() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); - assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("baz"))) - .isNull(); + assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("baz"))).isNull(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java index a6a8250a8bc..7ae4f064025 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java @@ -40,37 +40,32 @@ public class ConfigurationPropertyNameTests { @Test public void ofNameShouldNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyName.of(null)) + assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.of(null)) .withMessageContaining("Name must not be null"); } @Test public void ofNameShouldNotStartWithDash() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("-foo")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("-foo")).withMessageContaining("is not valid"); } @Test public void ofNameShouldNotStartWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of(".foo")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of(".foo")).withMessageContaining("is not valid"); } @Test public void ofNameShouldNotEndWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo.")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo.")).withMessageContaining("is not valid"); } @Test public void ofNameShouldNotContainUppercase() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("fOo")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("fOo")).withMessageContaining("is not valid"); } @Test @@ -78,8 +73,8 @@ public class ConfigurationPropertyNameTests { String invalid = "_@$%*+=':;"; for (char c : invalid.toCharArray()) { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)).satisfies( - (ex) -> assertThat(ex.getMessage()).contains("is not valid")); + .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)) + .satisfies((ex) -> assertThat(ex.getMessage()).contains("is not valid")); } } @@ -158,22 +153,19 @@ public class ConfigurationPropertyNameTests { @Test public void ofNameWhenMissingCloseBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("[bar")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("[bar")).withMessageContaining("is not valid"); } @Test public void ofNameWhenMissingOpenBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("bar]")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("bar]")).withMessageContaining("is not valid"); } @Test public void ofNameWhenMultipleMismatchedBrackets() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")).withMessageContaining("is not valid"); } @Test @@ -187,8 +179,7 @@ public class ConfigurationPropertyNameTests { @Test public void ofNameWithWhitespaceInName() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")) - .withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")).withMessageContaining("is not valid"); } @Test @@ -220,23 +211,20 @@ public class ConfigurationPropertyNameTests { @Test public void adaptWhenNameIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyName.adapt(null, '.')) + assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.adapt(null, '.')) .withMessageContaining("Name must not be null"); } @Test public void adaptWhenElementValueProcessorIsNullShouldAdapt() { - ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo", '.', - null); + ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo", '.', null); assertThat(name.toString()).isEqualTo("foo"); } @Test public void adaptShouldCreateName() { ConfigurationPropertyName expected = ConfigurationPropertyName.of("foo.bar.baz"); - ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo.bar.baz", - '.'); + ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo.bar.baz", '.'); assertThat(name).isEqualTo(expected); } @@ -272,8 +260,8 @@ public class ConfigurationPropertyNameTests { @Test public void adaptShouldUseElementValueProcessor() { - ConfigurationPropertyName name = ConfigurationPropertyName.adapt("FOO_THE-BAR", - '_', (c) -> c.toString().replace("-", "")); + ConfigurationPropertyName name = ConfigurationPropertyName.adapt("FOO_THE-BAR", '_', + (c) -> c.toString().replace("-", "")); assertThat(name.toString()).isEqualTo("foo.thebar"); } @@ -314,16 +302,13 @@ public class ConfigurationPropertyNameTests { @Test public void isLastElementIndexedWhenIndexedShouldReturnTrue() { - assertThat(ConfigurationPropertyName.of("foo[0]").isLastElementIndexed()) - .isTrue(); + assertThat(ConfigurationPropertyName.of("foo[0]").isLastElementIndexed()).isTrue(); } @Test public void isLastElementIndexedWhenNotIndexedShouldReturnFalse() { - assertThat(ConfigurationPropertyName.of("foo.bar").isLastElementIndexed()) - .isFalse(); - assertThat(ConfigurationPropertyName.of("foo[0].bar").isLastElementIndexed()) - .isFalse(); + assertThat(ConfigurationPropertyName.of("foo.bar").isLastElementIndexed()).isFalse(); + assertThat(ConfigurationPropertyName.of("foo[0].bar").isLastElementIndexed()).isFalse(); } @Test @@ -361,12 +346,9 @@ public class ConfigurationPropertyNameTests { assertThat(getElements("foo.[0]", Form.ORIGINAL)).containsExactly("foo", "0"); assertThat(getElements("foo[baz]", Form.ORIGINAL)).containsExactly("foo", "baz"); assertThat(getElements("foo.baz", Form.ORIGINAL)).containsExactly("foo", "baz"); - assertThat(getElements("foo[baz].bar", Form.ORIGINAL)).containsExactly("foo", - "baz", "bar"); - assertThat(getElements("foo.baz.bar", Form.ORIGINAL)).containsExactly("foo", - "baz", "bar"); - assertThat(getElements("foo.baz-bar", Form.ORIGINAL)).containsExactly("foo", - "baz-bar"); + assertThat(getElements("foo[baz].bar", Form.ORIGINAL)).containsExactly("foo", "baz", "bar"); + assertThat(getElements("foo.baz.bar", Form.ORIGINAL)).containsExactly("foo", "baz", "bar"); + assertThat(getElements("foo.baz-bar", Form.ORIGINAL)).containsExactly("foo", "baz-bar"); } @Test @@ -376,12 +358,9 @@ public class ConfigurationPropertyNameTests { assertThat(getElements("foo.[0]", Form.UNIFORM)).containsExactly("foo", "0"); assertThat(getElements("foo[baz]", Form.UNIFORM)).containsExactly("foo", "baz"); assertThat(getElements("foo.baz", Form.UNIFORM)).containsExactly("foo", "baz"); - assertThat(getElements("foo[baz].bar", Form.UNIFORM)).containsExactly("foo", - "baz", "bar"); - assertThat(getElements("foo.baz.bar", Form.UNIFORM)).containsExactly("foo", "baz", - "bar"); - assertThat(getElements("foo.baz-bar", Form.UNIFORM)).containsExactly("foo", - "bazbar"); + assertThat(getElements("foo[baz].bar", Form.UNIFORM)).containsExactly("foo", "baz", "bar"); + assertThat(getElements("foo.baz.bar", Form.UNIFORM)).containsExactly("foo", "baz", "bar"); + assertThat(getElements("foo.baz-bar", Form.UNIFORM)).containsExactly("foo", "bazbar"); } private List getElements(String name, Form form) { @@ -397,10 +376,8 @@ public class ConfigurationPropertyNameTests { public void getNumberOfElementsShouldReturnNumberOfElement() { assertThat(ConfigurationPropertyName.of("").getNumberOfElements()).isEqualTo(0); assertThat(ConfigurationPropertyName.of("x").getNumberOfElements()).isEqualTo(1); - assertThat(ConfigurationPropertyName.of("x.y").getNumberOfElements()) - .isEqualTo(2); - assertThat(ConfigurationPropertyName.of("x[0].y").getNumberOfElements()) - .isEqualTo(3); + assertThat(ConfigurationPropertyName.of("x.y").getNumberOfElements()).isEqualTo(2); + assertThat(ConfigurationPropertyName.of("x[0].y").getNumberOfElements()).isEqualTo(3); } @Test @@ -411,8 +388,7 @@ public class ConfigurationPropertyNameTests { @Test public void appendWhenIndexedShouldAppendWithBrackets() { - ConfigurationPropertyName name = ConfigurationPropertyName.of("foo") - .append("[bar]"); + ConfigurationPropertyName name = ConfigurationPropertyName.of("foo").append("[bar]"); assertThat(name.isLastElementIndexed()).isTrue(); assertThat(name.toString()).isEqualTo("foo[bar]"); } @@ -426,8 +402,7 @@ public class ConfigurationPropertyNameTests { @Test public void appendWhenElementNameMultiDotShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("bar.baz")) + assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.of("foo").append("bar.baz")) .withMessageContaining("Element value 'bar.baz' must be a single item"); } @@ -473,8 +448,7 @@ public class ConfigurationPropertyNameTests { @Test public void isParentOfWhenGrandparentShouldReturnFalse() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertyName grandchild = ConfigurationPropertyName - .of("foo.bar.baz"); + ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.isParentOf(grandchild)).isFalse(); assertThat(grandchild.isParentOf(name)).isFalse(); } @@ -506,8 +480,7 @@ public class ConfigurationPropertyNameTests { @Test public void isAncestorOfWhenGrandparentShouldReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertyName grandchild = ConfigurationPropertyName - .of("foo.bar.baz"); + ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.isAncestorOf(grandchild)).isTrue(); assertThat(grandchild.isAncestorOf(name)).isFalse(); } @@ -515,8 +488,7 @@ public class ConfigurationPropertyNameTests { @Test public void isAncestorOfWhenRootShouldReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of(""); - ConfigurationPropertyName grandchild = ConfigurationPropertyName - .of("foo.bar.baz"); + ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.isAncestorOf(grandchild)).isTrue(); assertThat(grandchild.isAncestorOf(name)).isFalse(); } @@ -531,15 +503,13 @@ public class ConfigurationPropertyNameTests { names.add(ConfigurationPropertyName.of("foo.baz")); names.add(ConfigurationPropertyName.of("foo")); Collections.sort(names); - assertThat(names.stream().map(ConfigurationPropertyName::toString) - .collect(Collectors.toList())).containsExactly("foo", "foo[2]", "foo[10]", - "foo.bar", "foo.bard", "foo.baz"); + assertThat(names.stream().map(ConfigurationPropertyName::toString).collect(Collectors.toList())) + .containsExactly("foo", "foo[2]", "foo[10]", "foo.bar", "foo.bard", "foo.baz"); } @Test public void compareDifferentLengthsShouldSortNames() { - ConfigurationPropertyName name = ConfigurationPropertyName - .of("spring.resources.chain.strategy.content"); + ConfigurationPropertyName name = ConfigurationPropertyName.of("spring.resources.chain.strategy.content"); ConfigurationPropertyName other = ConfigurationPropertyName .of("spring.resources.chain.strategy.content.enabled"); assertThat(name.compareTo(other)).isLessThan(0); @@ -547,8 +517,7 @@ public class ConfigurationPropertyNameTests { @Test public void toStringShouldBeLowerCaseDashed() { - ConfigurationPropertyName name = ConfigurationPropertyName.adapt("fOO.b_-a-r", - '.'); + ConfigurationPropertyName name = ConfigurationPropertyName.adapt("fOO.b_-a-r", '.'); assertThat(name.toString()).isEqualTo("foo.b-a-r"); } @@ -599,38 +568,31 @@ public class ConfigurationPropertyNameTests { public void equalsWhenStartsWith() { // gh-14665 ConfigurationPropertyName n1 = ConfigurationPropertyName.of("my.sources[0].xame"); - ConfigurationPropertyName n2 = ConfigurationPropertyName - .of("my.sources[0].xamespace"); + ConfigurationPropertyName n2 = ConfigurationPropertyName.of("my.sources[0].xamespace"); assertThat(n1).isNotEqualTo(n2); } @Test public void equalsWhenStartsWithOfAdaptedName() { // gh-15152 - ConfigurationPropertyName n1 = ConfigurationPropertyName - .adapt("example.mymap.ALPHA", '.'); - ConfigurationPropertyName n2 = ConfigurationPropertyName - .adapt("example.mymap.ALPHA_BRAVO", '.'); + ConfigurationPropertyName n1 = ConfigurationPropertyName.adapt("example.mymap.ALPHA", '.'); + ConfigurationPropertyName n2 = ConfigurationPropertyName.adapt("example.mymap.ALPHA_BRAVO", '.'); assertThat(n1).isNotEqualTo(n2); } @Test public void equalsWhenStartsWithOfAdaptedNameOfIllegalChars() { // gh-15152 - ConfigurationPropertyName n1 = ConfigurationPropertyName - .adapt("example.mymap.ALPH!", '.'); - ConfigurationPropertyName n2 = ConfigurationPropertyName - .adapt("example.mymap.ALPHA!BRAVO", '.'); + ConfigurationPropertyName n1 = ConfigurationPropertyName.adapt("example.mymap.ALPH!", '.'); + ConfigurationPropertyName n2 = ConfigurationPropertyName.adapt("example.mymap.ALPHA!BRAVO", '.'); assertThat(n1).isNotEqualTo(n2); } @Test public void equalsWhenNameStartsTheSameUsingDashedCompare() { // gh-16855 - ConfigurationPropertyName n1 = ConfigurationPropertyName - .of("management.metrics.web.server.auto-time-request"); - ConfigurationPropertyName n2 = ConfigurationPropertyName - .of("management.metrics.web.server.auto-time-requests"); + ConfigurationPropertyName n1 = ConfigurationPropertyName.of("management.metrics.web.server.auto-time-request"); + ConfigurationPropertyName n2 = ConfigurationPropertyName.of("management.metrics.web.server.auto-time-requests"); assertThat(n1).isNotEqualTo(n2); assertThat(n2).isNotEqualTo(n1); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java index 060e0002355..d392d0c0c84 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,15 +38,13 @@ public class ConfigurationPropertySourcesPropertySourceTests { @Test public void getPropertyShouldReturnValue() { - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "baz")); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); assertThat(this.propertySource.getProperty("foo.bar")).isEqualTo("baz"); } @Test public void getPropertyWhenNameIsNotValidShouldReturnNull() { - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "baz")); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); assertThat(this.propertySource.getProperty("FOO.B-A-R")).isNull(); assertThat(this.propertySource.getProperty("FOO.B A R")).isNull(); assertThat(this.propertySource.getProperty(".foo.bar")).isNull(); @@ -54,32 +52,26 @@ public class ConfigurationPropertySourcesPropertySourceTests { @Test public void getPropertyWhenMultipleShouldReturnFirst() { - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "baz")); - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "bill")); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "bill")); assertThat(this.propertySource.getProperty("foo.bar")).isEqualTo("baz"); } @Test public void getPropertyWhenNoneShouldReturnFirst() { - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "baz")); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); assertThat(this.propertySource.getProperty("foo.foo")).isNull(); } @Test public void getPropertyOriginShouldReturnOrigin() { - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "baz", "line1")); - assertThat(this.propertySource.getOrigin("foo.bar").toString()) - .isEqualTo("line1"); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz", "line1")); + assertThat(this.propertySource.getOrigin("foo.bar").toString()).isEqualTo("line1"); } @Test public void getPropertyOriginWhenMissingShouldReturnNull() { - this.configurationSources - .add(new MockConfigurationPropertySource("foo.bar", "baz", "line1")); + this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz", "line1")); assertThat(this.propertySource.getOrigin("foo.foo")).isNull(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java index 03e81c78a28..d30480d9364 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java @@ -45,10 +45,8 @@ public class ConfigurationPropertySourcesTests { public void attachShouldAddAdapterAtBeginning() { ConfigurableEnvironment environment = new StandardEnvironment(); MutablePropertySources sources = environment.getPropertySources(); - sources.addLast(new SystemEnvironmentPropertySource("system", - Collections.singletonMap("SERVER_PORT", "1234"))); - sources.addLast(new MapPropertySource("config", - Collections.singletonMap("server.port", "4568"))); + sources.addLast(new SystemEnvironmentPropertySource("system", Collections.singletonMap("SERVER_PORT", "1234"))); + sources.addLast(new MapPropertySource("config", Collections.singletonMap("server.port", "4568"))); int size = sources.size(); ConfigurationPropertySources.attach(environment); assertThat(sources.size()).isEqualTo(size + 1); @@ -62,8 +60,8 @@ public class ConfigurationPropertySourcesTests { ConfigurationPropertySources.attach(parent); ConfigurableEnvironment child = new StandardEnvironment(); child.merge(parent); - child.getPropertySources().addLast(new MapPropertySource("config", - Collections.singletonMap("my.example_property", "1234"))); + child.getPropertySources() + .addLast(new MapPropertySource("config", Collections.singletonMap("my.example_property", "1234"))); ConfigurationPropertySources.attach(child); assertThat(child.getProperty("my.example-property")).isEqualTo("1234"); } @@ -78,8 +76,7 @@ public class ConfigurationPropertySourcesTests { public void getWhenAttachedShouldReturnAttached() { ConfigurableEnvironment environment = new StandardEnvironment(); MutablePropertySources sources = environment.getPropertySources(); - sources.addFirst( - new MapPropertySource("test", Collections.singletonMap("a", "b"))); + sources.addFirst(new MapPropertySource("test", Collections.singletonMap("a", "b"))); int expectedSize = sources.size(); ConfigurationPropertySources.attach(environment); assertThat(ConfigurationPropertySources.get(environment)).hasSize(expectedSize); @@ -99,21 +96,17 @@ public class ConfigurationPropertySourcesTests { @Test public void fromPropertySourceShouldReturnSpringConfigurationPropertySource() { - PropertySource source = new MapPropertySource("foo", - Collections.singletonMap("foo", "bar")); - ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources - .from(source).iterator().next(); - assertThat(configurationPropertySource) - .isInstanceOf(SpringConfigurationPropertySource.class); + PropertySource source = new MapPropertySource("foo", Collections.singletonMap("foo", "bar")); + ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources.from(source).iterator() + .next(); + assertThat(configurationPropertySource).isInstanceOf(SpringConfigurationPropertySource.class); } @Test public void fromPropertySourceShouldFlattenPropertySources() { StandardEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addFirst( - new MapPropertySource("foo", Collections.singletonMap("foo", "bar"))); - environment.getPropertySources().addFirst( - new MapPropertySource("far", Collections.singletonMap("far", "far"))); + environment.getPropertySources().addFirst(new MapPropertySource("foo", Collections.singletonMap("foo", "bar"))); + environment.getPropertySources().addFirst(new MapPropertySource("far", Collections.singletonMap("far", "far"))); MutablePropertySources sources = new MutablePropertySources(); sources.addFirst(new PropertySource("env", environment) { @@ -123,10 +116,8 @@ public class ConfigurationPropertySourcesTests { } }); - sources.addLast( - new MapPropertySource("baz", Collections.singletonMap("baz", "barf"))); - Iterable configurationSources = ConfigurationPropertySources - .from(sources); + sources.addLast(new MapPropertySource("baz", Collections.singletonMap("baz", "barf"))); + Iterable configurationSources = ConfigurationPropertySources.from(sources); assertThat(configurationSources.iterator()).toIterable().hasSize(5); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java index fff90b6d700..ef83463ea3e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,31 +34,28 @@ public class ConfigurationPropertyStateTests { @Test public void searchWhenIterableIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyState.search(null, (e) -> true)) + assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyState.search(null, (e) -> true)) .withMessageContaining("Source must not be null"); } @Test public void searchWhenPredicateIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> ConfigurationPropertyState.search(Collections.emptyList(), null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> ConfigurationPropertyState.search(Collections.emptyList(), null)) .withMessageContaining("Predicate must not be null"); } @Test public void searchWhenContainsItemShouldReturnPresent() { List source = Arrays.asList("a", "b", "c"); - ConfigurationPropertyState result = ConfigurationPropertyState.search(source, - "b"::equals); + ConfigurationPropertyState result = ConfigurationPropertyState.search(source, "b"::equals); assertThat(result).isEqualTo(ConfigurationPropertyState.PRESENT); } @Test public void searchWhenContainsNoItemShouldReturnAbsent() { List source = Arrays.asList("a", "x", "c"); - ConfigurationPropertyState result = ConfigurationPropertyState.search(source, - "b"::equals); + ConfigurationPropertyState result = ConfigurationPropertyState.search(source, "b"::equals); assertThat(result).isEqualTo(ConfigurationPropertyState.ABSENT); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java index 79ea3f96071..b7922f412a3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,20 +33,17 @@ import static org.mockito.Mockito.mock; */ public class ConfigurationPropertyTests { - private static final ConfigurationPropertyName NAME = ConfigurationPropertyName - .of("foo"); + private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("foo"); @Test public void createWhenNameIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ConfigurationProperty(null, "bar", null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(null, "bar", null)) .withMessageContaining("Name must not be null"); } @Test public void createWhenValueIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ConfigurationProperty(NAME, null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(NAME, null, null)) .withMessageContaining("Value must not be null"); } @@ -71,17 +68,12 @@ public class ConfigurationPropertyTests { @Test public void equalsAndHashCode() { - ConfigurationProperty property1 = new ConfigurationProperty( - ConfigurationPropertyName.of("foo"), "bar", null); - ConfigurationProperty property2 = new ConfigurationProperty( - ConfigurationPropertyName.of("foo"), "bar", null); - ConfigurationProperty property3 = new ConfigurationProperty( - ConfigurationPropertyName.of("foo"), "baz", null); - ConfigurationProperty property4 = new ConfigurationProperty( - ConfigurationPropertyName.of("baz"), "bar", null); + ConfigurationProperty property1 = new ConfigurationProperty(ConfigurationPropertyName.of("foo"), "bar", null); + ConfigurationProperty property2 = new ConfigurationProperty(ConfigurationPropertyName.of("foo"), "bar", null); + ConfigurationProperty property3 = new ConfigurationProperty(ConfigurationPropertyName.of("foo"), "baz", null); + ConfigurationProperty property4 = new ConfigurationProperty(ConfigurationPropertyName.of("baz"), "bar", null); assertThat(property1.hashCode()).isEqualTo(property2.hashCode()); - assertThat(property1).isEqualTo(property2).isNotEqualTo(property3) - .isNotEqualTo(property4); + assertThat(property1).isEqualTo(property2).isNotEqualTo(property3).isNotEqualTo(property4); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java index db171249b83..b52fcd0b27d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java @@ -36,45 +36,28 @@ public class DefaultPropertyMapperTests extends AbstractPropertyMapperTests { @Test public void mapFromStringShouldReturnBestGuess() { assertThat(namesFromString("server")).toIterable().containsExactly("server"); - assertThat(namesFromString("server.port")).toIterable() - .containsExactly("server.port"); + assertThat(namesFromString("server.port")).toIterable().containsExactly("server.port"); assertThat(namesFromString("host[0]")).toIterable().containsExactly("host[0]"); - assertThat(namesFromString("host[0][1]")).toIterable() - .containsExactly("host[0][1]"); - assertThat(namesFromString("host[0].name")).toIterable() - .containsExactly("host[0].name"); - assertThat(namesFromString("host.f00.name")).toIterable() - .containsExactly("host.f00.name"); - assertThat(namesFromString("my.host-name")).toIterable() - .containsExactly("my.host-name"); - assertThat(namesFromString("my.hostName")).toIterable() - .containsExactly("my.hostname"); - assertThat(namesFromString("my.HOST_NAME")).toIterable() - .containsExactly("my.hostname"); - assertThat(namesFromString("s[!@#$%^&*()=+]e-rVeR")).toIterable() - .containsExactly("s[!@#$%^&*()=+].e-rver"); - assertThat(namesFromString("host[FOO].name")).toIterable() - .containsExactly("host[FOO].name"); + assertThat(namesFromString("host[0][1]")).toIterable().containsExactly("host[0][1]"); + assertThat(namesFromString("host[0].name")).toIterable().containsExactly("host[0].name"); + assertThat(namesFromString("host.f00.name")).toIterable().containsExactly("host.f00.name"); + assertThat(namesFromString("my.host-name")).toIterable().containsExactly("my.host-name"); + assertThat(namesFromString("my.hostName")).toIterable().containsExactly("my.hostname"); + assertThat(namesFromString("my.HOST_NAME")).toIterable().containsExactly("my.hostname"); + assertThat(namesFromString("s[!@#$%^&*()=+]e-rVeR")).toIterable().containsExactly("s[!@#$%^&*()=+].e-rver"); + assertThat(namesFromString("host[FOO].name")).toIterable().containsExactly("host[FOO].name"); } @Test public void mapFromConfigurationShouldReturnBestGuess() { - assertThat(namesFromConfiguration("server")).toIterable() - .containsExactly("server"); - assertThat(namesFromConfiguration("server.port")).toIterable() - .containsExactly("server.port"); - assertThat(namesFromConfiguration("host[0]")).toIterable() - .containsExactly("host[0]"); - assertThat(namesFromConfiguration("host[0][1]")).toIterable() - .containsExactly("host[0][1]"); - assertThat(namesFromConfiguration("host[0].name")).toIterable() - .containsExactly("host[0].name"); - assertThat(namesFromConfiguration("host.f00.name")).toIterable() - .containsExactly("host.f00.name"); - assertThat(namesFromConfiguration("my.host-name")).toIterable() - .containsExactly("my.host-name"); - assertThat(namesFromConfiguration("host[FOO].name")).toIterable() - .containsExactly("host[FOO].name"); + assertThat(namesFromConfiguration("server")).toIterable().containsExactly("server"); + assertThat(namesFromConfiguration("server.port")).toIterable().containsExactly("server.port"); + assertThat(namesFromConfiguration("host[0]")).toIterable().containsExactly("host[0]"); + assertThat(namesFromConfiguration("host[0][1]")).toIterable().containsExactly("host[0][1]"); + assertThat(namesFromConfiguration("host[0].name")).toIterable().containsExactly("host[0].name"); + assertThat(namesFromConfiguration("host.f00.name")).toIterable().containsExactly("host.f00.name"); + assertThat(namesFromConfiguration("my.host-name")).toIterable().containsExactly("my.host-name"); + assertThat(namesFromConfiguration("host[FOO].name")).toIterable().containsExactly("host[FOO].name"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java index 2e5fd5187ab..1794eeaeab2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,16 +36,16 @@ public class FilteredConfigurationPropertiesSourceTests { @Test public void createWhenSourceIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) .withMessageContaining("Source must not be null"); } @Test public void createWhenFilterIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FilteredConfigurationPropertiesSource( - new MockConfigurationPropertySource(), null)) + .isThrownBy( + () -> new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null)) .withMessageContaining("Filter must not be null"); } @@ -57,45 +57,35 @@ public class FilteredConfigurationPropertiesSourceTests { assertThat(source.getConfigurationProperty(name).getValue()).isEqualTo("1"); assertThat(filtered.getConfigurationProperty(name).getValue()).isEqualTo("1"); ConfigurationPropertyName bracketName = ConfigurationPropertyName.of("a[1]"); - assertThat(source.getConfigurationProperty(bracketName).getValue()) - .isEqualTo("2"); + assertThat(source.getConfigurationProperty(bracketName).getValue()).isEqualTo("2"); assertThat(filtered.getConfigurationProperty(bracketName)).isNull(); } @Test public void containsDescendantOfWhenSourceReturnsEmptyShouldReturnEmpty() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.UNKNOWN); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.UNKNOWN); ConfigurationPropertySource filtered = source.filter((n) -> true); - assertThat(filtered.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + assertThat(filtered.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test public void containsDescendantOfWhenSourceReturnsFalseShouldReturnFalse() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.ABSENT); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.ABSENT); ConfigurationPropertySource filtered = source.filter((n) -> true); - assertThat(filtered.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.ABSENT); + assertThat(filtered.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); } @Test public void containsDescendantOfWhenSourceReturnsTrueShouldReturnEmpty() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); - ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, - Answers.CALLS_REAL_METHODS); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.PRESENT); + ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); + given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.PRESENT); ConfigurationPropertySource filtered = source.filter((n) -> true); - assertThat(filtered.containsDescendantOf(name)) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + assertThat(filtered.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.UNKNOWN); } protected final ConfigurationPropertySource createTestSource() { @@ -108,8 +98,7 @@ public class FilteredConfigurationPropertiesSourceTests { return convertSource(source); } - protected ConfigurationPropertySource convertSource( - MockConfigurationPropertySource source) { + protected ConfigurationPropertySource convertSource(MockConfigurationPropertySource source) { return source.nonIterable(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java index 867096572d5..bbc309f48da 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java @@ -26,21 +26,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class FilteredIterableConfigurationPropertiesSourceTests - extends FilteredConfigurationPropertiesSourceTests { +public class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigurationPropertiesSourceTests { @Test public void iteratorShouldFilterNames() { MockConfigurationPropertySource source = (MockConfigurationPropertySource) createTestSource(); IterableConfigurationPropertySource filtered = source.filter(this::noBrackets); - assertThat(filtered.iterator()).toIterable() - .extracting(ConfigurationPropertyName::toString) + assertThat(filtered.iterator()).toIterable().extracting(ConfigurationPropertyName::toString) .containsExactly("a", "b", "c"); } @Override - protected ConfigurationPropertySource convertSource( - MockConfigurationPropertySource source) { + protected ConfigurationPropertySource convertSource(MockConfigurationPropertySource source) { return source; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java index a1678345f69..9b2d625ba07 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java @@ -34,8 +34,7 @@ public class MapConfigurationPropertySourceTests { @Test public void createWhenMapIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new MapConfigurationPropertySource(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new MapConfigurationPropertySource(null)) .withMessageContaining("Map must not be null"); } @@ -88,8 +87,7 @@ public class MapConfigurationPropertySourceTests { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); - assertThat(source.iterator()).toIterable().containsExactly( - ConfigurationPropertyName.of("foo.bar"), + assertThat(source.iterator()).toIterable().containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.baz")); } @@ -98,15 +96,13 @@ public class MapConfigurationPropertySourceTests { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); - assertThat(source.stream()).containsExactly( - ConfigurationPropertyName.of("foo.bar"), + assertThat(source.stream()).containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.baz")); } private Object getValue(ConfigurationPropertySource source, String name) { - ConfigurationProperty property = source - .getConfigurationProperty(ConfigurationPropertyName.of(name)); + ConfigurationProperty property = source.getConfigurationProperty(ConfigurationPropertyName.of(name)); return (property != null) ? property.getValue() : null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MockConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MockConfigurationPropertySource.java index 98161ece082..5ef62bf66e4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MockConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MockConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,21 +30,18 @@ import org.springframework.boot.origin.OriginTrackedValue; * @author Phillip Webb * @author Madhura Bhave */ -public class MockConfigurationPropertySource - implements IterableConfigurationPropertySource { +public class MockConfigurationPropertySource implements IterableConfigurationPropertySource { private final Map map = new LinkedHashMap<>(); public MockConfigurationPropertySource() { } - public MockConfigurationPropertySource(String configurationPropertyName, - Object value) { + public MockConfigurationPropertySource(String configurationPropertyName, Object value) { this(configurationPropertyName, value, null); } - public MockConfigurationPropertySource(String configurationPropertyName, Object value, - String origin) { + public MockConfigurationPropertySource(String configurationPropertyName, Object value, String origin) { put(ConfigurationPropertyName.of(configurationPropertyName), OriginTrackedValue.of(value, MockOrigin.of(origin))); } @@ -81,8 +78,7 @@ public class MockConfigurationPropertySource } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { OriginTrackedValue result = this.map.get(name); if (result == null) { result = findValue(name); @@ -102,8 +98,7 @@ public class MockConfigurationPropertySource } @Override - public ConfigurationProperty getConfigurationProperty( - ConfigurationPropertyName name) { + public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { return MockConfigurationPropertySource.this.getConfigurationProperty(name); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java index e5092dd5b82..b7a02c24ec5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,16 +41,14 @@ public class SpringConfigurationPropertySourceTests { @Test public void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringConfigurationPropertySource(null, - mock(PropertyMapper.class), null)) + .isThrownBy(() -> new SpringConfigurationPropertySource(null, mock(PropertyMapper.class), null)) .withMessageContaining("PropertySource must not be null"); } @Test public void createWhenMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringConfigurationPropertySource( - mock(PropertySource.class), null, null)) + .isThrownBy(() -> new SpringConfigurationPropertySource(mock(PropertySource.class), null, null)) .withMessageContaining("Mapper must not be null"); } @@ -64,8 +62,7 @@ public class SpringConfigurationPropertySourceTests { TestPropertyMapper mapper = new TestPropertyMapper(); ConfigurationPropertyName name = ConfigurationPropertyName.of("my.key"); mapper.addFromConfigurationProperty(name, "key2"); - SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource( - propertySource, mapper, null); + SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource(propertySource, mapper, null); assertThat(adapter.getConfigurationProperty(name).getValue()).isEqualTo("value2"); } @@ -77,8 +74,7 @@ public class SpringConfigurationPropertySourceTests { TestPropertyMapper mapper = new TestPropertyMapper(); ConfigurationPropertyName name = ConfigurationPropertyName.of("my.key"); mapper.addFromConfigurationProperty(name, "key"); - SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource( - propertySource, mapper, null); + SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource(propertySource, mapper, null); assertThat(adapter.getConfigurationProperty(name).getOrigin().toString()) .isEqualTo("\"key\" from property source \"test\""); } @@ -87,15 +83,12 @@ public class SpringConfigurationPropertySourceTests { public void getValueWhenOriginCapableShouldIncludeSourceOrigin() { Map source = new LinkedHashMap<>(); source.put("key", "value"); - PropertySource propertySource = new OriginCapablePropertySource<>( - new MapPropertySource("test", source)); + PropertySource propertySource = new OriginCapablePropertySource<>(new MapPropertySource("test", source)); TestPropertyMapper mapper = new TestPropertyMapper(); ConfigurationPropertyName name = ConfigurationPropertyName.of("my.key"); mapper.addFromConfigurationProperty(name, "key"); - SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource( - propertySource, mapper, null); - assertThat(adapter.getConfigurationProperty(name).getOrigin().toString()) - .isEqualTo("TestOrigin key"); + SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource(propertySource, mapper, null); + assertThat(adapter.getConfigurationProperty(name).getOrigin().toString()).isEqualTo("TestOrigin key"); } @Test @@ -103,23 +96,21 @@ public class SpringConfigurationPropertySourceTests { Map source = new LinkedHashMap<>(); source.put("foo.bar", "value"); PropertySource propertySource = new MapPropertySource("test", source); - SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource( - propertySource, DefaultPropertyMapper.INSTANCE, null); + SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource(propertySource, + DefaultPropertyMapper.INSTANCE, null); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo"))) .isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test public void fromWhenPropertySourceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> SpringConfigurationPropertySource.from(null)) + assertThatIllegalArgumentException().isThrownBy(() -> SpringConfigurationPropertySource.from(null)) .withMessageContaining("Source must not be null"); } @Test public void fromWhenNonEnumerableShouldReturnNonIterable() { - PropertySource propertySource = new PropertySource("test", - new Object()) { + PropertySource propertySource = new PropertySource("test", new Object()) { @Override public Object getProperty(String name) { @@ -160,8 +151,7 @@ public class SpringConfigurationPropertySourceTests { /** * Test {@link PropertySource} that's also an {@link OriginLookup}. */ - private static class OriginCapablePropertySource extends PropertySource - implements OriginLookup { + private static class OriginCapablePropertySource extends PropertySource implements OriginLookup { private final PropertySource propertySource; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java index bbe88fea857..98879de964b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java @@ -41,35 +41,28 @@ public class SpringConfigurationPropertySourcesTests { @Test public void createWhenPropertySourcesIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringConfigurationPropertySources(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new SpringConfigurationPropertySources(null)) .withMessageContaining("Sources must not be null"); } @Test public void shouldAdaptPropertySource() { MutablePropertySources sources = new MutablePropertySources(); - sources.addFirst( - new MapPropertySource("test", Collections.singletonMap("a", "b"))); - Iterator iterator = new SpringConfigurationPropertySources( - sources).iterator(); + sources.addFirst(new MapPropertySource("test", Collections.singletonMap("a", "b"))); + Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("a"); - assertThat(iterator.next().getConfigurationProperty(name).getValue()) - .isEqualTo("b"); + assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("b"); assertThat(iterator.hasNext()).isFalse(); } @Test public void shouldAdaptSystemEnvironmentPropertySource() { MutablePropertySources sources = new MutablePropertySources(); - sources.addLast(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("SERVER_PORT", "1234"))); - Iterator iterator = new SpringConfigurationPropertySources( - sources).iterator(); + Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port"); - assertThat(iterator.next().getConfigurationProperty(name).getValue()) - .isEqualTo("1234"); + assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); assertThat(iterator.hasNext()).isFalse(); } @@ -79,35 +72,29 @@ public class SpringConfigurationPropertySourcesTests { sources.addLast(new SystemEnvironmentPropertySource( "test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("SERVER_PORT", "1234"))); - Iterator iterator = new SpringConfigurationPropertySources( - sources).iterator(); + Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port"); - assertThat(iterator.next().getConfigurationProperty(name).getValue()) - .isEqualTo("1234"); + assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); assertThat(iterator.hasNext()).isFalse(); } @Test public void shouldNotAdaptSystemEnvironmentPropertyOverrideSource() { MutablePropertySources sources = new MutablePropertySources(); - sources.addLast(new SystemEnvironmentPropertySource("override", - Collections.singletonMap("server.port", "1234"))); - Iterator iterator = new SpringConfigurationPropertySources( - sources).iterator(); + sources.addLast( + new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234"))); + Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port"); - assertThat(iterator.next().getConfigurationProperty(name).getValue()) - .isEqualTo("1234"); + assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); assertThat(iterator.hasNext()).isFalse(); } @Test public void shouldAdaptSystemEnvironmentPropertySourceWithUnderscoreValue() { MutablePropertySources sources = new MutablePropertySources(); - sources.addLast(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("_", "1234"))); - Iterator iterator = new SpringConfigurationPropertySources( - sources).iterator(); + Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("bar"); assertThat(iterator.next().getConfigurationProperty(name)).isNull(); assertThat(iterator.hasNext()).isFalse(); @@ -116,32 +103,23 @@ public class SpringConfigurationPropertySourcesTests { @Test public void shouldAdaptMultiplePropertySources() { MutablePropertySources sources = new MutablePropertySources(); - sources.addLast(new SystemEnvironmentPropertySource("system", - Collections.singletonMap("SERVER_PORT", "1234"))); - sources.addLast(new MapPropertySource("test1", - Collections.singletonMap("server.po-rt", "4567"))); - sources.addLast( - new MapPropertySource("test2", Collections.singletonMap("a", "b"))); - Iterator iterator = new SpringConfigurationPropertySources( - sources).iterator(); + sources.addLast(new SystemEnvironmentPropertySource("system", Collections.singletonMap("SERVER_PORT", "1234"))); + sources.addLast(new MapPropertySource("test1", Collections.singletonMap("server.po-rt", "4567"))); + sources.addLast(new MapPropertySource("test2", Collections.singletonMap("a", "b"))); + Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port"); - assertThat(iterator.next().getConfigurationProperty(name).getValue()) - .isEqualTo("1234"); - assertThat(iterator.next().getConfigurationProperty(name).getValue()) - .isEqualTo("4567"); - assertThat(iterator.next() - .getConfigurationProperty(ConfigurationPropertyName.of("a")).getValue()) - .isEqualTo("b"); + assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); + assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("4567"); + assertThat(iterator.next().getConfigurationProperty(ConfigurationPropertyName.of("a")).getValue()) + .isEqualTo("b"); assertThat(iterator.hasNext()).isFalse(); } @Test public void shouldFlattenEnvironment() { StandardEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addFirst( - new MapPropertySource("foo", Collections.singletonMap("foo", "bar"))); - environment.getPropertySources().addFirst( - new MapPropertySource("far", Collections.singletonMap("far", "far"))); + environment.getPropertySources().addFirst(new MapPropertySource("foo", Collections.singletonMap("foo", "bar"))); + environment.getPropertySources().addFirst(new MapPropertySource("far", Collections.singletonMap("far", "far"))); MutablePropertySources sources = new MutablePropertySources(); sources.addFirst(new PropertySource("env", environment) { @@ -151,25 +129,20 @@ public class SpringConfigurationPropertySourcesTests { } }); - sources.addLast( - new MapPropertySource("baz", Collections.singletonMap("baz", "barf"))); - SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources( - sources); + sources.addLast(new MapPropertySource("baz", Collections.singletonMap("baz", "barf"))); + SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources); assertThat(configurationSources.iterator()).toIterable().hasSize(5); } @Test public void shouldTrackChanges() { MutablePropertySources sources = new MutablePropertySources(); - SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources( - sources); + SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources); assertThat(configurationSources.iterator()).toIterable().hasSize(0); - MapPropertySource source1 = new MapPropertySource("test1", - Collections.singletonMap("a", "b")); + MapPropertySource source1 = new MapPropertySource("test1", Collections.singletonMap("a", "b")); sources.addLast(source1); assertThat(configurationSources.iterator()).toIterable().hasSize(1); - MapPropertySource source2 = new MapPropertySource("test2", - Collections.singletonMap("b", "c")); + MapPropertySource source2 = new MapPropertySource("test2", Collections.singletonMap("b", "c")); sources.addLast(source2); assertThat(configurationSources.iterator()).toIterable().hasSize(2); } @@ -177,20 +150,15 @@ public class SpringConfigurationPropertySourcesTests { @Test public void shouldTrackWhenSourceHasIdenticalName() { MutablePropertySources sources = new MutablePropertySources(); - SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources( - sources); + SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources); ConfigurationPropertyName name = ConfigurationPropertyName.of("a"); - MapPropertySource source1 = new MapPropertySource("test", - Collections.singletonMap("a", "s1")); + MapPropertySource source1 = new MapPropertySource("test", Collections.singletonMap("a", "s1")); sources.addLast(source1); - assertThat(configurationSources.iterator().next().getConfigurationProperty(name) - .getValue()).isEqualTo("s1"); - MapPropertySource source2 = new MapPropertySource("test", - Collections.singletonMap("a", "s2")); + assertThat(configurationSources.iterator().next().getConfigurationProperty(name).getValue()).isEqualTo("s1"); + MapPropertySource source2 = new MapPropertySource("test", Collections.singletonMap("a", "s2")); sources.remove("test"); sources.addLast(source2); - assertThat(configurationSources.iterator().next().getConfigurationProperty(name) - .getValue()).isEqualTo("s2"); + assertThat(configurationSources.iterator().next().getConfigurationProperty(name).getValue()).isEqualTo("s2"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java index acaf152f6c0..d14139d5f3c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java @@ -48,16 +48,15 @@ public class SpringIterableConfigurationPropertySourceTests { @Test public void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, - mock(PropertyMapper.class))) + .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class))) .withMessageContaining("PropertySource must not be null"); } @Test public void createWhenMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringIterableConfigurationPropertySource( - mock(EnumerablePropertySource.class), null)) + .isThrownBy( + () -> new SpringIterableConfigurationPropertySource(mock(EnumerablePropertySource.class), null)) .withMessageContaining("Mapper must not be null"); } @@ -68,16 +67,15 @@ public class SpringIterableConfigurationPropertySourceTests { source.put("key2", "value2"); source.put("key3", "value3"); source.put("key4", "value4"); - EnumerablePropertySource propertySource = new MapPropertySource("test", - source); + EnumerablePropertySource propertySource = new MapPropertySource("test", source); TestPropertyMapper mapper = new TestPropertyMapper(); mapper.addFromPropertySource("key1", "my.key1"); mapper.addFromPropertySource("key2", "my.key2a", "my.key2b"); mapper.addFromPropertySource("key4", "my.key4"); SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, mapper); - assertThat(adapter.iterator()).toIterable().extracting(Object::toString) - .containsExactly("my.key1", "my.key2a", "my.key2b", "my.key4"); + assertThat(adapter.iterator()).toIterable().extracting(Object::toString).containsExactly("my.key1", "my.key2a", + "my.key2b", "my.key4"); } @Test @@ -86,8 +84,7 @@ public class SpringIterableConfigurationPropertySourceTests { source.put("key1", "value1"); source.put("key2", "value2"); source.put("key3", "value3"); - EnumerablePropertySource propertySource = new MapPropertySource("test", - source); + EnumerablePropertySource propertySource = new MapPropertySource("test", source); TestPropertyMapper mapper = new TestPropertyMapper(); ConfigurationPropertyName name = ConfigurationPropertyName.of("my.key"); mapper.addFromConfigurationProperty(name, "key2"); @@ -102,8 +99,7 @@ public class SpringIterableConfigurationPropertySourceTests { source.put("key1", "value1"); source.put("key2", "value2"); source.put("key3", "value3"); - EnumerablePropertySource propertySource = new MapPropertySource("test", - source); + EnumerablePropertySource propertySource = new MapPropertySource("test", source); TestPropertyMapper mapper = new TestPropertyMapper(); mapper.addFromPropertySource("key1", "my.missing"); mapper.addFromPropertySource("key2", "my.k-e-y"); @@ -117,8 +113,7 @@ public class SpringIterableConfigurationPropertySourceTests { public void getValueOrigin() { Map source = new LinkedHashMap<>(); source.put("key", "value"); - EnumerablePropertySource propertySource = new MapPropertySource("test", - source); + EnumerablePropertySource propertySource = new MapPropertySource("test", source); TestPropertyMapper mapper = new TestPropertyMapper(); ConfigurationPropertyName name = ConfigurationPropertyName.of("my.key"); mapper.addFromConfigurationProperty(name, "key"); @@ -139,8 +134,7 @@ public class SpringIterableConfigurationPropertySourceTests { mapper.addFromConfigurationProperty(name, "key"); SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, mapper); - assertThat(adapter.getConfigurationProperty(name).getOrigin().toString()) - .isEqualTo("TestOrigin key"); + assertThat(adapter.getConfigurationProperty(name).getOrigin().toString()).isEqualTo("TestOrigin key"); } @Test @@ -167,8 +161,8 @@ public class SpringIterableConfigurationPropertySourceTests { map.put("key1", "value1"); map.put("key2", "value2"); EnumerablePropertySource source = new MapPropertySource("test", map); - SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( - source, DefaultPropertyMapper.INSTANCE); + SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource(source, + DefaultPropertyMapper.INSTANCE); assertThat(adapter.stream().count()).isEqualTo(2); map.put("key3", "value3"); assertThat(adapter.stream().count()).isEqualTo(3); @@ -181,8 +175,8 @@ public class SpringIterableConfigurationPropertySourceTests { map.put("key1", "value1"); map.put("key2", "value2"); EnumerablePropertySource source = new MapPropertySource("test", map); - SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( - source, DefaultPropertyMapper.INSTANCE); + SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource(source, + DefaultPropertyMapper.INSTANCE); assertThat(adapter.stream().count()).isEqualTo(2); map.setThrowException(true); } @@ -192,10 +186,9 @@ public class SpringIterableConfigurationPropertySourceTests { Map map = new LinkedHashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); - EnumerablePropertySource source = new OriginTrackedMapPropertySource("test", - map); - SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( - source, DefaultPropertyMapper.INSTANCE); + EnumerablePropertySource source = new OriginTrackedMapPropertySource("test", map); + SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource(source, + DefaultPropertyMapper.INSTANCE); assertThat(adapter.stream().count()).isEqualTo(2); map.put("key3", "value3"); assertThat(adapter.stream().count()).isEqualTo(3); @@ -206,10 +199,9 @@ public class SpringIterableConfigurationPropertySourceTests { Map map = new LinkedHashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); - EnumerablePropertySource source = new OriginTrackedMapPropertySource("test", - map, true); - SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( - source, DefaultPropertyMapper.INSTANCE); + EnumerablePropertySource source = new OriginTrackedMapPropertySource("test", map, true); + SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource(source, + DefaultPropertyMapper.INSTANCE); assertThat(adapter.stream().count()).isEqualTo(2); map.put("key3", "value3"); assertThat(adapter.stream().count()).isEqualTo(2); @@ -218,8 +210,8 @@ public class SpringIterableConfigurationPropertySourceTests { /** * Test {@link PropertySource} that's also an {@link OriginLookup}. */ - private static class OriginCapablePropertySource - extends EnumerablePropertySource implements OriginLookup { + private static class OriginCapablePropertySource extends EnumerablePropertySource + implements OriginLookup { private final EnumerablePropertySource propertySource; @@ -252,8 +244,7 @@ public class SpringIterableConfigurationPropertySourceTests { } - private static class ConcurrentModificationThrowingMap - extends LinkedHashMap { + private static class ConcurrentModificationThrowingMap extends LinkedHashMap { private boolean throwException; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java index bb48a431660..2d5cba0228f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java @@ -36,34 +36,23 @@ public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapper @Test public void mapFromStringShouldReturnBestGuess() { assertThat(namesFromString("SERVER")).toIterable().containsExactly("server"); - assertThat(namesFromString("SERVER_PORT")).toIterable() - .containsExactly("server.port"); + assertThat(namesFromString("SERVER_PORT")).toIterable().containsExactly("server.port"); assertThat(namesFromString("HOST_0")).toIterable().containsExactly("host[0]"); - assertThat(namesFromString("HOST_0_1")).toIterable() - .containsExactly("host[0][1]"); - assertThat(namesFromString("HOST_0_NAME")).toIterable() - .containsExactly("host[0].name"); - assertThat(namesFromString("HOST_F00_NAME")).toIterable() - .containsExactly("host.f00.name"); + assertThat(namesFromString("HOST_0_1")).toIterable().containsExactly("host[0][1]"); + assertThat(namesFromString("HOST_0_NAME")).toIterable().containsExactly("host[0].name"); + assertThat(namesFromString("HOST_F00_NAME")).toIterable().containsExactly("host.f00.name"); assertThat(namesFromString("S-ERVER")).toIterable().containsExactly("s-erver"); } @Test public void mapFromConfigurationShouldReturnBestGuess() { - assertThat(namesFromConfiguration("server")).toIterable() - .containsExactly("SERVER"); - assertThat(namesFromConfiguration("server.port")).toIterable() - .containsExactly("SERVER_PORT"); - assertThat(namesFromConfiguration("host[0]")).toIterable() - .containsExactly("HOST_0"); - assertThat(namesFromConfiguration("host[0][1]")).toIterable() - .containsExactly("HOST_0_1"); - assertThat(namesFromConfiguration("host[0].name")).toIterable() - .containsExactly("HOST_0_NAME"); - assertThat(namesFromConfiguration("host.f00.name")).toIterable() - .containsExactly("HOST_F00_NAME"); - assertThat(namesFromConfiguration("foo.the-bar")).toIterable() - .containsExactly("FOO_THEBAR", "FOO_THE_BAR"); + assertThat(namesFromConfiguration("server")).toIterable().containsExactly("SERVER"); + assertThat(namesFromConfiguration("server.port")).toIterable().containsExactly("SERVER_PORT"); + assertThat(namesFromConfiguration("host[0]")).toIterable().containsExactly("HOST_0"); + assertThat(namesFromConfiguration("host[0][1]")).toIterable().containsExactly("HOST_0_1"); + assertThat(namesFromConfiguration("host[0].name")).toIterable().containsExactly("HOST_0_NAME"); + assertThat(namesFromConfiguration("host.f00.name")).toIterable().containsExactly("HOST_F00_NAME"); + assertThat(namesFromConfiguration("foo.the-bar")).toIterable().containsExactly("FOO_THEBAR", "FOO_THE_BAR"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/TestPropertyMapper.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/TestPropertyMapper.java index b63707d4b7e..44356923f85 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/TestPropertyMapper.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/TestPropertyMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,13 +32,12 @@ class TestPropertyMapper implements PropertyMapper { public void addFromPropertySource(String from, String... to) { for (String configurationPropertyName : to) { - this.fromSource.add(from, new PropertyMapping(from, - ConfigurationPropertyName.of(configurationPropertyName))); + this.fromSource.add(from, + new PropertyMapping(from, ConfigurationPropertyName.of(configurationPropertyName))); } } - public void addFromConfigurationProperty(ConfigurationPropertyName from, - String... to) { + public void addFromConfigurationProperty(ConfigurationPropertyName from, String... to) { for (String propertySourceName : to) { this.fromConfig.add(from, new PropertyMapping(propertySourceName, from)); } @@ -52,8 +51,7 @@ class TestPropertyMapper implements PropertyMapper { @Override public PropertyMapping[] map(ConfigurationPropertyName configurationPropertyName) { - return this.fromConfig - .getOrDefault(configurationPropertyName, Collections.emptyList()) + return this.fromConfig.getOrDefault(configurationPropertyName, Collections.emptyList()) .toArray(new PropertyMapping[0]); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java index 4a55b2c0fc6..2a97d68351f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ public class ArrayToDelimitedStringConverterTests { private final ConversionService conversionService; - public ArrayToDelimitedStringConverterTests(String name, - ConversionService conversionService) { + public ArrayToDelimitedStringConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -75,9 +74,8 @@ public class ArrayToDelimitedStringConverterTests { if (this.conversionService instanceof ApplicationConversionService) { Data data = new Data(); data.type = new int[] { 1, 2, 3 }; - String converted = (String) this.conversionService.convert( - data.type, TypeDescriptor - .nested(ReflectionUtils.findField(Data.class, "type"), 0), + String converted = (String) this.conversionService.convert(data.type, + TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "type"), 0), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1.2.3"); } @@ -92,8 +90,7 @@ public class ArrayToDelimitedStringConverterTests { @Parameters(name = "{0}") public static Iterable conversionServices() { - return new ConversionServiceParameters( - ArrayToDelimitedStringConverterTests::addConverter); + return new ConversionServiceParameters(ArrayToDelimitedStringConverterTests::addConverter); } private static void addConverter(FormattingConversionService service) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java index 462ac6712fd..c0bdbecd6c2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class CollectionToDelimitedStringConverterTests { private final ConversionService conversionService; - public CollectionToDelimitedStringConverterTests(String name, - ConversionService conversionService) { + public CollectionToDelimitedStringConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -78,9 +77,8 @@ public class CollectionToDelimitedStringConverterTests { if (this.conversionService instanceof ApplicationConversionService) { Data data = new Data(); data.type = Arrays.asList(1, 2, 3); - String converted = (String) this.conversionService.convert( - data.type, TypeDescriptor - .nested(ReflectionUtils.findField(Data.class, "type"), 0), + String converted = (String) this.conversionService.convert(data.type, + TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "type"), 0), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1.2.3"); } @@ -95,8 +93,7 @@ public class CollectionToDelimitedStringConverterTests { @Parameters(name = "{0}") public static Iterable conversionServices() { - return new ConversionServiceParameters( - CollectionToDelimitedStringConverterTests::addConverter); + return new ConversionServiceParameters(CollectionToDelimitedStringConverterTests::addConverter); } private static void addConverter(FormattingConversionService service) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java index 32c1e35ed89..cf738e26229 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,30 +41,24 @@ public class ConversionServiceParameters implements Iterable { private final List parameters; public ConversionServiceParameters(Formatter formatter) { - this((Consumer) ( - conversionService) -> conversionService.addFormatter(formatter)); + this((Consumer) (conversionService) -> conversionService.addFormatter(formatter)); } public ConversionServiceParameters(ConverterFactory converterFactory) { - this((Consumer) ( - conversionService) -> conversionService - .addConverterFactory(converterFactory)); + this((Consumer) (conversionService) -> conversionService + .addConverterFactory(converterFactory)); } public ConversionServiceParameters(GenericConverter converter) { - this((Consumer) ( - conversionService) -> conversionService.addConverter(converter)); + this((Consumer) (conversionService) -> conversionService.addConverter(converter)); } - public ConversionServiceParameters( - Consumer initializer) { + public ConversionServiceParameters(Consumer initializer) { FormattingConversionService withoutDefaults = new FormattingConversionService(); initializer.accept(withoutDefaults); List parameters = new ArrayList<>(); - parameters.add( - new Object[] { "without defaults conversion service", withoutDefaults }); - parameters.add(new Object[] { "application conversion service", - new ApplicationConversionService() }); + parameters.add(new Object[] { "without defaults conversion service", withoutDefaults }); + parameters.add(new Object[] { "application conversion service", new ApplicationConversionService() }); this.parameters = Collections.unmodifiableList(parameters); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java index f7fb33404f0..0fc17ddbc54 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,54 +41,50 @@ public class DelimitedStringToArrayConverterTests { private final ConversionService conversionService; - public DelimitedStringToArrayConverterTests(String name, - ConversionService conversionService) { + public DelimitedStringToArrayConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @Test public void canConvertFromStringToArrayShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, String[].class)) - .isTrue(); + assertThat(this.conversionService.canConvert(String.class, String[].class)).isTrue(); } @Test public void matchesWhenTargetIsNotAnnotatedShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); - assertThat(new DelimitedStringToArrayConverter(this.conversionService) - .matches(sourceType, targetType)).isTrue(); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); + assertThat(new DelimitedStringToArrayConverter(this.conversionService).matches(sourceType, targetType)) + .isTrue(); } @Test public void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { if (this.conversionService instanceof ApplicationConversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor.nested( - ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - assertThat(new DelimitedStringToArrayConverter(this.conversionService) - .matches(sourceType, targetType)).isTrue(); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + assertThat(new DelimitedStringToArrayConverter(this.conversionService).matches(sourceType, targetType)) + .isTrue(); } } @Test public void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor.nested( - ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); - assertThat(new DelimitedStringToArrayConverter(this.conversionService) - .matches(sourceType, targetType)).isFalse(); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); + assertThat(new DelimitedStringToArrayConverter(this.conversionService).matches(sourceType, targetType)) + .isFalse(); } @Test public void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { if (this.conversionService instanceof ApplicationConversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor.nested( - ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - Integer[] converted = (Integer[]) this.conversionService - .convert(" 1 | 2| 3 ", sourceType, targetType); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + Integer[] converted = (Integer[]) this.conversionService.convert(" 1 | 2| 3 ", sourceType, targetType); assertThat(converted).containsExactly(1, 2, 3); } } @@ -96,17 +92,14 @@ public class DelimitedStringToArrayConverterTests { @Test public void convertWhenHasDelimiterOfNoneShouldReturnWholeString() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "delimiterNone"), 0); - String[] converted = (String[]) this.conversionService.convert("a,b,c", - sourceType, targetType); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "delimiterNone"), 0); + String[] converted = (String[]) this.conversionService.convert("a,b,c", sourceType, targetType); assertThat(converted).containsExactly("a,b,c"); } @Parameters(name = "{0}") public static Iterable conversionServices() { - return new ConversionServiceParameters( - DelimitedStringToArrayConverterTests::addConverter); + return new ConversionServiceParameters(DelimitedStringToArrayConverterTests::addConverter); } private static void addConverter(FormattingConversionService service) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java index 46e10741c2e..52ffb9d2a64 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,63 +42,58 @@ public class DelimitedStringToCollectionConverterTests { private final ConversionService conversionService; - public DelimitedStringToCollectionConverterTests(String name, - ConversionService conversionService) { + public DelimitedStringToCollectionConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @Test public void canConvertFromStringToCollectionShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, Collection.class)) - .isTrue(); + assertThat(this.conversionService.canConvert(String.class, Collection.class)).isTrue(); } @Test public void matchesWhenTargetIsNotAnnotatedShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService) - .matches(sourceType, targetType)).isTrue(); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); + assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + .isTrue(); } @Test public void matchesWhenHasAnnotationAndNoElementTypeShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService) - .matches(sourceType, targetType)).isTrue(); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); + assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + .isTrue(); } @Test public void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { if (this.conversionService instanceof ApplicationConversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor.nested( - ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService) - .matches(sourceType, targetType)).isTrue(); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + .isTrue(); } } @Test public void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor.nested( - ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService) - .matches(sourceType, targetType)).isFalse(); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); + assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + .isFalse(); } @Test @SuppressWarnings("unchecked") public void convertWhenHasNoElementTypeShouldReturnTrimmedString() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); - Collection converted = (Collection) this.conversionService - .convert(" a | b| c ", sourceType, targetType); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); + Collection converted = (Collection) this.conversionService.convert(" a | b| c ", sourceType, + targetType); assertThat(converted).containsExactly("a", "b", "c"); } @@ -107,10 +102,10 @@ public class DelimitedStringToCollectionConverterTests { public void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { if (this.conversionService instanceof ApplicationConversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor.nested( - ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - List converted = (List) this.conversionService - .convert(" 1 | 2| 3 ", sourceType, targetType); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + List converted = (List) this.conversionService.convert(" 1 | 2| 3 ", sourceType, + targetType); assertThat(converted).containsExactly(1, 2, 3); } } @@ -119,10 +114,8 @@ public class DelimitedStringToCollectionConverterTests { @SuppressWarnings("unchecked") public void convertWhenHasDelimiterOfNoneShouldReturnWholeString() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "delimiterNone"), 0); - List converted = (List) this.conversionService.convert("a,b,c", - sourceType, targetType); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "delimiterNone"), 0); + List converted = (List) this.conversionService.convert("a,b,c", sourceType, targetType); assertThat(converted).containsExactly("a,b,c"); } @@ -130,17 +123,15 @@ public class DelimitedStringToCollectionConverterTests { @Test public void convertWhenHasCollectionObjectTypeShouldUseCollectionObjectType() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "specificType"), 0); - MyCustomList converted = (MyCustomList) this.conversionService - .convert("a*b", sourceType, targetType); + TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "specificType"), 0); + MyCustomList converted = (MyCustomList) this.conversionService.convert("a*b", sourceType, + targetType); assertThat(converted).containsExactly("a", "b"); } @Parameters(name = "{0}") public static Iterable conversionServices() { - return new ConversionServiceParameters( - DelimitedStringToCollectionConverterTests::addConverter); + return new ConversionServiceParameters(DelimitedStringToCollectionConverterTests::addConverter); } private static void addConverter(FormattingConversionService service) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java index 794355f76ce..321d5837df1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java @@ -33,28 +33,20 @@ public class DurationStyleTests { @Test public void detectAndParseWhenValueIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> DurationStyle.detectAndParse(null)) + assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse(null)) .withMessageContaining("Value must not be null"); } @Test public void detectAndParseWhenIso8601ShouldReturnDuration() { - assertThat(DurationStyle.detectAndParse("PT20.345S")) - .isEqualTo(Duration.parse("PT20.345S")); - assertThat(DurationStyle.detectAndParse("PT15M")) - .isEqualTo(Duration.parse("PT15M")); - assertThat(DurationStyle.detectAndParse("+PT15M")) - .isEqualTo(Duration.parse("PT15M")); - assertThat(DurationStyle.detectAndParse("PT10H")) - .isEqualTo(Duration.parse("PT10H")); + assertThat(DurationStyle.detectAndParse("PT20.345S")).isEqualTo(Duration.parse("PT20.345S")); + assertThat(DurationStyle.detectAndParse("PT15M")).isEqualTo(Duration.parse("PT15M")); + assertThat(DurationStyle.detectAndParse("+PT15M")).isEqualTo(Duration.parse("PT15M")); + assertThat(DurationStyle.detectAndParse("PT10H")).isEqualTo(Duration.parse("PT10H")); assertThat(DurationStyle.detectAndParse("P2D")).isEqualTo(Duration.parse("P2D")); - assertThat(DurationStyle.detectAndParse("P2DT3H4M")) - .isEqualTo(Duration.parse("P2DT3H4M")); - assertThat(DurationStyle.detectAndParse("-PT6H3M")) - .isEqualTo(Duration.parse("-PT6H3M")); - assertThat(DurationStyle.detectAndParse("-PT-6H+3M")) - .isEqualTo(Duration.parse("-PT-6H+3M")); + assertThat(DurationStyle.detectAndParse("P2DT3H4M")).isEqualTo(Duration.parse("P2DT3H4M")); + assertThat(DurationStyle.detectAndParse("-PT6H3M")).isEqualTo(Duration.parse("-PT6H3M")); + assertThat(DurationStyle.detectAndParse("-PT-6H+3M")).isEqualTo(Duration.parse("-PT-6H+3M")); } @Test @@ -62,50 +54,39 @@ public class DurationStyleTests { assertThat(DurationStyle.detectAndParse("10ns")).isEqualTo(Duration.ofNanos(10)); assertThat(DurationStyle.detectAndParse("10NS")).isEqualTo(Duration.ofNanos(10)); assertThat(DurationStyle.detectAndParse("+10ns")).isEqualTo(Duration.ofNanos(10)); - assertThat(DurationStyle.detectAndParse("-10ns")) - .isEqualTo(Duration.ofNanos(-10)); + assertThat(DurationStyle.detectAndParse("-10ns")).isEqualTo(Duration.ofNanos(-10)); } @Test public void detectAndParseWhenSimpleMicrosShouldReturnDuration() { - assertThat(DurationStyle.detectAndParse("10us")) - .isEqualTo(Duration.ofNanos(10000)); - assertThat(DurationStyle.detectAndParse("10US")) - .isEqualTo(Duration.ofNanos(10000)); - assertThat(DurationStyle.detectAndParse("+10us")) - .isEqualTo(Duration.ofNanos(10000)); - assertThat(DurationStyle.detectAndParse("-10us")) - .isEqualTo(Duration.ofNanos(-10000)); + assertThat(DurationStyle.detectAndParse("10us")).isEqualTo(Duration.ofNanos(10000)); + assertThat(DurationStyle.detectAndParse("10US")).isEqualTo(Duration.ofNanos(10000)); + assertThat(DurationStyle.detectAndParse("+10us")).isEqualTo(Duration.ofNanos(10000)); + assertThat(DurationStyle.detectAndParse("-10us")).isEqualTo(Duration.ofNanos(-10000)); } @Test public void detectAndParseWhenSimpleMillisShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10ms")).isEqualTo(Duration.ofMillis(10)); assertThat(DurationStyle.detectAndParse("10MS")).isEqualTo(Duration.ofMillis(10)); - assertThat(DurationStyle.detectAndParse("+10ms")) - .isEqualTo(Duration.ofMillis(10)); - assertThat(DurationStyle.detectAndParse("-10ms")) - .isEqualTo(Duration.ofMillis(-10)); + assertThat(DurationStyle.detectAndParse("+10ms")).isEqualTo(Duration.ofMillis(10)); + assertThat(DurationStyle.detectAndParse("-10ms")).isEqualTo(Duration.ofMillis(-10)); } @Test public void detectAndParseWhenSimpleSecondsShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10s")).isEqualTo(Duration.ofSeconds(10)); assertThat(DurationStyle.detectAndParse("10S")).isEqualTo(Duration.ofSeconds(10)); - assertThat(DurationStyle.detectAndParse("+10s")) - .isEqualTo(Duration.ofSeconds(10)); - assertThat(DurationStyle.detectAndParse("-10s")) - .isEqualTo(Duration.ofSeconds(-10)); + assertThat(DurationStyle.detectAndParse("+10s")).isEqualTo(Duration.ofSeconds(10)); + assertThat(DurationStyle.detectAndParse("-10s")).isEqualTo(Duration.ofSeconds(-10)); } @Test public void detectAndParseWhenSimpleMinutesShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10m")).isEqualTo(Duration.ofMinutes(10)); assertThat(DurationStyle.detectAndParse("10M")).isEqualTo(Duration.ofMinutes(10)); - assertThat(DurationStyle.detectAndParse("+10m")) - .isEqualTo(Duration.ofMinutes(10)); - assertThat(DurationStyle.detectAndParse("-10m")) - .isEqualTo(Duration.ofMinutes(-10)); + assertThat(DurationStyle.detectAndParse("+10m")).isEqualTo(Duration.ofMinutes(10)); + assertThat(DurationStyle.detectAndParse("-10m")).isEqualTo(Duration.ofMinutes(-10)); } @Test @@ -133,18 +114,14 @@ public class DurationStyleTests { @Test public void detectAndParseWhenSimpleWithoutSuffixButWithChronoUnitShouldReturnDuration() { - assertThat(DurationStyle.detectAndParse("10", ChronoUnit.SECONDS)) - .isEqualTo(Duration.ofSeconds(10)); - assertThat(DurationStyle.detectAndParse("+10", ChronoUnit.SECONDS)) - .isEqualTo(Duration.ofSeconds(10)); - assertThat(DurationStyle.detectAndParse("-10", ChronoUnit.SECONDS)) - .isEqualTo(Duration.ofSeconds(-10)); + assertThat(DurationStyle.detectAndParse("10", ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); + assertThat(DurationStyle.detectAndParse("+10", ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); + assertThat(DurationStyle.detectAndParse("-10", ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(-10)); } @Test public void detectAndParseWhenBadFormatShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> DurationStyle.detectAndParse("10foo")) + assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse("10foo")) .withMessageContaining("'10foo' is not a valid duration"); } @@ -184,46 +161,31 @@ public class DurationStyleTests { @Test public void parseIso8601ShouldParse() { - assertThat(DurationStyle.ISO8601.parse("PT20.345S")) - .isEqualTo(Duration.parse("PT20.345S")); - assertThat(DurationStyle.ISO8601.parse("PT15M")) - .isEqualTo(Duration.parse("PT15M")); - assertThat(DurationStyle.ISO8601.parse("+PT15M")) - .isEqualTo(Duration.parse("PT15M")); - assertThat(DurationStyle.ISO8601.parse("PT10H")) - .isEqualTo(Duration.parse("PT10H")); + assertThat(DurationStyle.ISO8601.parse("PT20.345S")).isEqualTo(Duration.parse("PT20.345S")); + assertThat(DurationStyle.ISO8601.parse("PT15M")).isEqualTo(Duration.parse("PT15M")); + assertThat(DurationStyle.ISO8601.parse("+PT15M")).isEqualTo(Duration.parse("PT15M")); + assertThat(DurationStyle.ISO8601.parse("PT10H")).isEqualTo(Duration.parse("PT10H")); assertThat(DurationStyle.ISO8601.parse("P2D")).isEqualTo(Duration.parse("P2D")); - assertThat(DurationStyle.ISO8601.parse("P2DT3H4M")) - .isEqualTo(Duration.parse("P2DT3H4M")); - assertThat(DurationStyle.ISO8601.parse("-PT6H3M")) - .isEqualTo(Duration.parse("-PT6H3M")); - assertThat(DurationStyle.ISO8601.parse("-PT-6H+3M")) - .isEqualTo(Duration.parse("-PT-6H+3M")); + assertThat(DurationStyle.ISO8601.parse("P2DT3H4M")).isEqualTo(Duration.parse("P2DT3H4M")); + assertThat(DurationStyle.ISO8601.parse("-PT6H3M")).isEqualTo(Duration.parse("-PT6H3M")); + assertThat(DurationStyle.ISO8601.parse("-PT-6H+3M")).isEqualTo(Duration.parse("-PT-6H+3M")); } @Test public void parseIso8601WithUnitShouldIgnoreUnit() { - assertThat(DurationStyle.ISO8601.parse("PT20.345S", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("PT20.345S")); - assertThat(DurationStyle.ISO8601.parse("PT15M", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("PT15M")); - assertThat(DurationStyle.ISO8601.parse("+PT15M", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("PT15M")); - assertThat(DurationStyle.ISO8601.parse("PT10H", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("PT10H")); + assertThat(DurationStyle.ISO8601.parse("PT20.345S", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT20.345S")); + assertThat(DurationStyle.ISO8601.parse("PT15M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT15M")); + assertThat(DurationStyle.ISO8601.parse("+PT15M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT15M")); + assertThat(DurationStyle.ISO8601.parse("PT10H", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT10H")); assertThat(DurationStyle.ISO8601.parse("P2D")).isEqualTo(Duration.parse("P2D")); - assertThat(DurationStyle.ISO8601.parse("P2DT3H4M", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("P2DT3H4M")); - assertThat(DurationStyle.ISO8601.parse("-PT6H3M", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("-PT6H3M")); - assertThat(DurationStyle.ISO8601.parse("-PT-6H+3M", ChronoUnit.SECONDS)) - .isEqualTo(Duration.parse("-PT-6H+3M")); + assertThat(DurationStyle.ISO8601.parse("P2DT3H4M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("P2DT3H4M")); + assertThat(DurationStyle.ISO8601.parse("-PT6H3M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("-PT6H3M")); + assertThat(DurationStyle.ISO8601.parse("-PT-6H+3M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("-PT-6H+3M")); } @Test public void parseIso8601WhenSimpleShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> DurationStyle.ISO8601.parse("10d")) + assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.ISO8601.parse("10d")) .withMessageContaining("'10d' is not a valid ISO-8601 duration"); } @@ -234,24 +196,19 @@ public class DurationStyleTests { @Test public void parseSimpleWithUnitShouldUseUnitAsFallback() { - assertThat(DurationStyle.SIMPLE.parse("10m", ChronoUnit.SECONDS)) - .isEqualTo(Duration.ofMinutes(10)); - assertThat(DurationStyle.SIMPLE.parse("10", ChronoUnit.MINUTES)) - .isEqualTo(Duration.ofMinutes(10)); + assertThat(DurationStyle.SIMPLE.parse("10m", ChronoUnit.SECONDS)).isEqualTo(Duration.ofMinutes(10)); + assertThat(DurationStyle.SIMPLE.parse("10", ChronoUnit.MINUTES)).isEqualTo(Duration.ofMinutes(10)); } @Test public void parseSimpleWhenUnknownUnitShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb")) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .isEqualTo("Unknown unit 'mb'")); + assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb")) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'")); } @Test public void parseSimpleWhenIso8601ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> DurationStyle.SIMPLE.parse("PT10H")) + assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("PT10H")) .withMessageContaining("'PT10H' is not a valid simple duration"); } @@ -264,8 +221,7 @@ public class DurationStyleTests { @Test public void printIso8601ShouldIgnoreUnit() { Duration duration = Duration.parse("-PT-6H+3M"); - assertThat(DurationStyle.ISO8601.print(duration, ChronoUnit.DAYS)) - .isEqualTo("PT5H57M"); + assertThat(DurationStyle.ISO8601.print(duration, ChronoUnit.DAYS)).isEqualTo("PT5H57M"); } @Test @@ -277,8 +233,7 @@ public class DurationStyleTests { @Test public void printSimpleWithUnitShouldPrintInUnit() { Duration duration = Duration.ofMillis(1000); - assertThat(DurationStyle.SIMPLE.print(duration, ChronoUnit.SECONDS)) - .isEqualTo("1s"); + assertThat(DurationStyle.SIMPLE.print(duration, ChronoUnit.SECONDS)).isEqualTo("1s"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java index ba6783ecb8d..1022e83d68f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,32 +39,27 @@ public class DurationToNumberConverterTests { private final ConversionService conversionService; - public DurationToNumberConverterTests(String name, - ConversionService conversionService) { + public DurationToNumberConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @Test public void convertWithoutStyleShouldReturnMs() { - Long converted = this.conversionService.convert(Duration.ofSeconds(1), - Long.class); + Long converted = this.conversionService.convert(Duration.ofSeconds(1), Long.class); assertThat(converted).isEqualTo(1000); } @Test public void convertWithFormatShouldUseIgnoreFormat() { - Integer converted = (Integer) this.conversionService.convert( - Duration.ofSeconds(1), - MockDurationTypeDescriptor.get(null, DurationStyle.ISO8601), - TypeDescriptor.valueOf(Integer.class)); + Integer converted = (Integer) this.conversionService.convert(Duration.ofSeconds(1), + MockDurationTypeDescriptor.get(null, DurationStyle.ISO8601), TypeDescriptor.valueOf(Integer.class)); assertThat(converted).isEqualTo(1000); } @Test public void convertWithFormatAndUnitShouldUseFormatAndUnit() { Byte converted = (Byte) this.conversionService.convert(Duration.ofSeconds(1), - MockDurationTypeDescriptor.get(ChronoUnit.SECONDS, null), - TypeDescriptor.valueOf(Byte.class)); + MockDurationTypeDescriptor.get(ChronoUnit.SECONDS, null), TypeDescriptor.valueOf(Byte.class)); assertThat(converted).isEqualTo((byte) 1); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java index 95f75404162..f3d9f40b740 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,23 +39,20 @@ public class DurationToStringConverterTests { private final ConversionService conversionService; - public DurationToStringConverterTests(String name, - ConversionService conversionService) { + public DurationToStringConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @Test public void convertWithoutStyleShouldReturnIso8601() { - String converted = this.conversionService.convert(Duration.ofSeconds(1), - String.class); + String converted = this.conversionService.convert(Duration.ofSeconds(1), String.class); assertThat(converted).isEqualTo("PT1S"); } @Test public void convertWithFormatShouldUseFormatAndMs() { String converted = (String) this.conversionService.convert(Duration.ofSeconds(1), - MockDurationTypeDescriptor.get(null, DurationStyle.SIMPLE), - TypeDescriptor.valueOf(String.class)); + MockDurationTypeDescriptor.get(null, DurationStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1000ms"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java index dac35c14e8a..0e0a9271d83 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ public class InetAddressFormatterTests { } @Test - public void convertFromInetAddressToStringShouldConvert() - throws UnknownHostException { + public void convertFromInetAddressToStringShouldConvert() throws UnknownHostException { assumeResolves("example.com", true); InetAddress address = InetAddress.getByName("example.com"); String converted = this.conversionService.convert(address, String.class); @@ -57,8 +56,7 @@ public class InetAddressFormatterTests { @Test public void convertFromStringToInetAddressShouldConvert() { assumeResolves("example.com", true); - InetAddress converted = this.conversionService.convert("example.com", - InetAddress.class); + InetAddress converted = this.conversionService.convert("example.com", InetAddress.class); assertThat(converted.toString()).startsWith("example.com"); } @@ -66,15 +64,14 @@ public class InetAddressFormatterTests { public void convertFromStringToInetAddressWhenHostDoesNotExistShouldThrowException() { String missingDomain = "ireallydontexist.example.com"; assumeResolves(missingDomain, false); - assertThatExceptionOfType(ConversionFailedException.class).isThrownBy( - () -> this.conversionService.convert(missingDomain, InetAddress.class)); + assertThatExceptionOfType(ConversionFailedException.class) + .isThrownBy(() -> this.conversionService.convert(missingDomain, InetAddress.class)); } private void assumeResolves(String host, boolean expectedToResolve) { boolean resolved = isResolvable(host); if (resolved != expectedToResolve) { - throw new AssumptionViolatedException( - "Host " + host + " resolved " + resolved); + throw new AssumptionViolatedException("Host " + host + " resolved " + resolved); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java index 5c536653d74..9c2b4a2c044 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,8 @@ public class IsoOffsetFormatterTests { @Test public void convertShouldConvertStringToIsoDate() { OffsetDateTime now = OffsetDateTime.now(); - OffsetDateTime converted = this.conversionService.convert( - DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now), OffsetDateTime.class); + OffsetDateTime converted = this.conversionService.convert(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now), + OffsetDateTime.class); assertThat(converted).isEqualTo(now); } @@ -54,8 +54,7 @@ public class IsoOffsetFormatterTests { public void convertShouldConvertIsoDateToString() { OffsetDateTime now = OffsetDateTime.now(); String converted = this.conversionService.convert(now, String.class); - assertThat(converted).isNotNull() - .startsWith(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); + assertThat(converted).isNotNull().startsWith(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); } @Parameters(name = "{0}") diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDataSizeTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDataSizeTypeDescriptor.java index bfea6b3f3c7..5008c0860f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDataSizeTypeDescriptor.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDataSizeTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,9 @@ public final class MockDataSizeTypeDescriptor { public static TypeDescriptor get(DataUnit unit) { TypeDescriptor descriptor = mock(TypeDescriptor.class); if (unit != null) { - DataSizeUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation( - Collections.singletonMap("value", unit), DataSizeUnit.class, null); - given(descriptor.getAnnotation(DataSizeUnit.class)) - .willReturn(unitAnnotation); + DataSizeUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation(Collections.singletonMap("value", unit), + DataSizeUnit.class, null); + given(descriptor.getAnnotation(DataSizeUnit.class)).willReturn(unitAnnotation); } given(descriptor.getType()).willReturn((Class) DataSize.class); given(descriptor.getObjectType()).willReturn((Class) DataSize.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java index 3ad5b12ecca..f8d8d65dd94 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,16 +41,14 @@ public final class MockDurationTypeDescriptor { public static TypeDescriptor get(ChronoUnit unit, DurationStyle style) { TypeDescriptor descriptor = mock(TypeDescriptor.class); if (unit != null) { - DurationUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation( - Collections.singletonMap("value", unit), DurationUnit.class, null); - given(descriptor.getAnnotation(DurationUnit.class)) - .willReturn(unitAnnotation); + DurationUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation(Collections.singletonMap("value", unit), + DurationUnit.class, null); + given(descriptor.getAnnotation(DurationUnit.class)).willReturn(unitAnnotation); } if (style != null) { - DurationFormat formatAnnotation = AnnotationUtils.synthesizeAnnotation( - Collections.singletonMap("value", style), DurationFormat.class, null); - given(descriptor.getAnnotation(DurationFormat.class)) - .willReturn(formatAnnotation); + DurationFormat formatAnnotation = AnnotationUtils + .synthesizeAnnotation(Collections.singletonMap("value", style), DurationFormat.class, null); + given(descriptor.getAnnotation(DurationFormat.class)).willReturn(formatAnnotation); } given(descriptor.getType()).willReturn((Class) Duration.class); given(descriptor.getObjectType()).willReturn((Class) Duration.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java index 5058ebd6ac2..b9d4f406b19 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class NumberToDataSizeConverterTests { private final ConversionService conversionService; - public NumberToDataSizeConverterTests(String name, - ConversionService conversionService) { + public NumberToDataSizeConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -69,15 +68,12 @@ public class NumberToDataSizeConverterTests { private DataSize convert(Integer source, DataUnit defaultUnit) { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { - DataSizeUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation( - Collections.singletonMap("value", defaultUnit), DataSizeUnit.class, - null); - given(targetType.getAnnotation(DataSizeUnit.class)) - .willReturn(unitAnnotation); + DataSizeUnit unitAnnotation = AnnotationUtils + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DataSizeUnit.class, null); + given(targetType.getAnnotation(DataSizeUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) DataSize.class); - return (DataSize) this.conversionService.convert(source, - TypeDescriptor.forObject(source), targetType); + return (DataSize) this.conversionService.convert(source, TypeDescriptor.forObject(source), targetType); } @Parameterized.Parameters(name = "{0}") diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java index 02771799588..0b7c75522a8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class NumberToDurationConverterTests { private final ConversionService conversionService; - public NumberToDurationConverterTests(String name, - ConversionService conversionService) { + public NumberToDurationConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -70,15 +69,12 @@ public class NumberToDurationConverterTests { private Duration convert(Integer source, ChronoUnit defaultUnit) { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { - DurationUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation( - Collections.singletonMap("value", defaultUnit), DurationUnit.class, - null); - given(targetType.getAnnotation(DurationUnit.class)) - .willReturn(unitAnnotation); + DurationUnit unitAnnotation = AnnotationUtils + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DurationUnit.class, null); + given(targetType.getAnnotation(DurationUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) Duration.class); - return (Duration) this.conversionService.convert(source, - TypeDescriptor.forObject(source), targetType); + return (Duration) this.conversionService.convert(source, TypeDescriptor.forObject(source), targetType); } @Parameters(name = "{0}") diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java index 5fbaf4dbcfb..a350ddadab9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ public class StringToDataSizeConverterTests { private final ConversionService conversionService; - public StringToDataSizeConverterTests(String name, - ConversionService conversionService) { + public StringToDataSizeConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -90,16 +89,13 @@ public class StringToDataSizeConverterTests { @Test public void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDataSize() { assertThat(convert("10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert("+10", DataUnit.KILOBYTES)) - .isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert("-10", DataUnit.KILOBYTES)) - .isEqualTo(DataSize.ofKilobytes(-10)); + assertThat(convert("+10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert("-10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-10)); } @Test public void convertWhenBadFormatShouldThrowException() { - assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> convert("10WB")) + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert("10WB")) .withMessageContaining("'10WB' is not a valid data size"); } @@ -113,8 +109,8 @@ public class StringToDataSizeConverterTests { } private DataSize convert(String source, DataUnit unit) { - return (DataSize) this.conversionService.convert(source, - TypeDescriptor.forObject(source), MockDataSizeTypeDescriptor.get(unit)); + return (DataSize) this.conversionService.convert(source, TypeDescriptor.forObject(source), + MockDataSizeTypeDescriptor.get(unit)); } @Parameters(name = "{0}") diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java index 7d5ee5dc184..4dfb9aa6f2b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class StringToDurationConverterTests { private final ConversionService conversionService; - public StringToDurationConverterTests(String name, - ConversionService conversionService) { + public StringToDurationConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -123,18 +122,14 @@ public class StringToDurationConverterTests { @Test public void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDuration() { - assertThat(convert("10", ChronoUnit.SECONDS, null)) - .isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("+10", ChronoUnit.SECONDS, null)) - .isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("-10", ChronoUnit.SECONDS, null)) - .isEqualTo(Duration.ofSeconds(-10)); + assertThat(convert("10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert("+10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert("-10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(-10)); } @Test public void convertWhenBadFormatShouldThrowException() { - assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> convert("10foo")) + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert("10foo")) .withMessageContaining("'10foo' is not a valid duration"); } @@ -154,8 +149,7 @@ public class StringToDurationConverterTests { } private Duration convert(String source, ChronoUnit unit, DurationStyle style) { - return (Duration) this.conversionService.convert(source, - TypeDescriptor.forObject(source), + return (Duration) this.conversionService.convert(source, TypeDescriptor.forObject(source), MockDurationTypeDescriptor.get(unit, style)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java index d2071aaf42c..b194015af72 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,21 +37,18 @@ public class StringToEnumIgnoringCaseConverterFactoryTests { private final ConversionService conversionService; - public StringToEnumIgnoringCaseConverterFactoryTests(String name, - ConversionService conversionService) { + public StringToEnumIgnoringCaseConverterFactoryTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @Test public void canConvertFromStringToEnumShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, TestEnum.class)) - .isTrue(); + assertThat(this.conversionService.canConvert(String.class, TestEnum.class)).isTrue(); } @Test public void canConvertFromStringToEnumSubclassShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, - TestSubclassEnum.ONE.getClass())).isTrue(); + assertThat(this.conversionService.canConvert(String.class, TestSubclassEnum.ONE.getClass())).isTrue(); } @Test @@ -60,8 +57,7 @@ public class StringToEnumIgnoringCaseConverterFactoryTests { assertThat(service.convert("", TestEnum.class)).isNull(); assertThat(service.convert("ONE", TestEnum.class)).isEqualTo(TestEnum.ONE); assertThat(service.convert("TWO", TestEnum.class)).isEqualTo(TestEnum.TWO); - assertThat(service.convert("THREE_AND_FOUR", TestEnum.class)) - .isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(service.convert("THREE_AND_FOUR", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); } @Test @@ -70,14 +66,10 @@ public class StringToEnumIgnoringCaseConverterFactoryTests { assertThat(service.convert("", TestEnum.class)).isNull(); assertThat(service.convert("one", TestEnum.class)).isEqualTo(TestEnum.ONE); assertThat(service.convert("tWo", TestEnum.class)).isEqualTo(TestEnum.TWO); - assertThat(service.convert("three_and_four", TestEnum.class)) - .isEqualTo(TestEnum.THREE_AND_FOUR); - assertThat(service.convert("threeandfour", TestEnum.class)) - .isEqualTo(TestEnum.THREE_AND_FOUR); - assertThat(service.convert("three-and-four", TestEnum.class)) - .isEqualTo(TestEnum.THREE_AND_FOUR); - assertThat(service.convert("threeAndFour", TestEnum.class)) - .isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(service.convert("three_and_four", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(service.convert("threeandfour", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(service.convert("three-and-four", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(service.convert("threeAndFour", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); } @Test @@ -85,10 +77,9 @@ public class StringToEnumIgnoringCaseConverterFactoryTests { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(new Locale("tr")); - LocaleSensitiveEnum result = this.conversionService.convert( - "accept-case-insensitive-properties", LocaleSensitiveEnum.class); - assertThat(result) - .isEqualTo(LocaleSensitiveEnum.ACCEPT_CASE_INSENSITIVE_PROPERTIES); + LocaleSensitiveEnum result = this.conversionService.convert("accept-case-insensitive-properties", + LocaleSensitiveEnum.class); + assertThat(result).isEqualTo(LocaleSensitiveEnum.ACCEPT_CASE_INSENSITIVE_PROPERTIES); } finally { Locale.setDefault(defaultLocale); @@ -97,8 +88,7 @@ public class StringToEnumIgnoringCaseConverterFactoryTests { @Parameters(name = "{0}") public static Iterable conversionServices() { - return new ConversionServiceParameters( - new StringToEnumIgnoringCaseConverterFactory()); + return new ConversionServiceParameters(new StringToEnumIgnoringCaseConverterFactory()); } enum TestEnum { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java index 12a2401e0a2..fed625bb45d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java @@ -42,9 +42,8 @@ public class FailureAnalyzersIntegrationTests { @Test public void analysisIsPerformed() { - assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE).run()); + assertThatExceptionOfType(Exception.class).isThrownBy( + () -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); assertThat(this.outputCapture.toString()).contains("APPLICATION FAILED TO START"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java index 614423e0e87..370d15acdaa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -123,13 +123,11 @@ public class FailureAnalyzersTests { } - interface AwareFailureAnalyzer - extends BeanFactoryAware, EnvironmentAware, FailureAnalyzer { + interface AwareFailureAnalyzer extends BeanFactoryAware, EnvironmentAware, FailureAnalyzer { } - static class StandardAwareFailureAnalyzer extends BasicFailureAnalyzer - implements AwareFailureAnalyzer { + static class StandardAwareFailureAnalyzer extends BasicFailureAnalyzer implements AwareFailureAnalyzer { @Override public void setEnvironment(Environment environment) { @@ -155,8 +153,7 @@ public class FailureAnalyzersTests { @Override public Enumeration getResources(String name) throws IOException { if ("META-INF/spring.factories".equals(name)) { - return super.getResources( - "failure-analyzers-tests/" + this.factoriesName); + return super.getResources("failure-analyzers-tests/" + this.factoriesName); } return super.getResources(name); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java index 4f831a44cd4..30c9df85be6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java @@ -54,79 +54,68 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { FailureAnalysis analysis = performAnalysis(CyclicBeanMethodsConfiguration.class); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); - assertThat(lines.get(0)).isEqualTo( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(lines.get(0)) + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌─────┐"); - assertThat(lines.get(3)).startsWith( - "| one defined in " + InnerInnerConfiguration.class.getName()); + assertThat(lines.get(3)).startsWith("| one defined in " + InnerInnerConfiguration.class.getName()); assertThat(lines.get(4)).isEqualTo("↑ ↓"); - assertThat(lines.get(5)) - .startsWith("| two defined in " + InnerConfiguration.class.getName()); + assertThat(lines.get(5)).startsWith("| two defined in " + InnerConfiguration.class.getName()); assertThat(lines.get(6)).isEqualTo("↑ ↓"); - assertThat(lines.get(7)).startsWith( - "| three defined in " + CyclicBeanMethodsConfiguration.class.getName()); + assertThat(lines.get(7)).startsWith("| three defined in " + CyclicBeanMethodsConfiguration.class.getName()); assertThat(lines.get(8)).isEqualTo("└─────┘"); } @Test public void cycleWithAutowiredFields() throws IOException { FailureAnalysis analysis = performAnalysis(CycleWithAutowiredFields.class); - assertThat(analysis.getDescription()).startsWith( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(analysis.getDescription()) + .startsWith("The dependencies of some of the beans in the application context form a cycle:"); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); - assertThat(lines.get(0)).isEqualTo( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(lines.get(0)) + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌─────┐"); - assertThat(lines.get(3)).startsWith( - "| three defined in " + BeanThreeConfiguration.class.getName()); + assertThat(lines.get(3)).startsWith("| three defined in " + BeanThreeConfiguration.class.getName()); assertThat(lines.get(4)).isEqualTo("↑ ↓"); - assertThat(lines.get(5)).startsWith( - "| one defined in " + CycleWithAutowiredFields.class.getName()); + assertThat(lines.get(5)).startsWith("| one defined in " + CycleWithAutowiredFields.class.getName()); assertThat(lines.get(6)).isEqualTo("↑ ↓"); - assertThat(lines.get(7)).startsWith("| " + BeanTwoConfiguration.class.getName() - + " (field private " + BeanThree.class.getName()); + assertThat(lines.get(7)).startsWith( + "| " + BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); assertThat(lines.get(8)).isEqualTo("└─────┘"); } @Test public void cycleReferencedViaOtherBeans() throws IOException { - FailureAnalysis analysis = performAnalysis( - CycleReferencedViaOtherBeansConfiguration.class); + FailureAnalysis analysis = performAnalysis(CycleReferencedViaOtherBeansConfiguration.class); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(12); - assertThat(lines.get(0)).isEqualTo( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(lines.get(0)) + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); - assertThat(lines.get(2)) - .contains("refererOne " + "(field " + RefererTwo.class.getName()); + assertThat(lines.get(2)).contains("refererOne " + "(field " + RefererTwo.class.getName()); assertThat(lines.get(3)).isEqualTo(" ↓"); - assertThat(lines.get(4)) - .contains("refererTwo " + "(field " + BeanOne.class.getName()); + assertThat(lines.get(4)).contains("refererTwo " + "(field " + BeanOne.class.getName()); assertThat(lines.get(5)).isEqualTo("┌─────┐"); - assertThat(lines.get(6)).startsWith("| one defined in " - + CycleReferencedViaOtherBeansConfiguration.class.getName()); + assertThat(lines.get(6)) + .startsWith("| one defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(7)).isEqualTo("↑ ↓"); - assertThat(lines.get(8)).startsWith("| two defined in " - + CycleReferencedViaOtherBeansConfiguration.class.getName()); + assertThat(lines.get(8)) + .startsWith("| two defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(9)).isEqualTo("↑ ↓"); - assertThat(lines.get(10)).startsWith("| three defined in " - + CycleReferencedViaOtherBeansConfiguration.class.getName()); + assertThat(lines.get(10)) + .startsWith("| three defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(11)).isEqualTo("└─────┘"); } @Test public void cycleWithAnUnknownStartIsNotAnalyzed() { - assertThat(this.analyzer.analyze(new BeanCurrentlyInCreationException("test"))) - .isNull(); + assertThat(this.analyzer.analyze(new BeanCurrentlyInCreationException("test"))).isNull(); } - private List readDescriptionLines(FailureAnalysis analysis) - throws IOException { - try (BufferedReader reader = new BufferedReader( - new StringReader(analysis.getDescription()))) { + private List readDescriptionLines(FailureAnalysis analysis) throws IOException { + try (BufferedReader reader = new BufferedReader(new StringReader(analysis.getDescription()))) { return reader.lines().collect(Collectors.toList()); } } @@ -138,8 +127,7 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { } private Exception createFailure(Class configuration) { - try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - configuration)) { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { fail("Expected failure did not occur"); return null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java index ebe18c44cbc..c129a6e6394 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java @@ -38,8 +38,8 @@ public class BeanDefinitionOverrideFailureAnalyzerTests { public void analyzeBeanDefinitionOverrideException() { FailureAnalysis analysis = performAnalysis(BeanOverrideConfiguration.class); String description = analysis.getDescription(); - assertThat(description).contains("The bean 'testBean', defined in " - + SecondConfiguration.class.getName() + ", could not be registered."); + assertThat(description).contains("The bean 'testBean', defined in " + SecondConfiguration.class.getName() + + ", could not be registered."); assertThat(description).contains(FirstConfiguration.class.getName()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index d13e0f86229..013a9d44e68 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java @@ -44,10 +44,8 @@ public class BeanNotOfRequiredTypeFailureAnalyzerTests { public void jdkProxyCausesInjectionFailure() { FailureAnalysis analysis = performAnalysis(JdkProxyConfiguration.class); assertThat(analysis.getDescription()).startsWith("The bean 'asyncBean'"); - assertThat(analysis.getDescription()) - .contains("'" + AsyncBean.class.getName() + "'"); - assertThat(analysis.getDescription()) - .endsWith(String.format("%s%n", SomeInterface.class.getName())); + assertThat(analysis.getDescription()).contains("'" + AsyncBean.class.getName() + "'"); + assertThat(analysis.getDescription()).endsWith(String.format("%s%n", SomeInterface.class.getName())); } private FailureAnalysis performAnalysis(Class configuration) { @@ -57,8 +55,7 @@ public class BeanNotOfRequiredTypeFailureAnalyzerTests { } private Exception createFailure(Class configuration) { - try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - configuration)) { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { fail("Expected failure did not occur"); return null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java index 0bde8f458c9..b35e1dc80a9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,32 +46,27 @@ public class BindFailureAnalyzerTests { @Test public void analysisForUnboundElementsIsNull() { - FailureAnalysis analysis = performAnalysis( - UnboundElementsFailureConfiguration.class, "test.foo.listValue[0]=hello", - "test.foo.listValue[2]=world"); + FailureAnalysis analysis = performAnalysis(UnboundElementsFailureConfiguration.class, + "test.foo.listValue[0]=hello", "test.foo.listValue[2]=world"); assertThat(analysis).isNull(); } @Test public void analysisForValidationExceptionIsNull() { - FailureAnalysis analysis = performAnalysis( - FieldValidationFailureConfiguration.class, "test.foo.value=1"); + FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class, "test.foo.value=1"); assertThat(analysis).isNull(); } @Test public void bindExceptionDueToOtherFailure() { - FailureAnalysis analysis = performAnalysis(GenericFailureConfiguration.class, - "test.foo.value=alpha"); + FailureAnalysis analysis = performAnalysis(GenericFailureConfiguration.class, "test.foo.value=alpha"); assertThat(analysis.getDescription()).contains(failure("test.foo.value", "alpha", - "\"test.foo.value\" from property source \"test\"", - "failed to convert java.lang.String to int")); + "\"test.foo.value\" from property source \"test\"", "failed to convert java.lang.String to int")); } @Test public void bindExceptionForUnknownValueInEnumListsValidValuesInAction() { - FailureAnalysis analysis = performAnalysis(EnumFailureConfiguration.class, - "test.foo.fruit=apple,strawberry"); + FailureAnalysis analysis = performAnalysis(EnumFailureConfiguration.class, "test.foo.fruit=apple,strawberry"); for (Fruit fruit : Fruit.values()) { assertThat(analysis.getAction()).contains(fruit.name()); } @@ -79,28 +74,23 @@ public class BindFailureAnalyzerTests { @Test public void bindExceptionWithNestedFailureShouldDisplayNestedMessage() { - FailureAnalysis analysis = performAnalysis(NestedFailureConfiguration.class, - "test.foo.value=hello"); + FailureAnalysis analysis = performAnalysis(NestedFailureConfiguration.class, "test.foo.value=hello"); assertThat(analysis.getDescription()).contains(failure("test.foo.value", "hello", "\"test.foo.value\" from property source \"test\"", "This is a failure")); } - private static String failure(String property, String value, String origin, - String reason) { - return String.format( - "Property: %s%n Value: %s%n Origin: %s%n Reason: %s", property, - value, origin, reason); + private static String failure(String property, String value, String origin, String reason) { + return String.format("Property: %s%n Value: %s%n Origin: %s%n Reason: %s", property, value, origin, + reason); } - private FailureAnalysis performAnalysis(Class configuration, - String... environment) { + private FailureAnalysis performAnalysis(Class configuration, String... environment) { BeanCreationException failure = createFailure(configuration, environment); assertThat(failure).isNotNull(); return new BindFailureAnalyzer().analyze(failure); } - private BeanCreationException createFailure(Class configuration, - String... environment) { + private BeanCreationException createFailure(Class configuration, String... environment) { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); addEnvironment(context, environment); @@ -114,8 +104,7 @@ public class BindFailureAnalyzerTests { } } - private void addEnvironment(AnnotationConfigApplicationContext context, - String[] environment) { + private void addEnvironment(AnnotationConfigApplicationContext context, String[] environment) { MutablePropertySources sources = context.getEnvironment().getPropertySources(); Map map = new HashMap<>(); for (String pair : environment) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java index 78b05451a8e..8556e0034d2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,30 +63,22 @@ public class BindValidationFailureAnalyzerTests { @Test public void bindExceptionWithFieldErrorsDueToValidationFailure() { - FailureAnalysis analysis = performAnalysis( - FieldValidationFailureConfiguration.class); - assertThat(analysis.getDescription()) - .contains(failure("test.foo.foo", "null", "must not be null")); - assertThat(analysis.getDescription()) - .contains(failure("test.foo.value", "0", "at least five")); - assertThat(analysis.getDescription()) - .contains(failure("test.foo.nested.bar", "null", "must not be null")); + FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class); + assertThat(analysis.getDescription()).contains(failure("test.foo.foo", "null", "must not be null")); + assertThat(analysis.getDescription()).contains(failure("test.foo.value", "0", "at least five")); + assertThat(analysis.getDescription()).contains(failure("test.foo.nested.bar", "null", "must not be null")); } @Test public void bindExceptionWithOriginDueToValidationFailure() { - FailureAnalysis analysis = performAnalysis( - FieldValidationFailureConfiguration.class, "test.foo.value=4"); - assertThat(analysis.getDescription()) - .contains("Origin: \"test.foo.value\" from property source \"test\""); + FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class, "test.foo.value=4"); + assertThat(analysis.getDescription()).contains("Origin: \"test.foo.value\" from property source \"test\""); } @Test public void bindExceptionWithObjectErrorsDueToValidationFailure() { - FailureAnalysis analysis = performAnalysis( - ObjectValidationFailureConfiguration.class); - assertThat(analysis.getDescription()) - .contains("Reason: This object could not be bound."); + FailureAnalysis analysis = performAnalysis(ObjectValidationFailureConfiguration.class); + assertThat(analysis.getDescription()).contains("Reason: This object could not be bound."); } @Test @@ -94,28 +86,22 @@ public class BindValidationFailureAnalyzerTests { BindException cause = new BindException(new FieldValidationFailureProperties(), "fieldValidationFailureProperties"); cause.addError(new FieldError("test", "value", "must not be null")); - BeanCreationException rootFailure = new BeanCreationException( - "bean creation failure", cause); - FailureAnalysis analysis = new BindValidationFailureAnalyzer() - .analyze(rootFailure, rootFailure); - assertThat(analysis.getDescription()) - .contains(failure("test.value", "null", "must not be null")); + BeanCreationException rootFailure = new BeanCreationException("bean creation failure", cause); + FailureAnalysis analysis = new BindValidationFailureAnalyzer().analyze(rootFailure, rootFailure); + assertThat(analysis.getDescription()).contains(failure("test.value", "null", "must not be null")); } private static String failure(String property, String value, String reason) { - return String.format("Property: %s%n Value: %s%n Reason: %s", property, - value, reason); + return String.format("Property: %s%n Value: %s%n Reason: %s", property, value, reason); } - private FailureAnalysis performAnalysis(Class configuration, - String... environment) { + private FailureAnalysis performAnalysis(Class configuration, String... environment) { BeanCreationException failure = createFailure(configuration, environment); assertThat(failure).isNotNull(); return new BindValidationFailureAnalyzer().analyze(failure); } - private BeanCreationException createFailure(Class configuration, - String... environment) { + private BeanCreationException createFailure(Class configuration, String... environment) { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); addEnvironment(context, environment); @@ -129,8 +115,7 @@ public class BindValidationFailureAnalyzerTests { } } - private void addEnvironment(AnnotationConfigApplicationContext context, - String[] environment) { + private void addEnvironment(AnnotationConfigApplicationContext context, String[] environment) { MutablePropertySources sources = context.getEnvironment().getPropertySources(); Map map = new HashMap<>(); for (String pair : environment) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java index 6aeaec3d98a..7d132097628 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java @@ -38,21 +38,18 @@ public class InvalidConfigurationPropertiesFailureAnalyzerTests { public void analysisForInvalidConfigurationOfConfigurationProperties() { FailureAnalysis analysis = performAnalysis(); assertThat(analysis.getDescription()).isEqualTo(getDescription()); - assertThat(analysis.getAction()).isEqualTo("Remove @Component from " - + TestProperties.class.getName() + assertThat(analysis.getAction()).isEqualTo("Remove @Component from " + TestProperties.class.getName() + " or consider disabling automatic @ConfigurationProperties scanning."); } private String getDescription() { - return TestProperties.class.getName() - + " is annotated with @ConfigurationProperties and @Component" + return TestProperties.class.getName() + " is annotated with @ConfigurationProperties and @Component" + ". This may cause the @ConfigurationProperties bean to be registered twice."; } private FailureAnalysis performAnalysis() { FailureAnalysis analysis = this.analyzer - .analyze(new InvalidConfigurationPropertiesException(TestProperties.class, - Component.class)); + .analyze(new InvalidConfigurationPropertiesException(TestProperties.class, Component.class)); assertThat(analysis).isNotNull(); return analysis; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java index b198de2e75d..e2ae6bc1dcf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java @@ -41,11 +41,10 @@ public class InvalidConfigurationPropertyNameFailureAnalyzerTests { public void analysisWhenRootCauseIsBeanCreationFailureShouldContainBeanName() { BeanCreationException failure = createFailure(InvalidPrefixConfiguration.class); FailureAnalysis analysis = this.analyzer.analyze(failure); - assertThat(analysis.getDescription()).contains(String.format( - "%n Invalid characters: %s%n Bean: %s%n Reason: %s", "'F', 'P'", - "invalidPrefixProperties", - "Canonical names should be kebab-case ('-' separated), " - + "lowercase alpha-numeric characters and must start with a letter")); + assertThat(analysis.getDescription()) + .contains(String.format("%n Invalid characters: %s%n Bean: %s%n Reason: %s", "'F', 'P'", + "invalidPrefixProperties", "Canonical names should be kebab-case ('-' separated), " + + "lowercase alpha-numeric characters and must start with a letter")); } private BeanCreationException createFailure(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java index cb3629ff5fe..96fa3828d0f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,35 +43,27 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { public void analysisWithNullEnvironment() { InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( "test.property", "invalid", "This is not valid."); - FailureAnalysis analysis = new InvalidConfigurationPropertyValueFailureAnalyzer() - .analyze(failure); + FailureAnalysis analysis = new InvalidConfigurationPropertyValueFailureAnalyzer().analyze(failure); assertThat(analysis).isNull(); } @Test public void analysisWithKnownProperty() { - MapPropertySource source = new MapPropertySource("test", - Collections.singletonMap("test.property", "invalid")); - this.environment.getPropertySources() - .addFirst(OriginCapablePropertySource.get(source)); + MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid")); + this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source)); InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( "test.property", "invalid", "This is not valid."); FailureAnalysis analysis = performAnalysis(failure); assertCommonParts(failure, analysis); - assertThat(analysis.getAction()) - .contains("Review the value of the property with the provided reason."); - assertThat(analysis.getDescription()) - .contains("Validation failed for the following reason") - .contains("This is not valid.") - .doesNotContain("Additionally, this property is also set"); + assertThat(analysis.getAction()).contains("Review the value of the property with the provided reason."); + assertThat(analysis.getDescription()).contains("Validation failed for the following reason") + .contains("This is not valid.").doesNotContain("Additionally, this property is also set"); } @Test public void analysisWithKnownPropertyAndNoReason() { - MapPropertySource source = new MapPropertySource("test", - Collections.singletonMap("test.property", "invalid")); - this.environment.getPropertySources() - .addFirst(OriginCapablePropertySource.get(source)); + MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid")); + this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source)); InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( "test.property", "invalid", null); FailureAnalysis analysis = performAnalysis(failure); @@ -82,28 +74,22 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { @Test public void analysisWithKnownPropertyAndOtherCandidates() { - MapPropertySource source = new MapPropertySource("test", - Collections.singletonMap("test.property", "invalid")); + MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid")); MapPropertySource additional = new MapPropertySource("additional", Collections.singletonMap("test.property", "valid")); - MapPropertySource another = new MapPropertySource("another", - Collections.singletonMap("test.property", "test")); - this.environment.getPropertySources() - .addFirst(OriginCapablePropertySource.get(source)); + MapPropertySource another = new MapPropertySource("another", Collections.singletonMap("test.property", "test")); + this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source)); this.environment.getPropertySources().addLast(additional); - this.environment.getPropertySources() - .addLast(OriginCapablePropertySource.get(another)); + this.environment.getPropertySources().addLast(OriginCapablePropertySource.get(another)); InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( "test.property", "invalid", "This is not valid."); FailureAnalysis analysis = performAnalysis(failure); assertCommonParts(failure, analysis); - assertThat(analysis.getAction()) - .contains("Review the value of the property with the provided reason."); + assertThat(analysis.getAction()).contains("Review the value of the property with the provided reason."); assertThat(analysis.getDescription()) - .contains("Additionally, this property is also set in the following " - + "property sources:") - .contains("In 'additional' with the value 'valid'").contains( - "In 'another' with the value 'test' (originating from 'TestOrigin test.property')"); + .contains("Additionally, this property is also set in the following " + "property sources:") + .contains("In 'additional' with the value 'valid'") + .contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')"); } @Test @@ -113,22 +99,19 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { assertThat(performAnalysis(failure)).isNull(); } - private void assertCommonParts(InvalidConfigurationPropertyValueException failure, - FailureAnalysis analysis) { - assertThat(analysis.getDescription()).contains("test.property") - .contains("invalid").contains("TestOrigin test.property"); + private void assertCommonParts(InvalidConfigurationPropertyValueException failure, FailureAnalysis analysis) { + assertThat(analysis.getDescription()).contains("test.property").contains("invalid") + .contains("TestOrigin test.property"); assertThat(analysis.getCause()).isSameAs(failure); } - private FailureAnalysis performAnalysis( - InvalidConfigurationPropertyValueException failure) { + private FailureAnalysis performAnalysis(InvalidConfigurationPropertyValueException failure) { InvalidConfigurationPropertyValueFailureAnalyzer analyzer = new InvalidConfigurationPropertyValueFailureAnalyzer(); analyzer.setEnvironment(this.environment); return analyzer.analyze(failure); } - static class OriginCapablePropertySource extends EnumerablePropertySource - implements OriginLookup { + static class OriginCapablePropertySource extends EnumerablePropertySource implements OriginLookup { private final EnumerablePropertySource propertySource; @@ -159,8 +142,7 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { }; } - static OriginCapablePropertySource get( - EnumerablePropertySource propertySource) { + static OriginCapablePropertySource get(EnumerablePropertySource propertySource) { return new OriginCapablePropertySource<>(propertySource); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java index e00fde0a8a9..2e80d8953d0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java @@ -45,10 +45,8 @@ public class NoSuchMethodFailureAnalyzerTests { FailureAnalysis analysis = new NoSuchMethodFailureAnalyzer().analyze(failure); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) - .contains(NoSuchMethodFailureAnalyzerTests.class.getName() - + ".createFailure(") - .contains("javax.servlet.ServletContext.addServlet" - + "(Ljava/lang/String;Ljavax/servlet/Servlet;)" + .contains(NoSuchMethodFailureAnalyzerTests.class.getName() + ".createFailure(") + .contains("javax.servlet.ServletContext.addServlet" + "(Ljava/lang/String;Ljavax/servlet/Servlet;)" + "Ljavax/servlet/ServletRegistration$Dynamic;") .contains("class, javax.servlet.ServletContext,"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java index 409fb712205..e44ec705995 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java @@ -43,69 +43,56 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { @Test public void failureAnalysisForFieldConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(FieldConsumer.class)); - assertThat(failureAnalysis.getDescription()) - .startsWith("Field testBean in " + FieldConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(FieldConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith( + "Field testBean in " + FieldConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForMethodConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(MethodConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Parameter 0 of method consumer in " + MethodConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(MethodConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of method consumer in " + + MethodConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForConstructorConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(ConstructorConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Parameter 0 of constructor in " + ConstructorConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ConstructorConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of constructor in " + + ConstructorConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForObjectProviderMethodConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(ObjectProviderMethodConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Method consumer in " + ObjectProviderMethodConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ObjectProviderMethodConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Method consumer in " + + ObjectProviderMethodConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForXmlConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(XmlConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Parameter 0 of constructor in " + TestBeanConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(XmlConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of constructor in " + + TestBeanConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForObjectProviderConstructorConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(ObjectProviderConstructorConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Constructor in " + ObjectProviderConstructorConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ObjectProviderConstructorConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Constructor in " + + ObjectProviderConstructorConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } private BeanCreationException createFailure(Class consumer) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { context.register(DuplicateBeansProducer.class, consumer); - context.setParent( - new AnnotationConfigApplicationContext(ParentProducer.class)); + context.setParent(new AnnotationConfigApplicationContext(ParentProducer.class)); try { context.refresh(); } @@ -123,14 +110,11 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { private void assertFoundBeans(FailureAnalysis analysis) { assertThat(analysis.getDescription()) - .contains("beanOne: defined by method 'beanOne' in " - + DuplicateBeansProducer.class.getName()); + .contains("beanOne: defined by method 'beanOne' in " + DuplicateBeansProducer.class.getName()); assertThat(analysis.getDescription()) - .contains("beanTwo: defined by method 'beanTwo' in " - + DuplicateBeansProducer.class.getName()); + .contains("beanTwo: defined by method 'beanTwo' in " + DuplicateBeansProducer.class.getName()); assertThat(analysis.getDescription()) - .contains("beanThree: defined by method 'beanThree' in " - + ParentProducer.class.getName()); + .contains("beanThree: defined by method 'beanThree' in " + ParentProducer.class.getName()); assertThat(analysis.getDescription()).contains("barTestBean"); assertThat(analysis.getDescription()).contains("fooTestBean"); assertThat(analysis.getDescription()).contains("xmlTestBean"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java index 649fbb6758b..2e4c9a677b7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,30 +55,25 @@ public class UnboundConfigurationPropertyFailureAnalyzerTests { @Test public void bindExceptionDueToUnboundElements() { - FailureAnalysis analysis = performAnalysis( - UnboundElementsFailureConfiguration.class, "test.foo.listValue[0]=hello", - "test.foo.listValue[2]=world"); - assertThat(analysis.getDescription()).contains(failure("test.foo.listvalue[2]", - "world", "\"test.foo.listValue[2]\" from property source \"test\"", - "The elements [test.foo.listvalue[2]] were left unbound.")); + FailureAnalysis analysis = performAnalysis(UnboundElementsFailureConfiguration.class, + "test.foo.listValue[0]=hello", "test.foo.listValue[2]=world"); + assertThat(analysis.getDescription()).contains( + failure("test.foo.listvalue[2]", "world", "\"test.foo.listValue[2]\" from property source \"test\"", + "The elements [test.foo.listvalue[2]] were left unbound.")); } - private static String failure(String property, String value, String origin, - String reason) { - return String.format( - "Property: %s%n Value: %s%n Origin: %s%n Reason: %s", property, - value, origin, reason); + private static String failure(String property, String value, String origin, String reason) { + return String.format("Property: %s%n Value: %s%n Origin: %s%n Reason: %s", property, value, origin, + reason); } - private FailureAnalysis performAnalysis(Class configuration, - String... environment) { + private FailureAnalysis performAnalysis(Class configuration, String... environment) { BeanCreationException failure = createFailure(configuration, environment); assertThat(failure).isNotNull(); return new UnboundConfigurationPropertyFailureAnalyzer().analyze(failure); } - private BeanCreationException createFailure(Class configuration, - String... environment) { + private BeanCreationException createFailure(Class configuration, String... environment) { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); addEnvironment(context, environment); @@ -92,8 +87,7 @@ public class UnboundConfigurationPropertyFailureAnalyzerTests { } } - private void addEnvironment(AnnotationConfigApplicationContext context, - String[] environment) { + private void addEnvironment(AnnotationConfigApplicationContext context, String[] environment) { MutablePropertySources sources = context.getEnvironment().getPropertySources(); Map map = new HashMap<>(); for (String pair : environment) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java index d3baf2835ff..af5e9d70fd2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java @@ -41,17 +41,13 @@ public class ValidationExceptionFailureAnalyzerTests { @Test public void validatedPropertiesTest() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new AnnotationConfigApplicationContext( - TestConfiguration.class).close()) - .satisfies((ex) -> assertThat( - new ValidationExceptionFailureAnalyzer().analyze(ex)) - .isNotNull()); + .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) + .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); } @Test public void nonValidatedPropertiesTest() { - new AnnotationConfigApplicationContext(NonValidatedTestConfiguration.class) - .close(); + new AnnotationConfigApplicationContext(NonValidatedTestConfiguration.class).close(); } @EnableConfigurationProperties(TestProperties.class) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java index 7ccb8b379cc..71de086c23c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,12 +38,9 @@ public class NoSnakeYamlPropertySourceLoaderTests { @Test public void load() throws Exception { - ByteArrayResource resource = new ByteArrayResource( - "foo:\n bar: spam".getBytes()); - assertThatIllegalStateException() - .isThrownBy(() -> this.loader.load("resource", resource)) - .withMessageContaining( - "Attempted to load resource but snakeyaml was not found on the classpath"); + ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); + assertThatIllegalStateException().isThrownBy(() -> this.loader.load("resource", resource)) + .withMessageContaining("Attempted to load resource but snakeyaml was not found on the classpath"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java index 6891660ad7f..c6afbe9c25b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class OriginTrackedMapPropertySourceTests { private Map map = new LinkedHashMap<>(); - private OriginTrackedMapPropertySource source = new OriginTrackedMapPropertySource( - "test", this.map); + private OriginTrackedMapPropertySource source = new OriginTrackedMapPropertySource("test", this.map); private Origin origin = mock(Origin.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java index 29ea2c69c7b..2256ca25b0b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ public class OriginTrackedPropertiesLoaderTests { public void compareToJavaProperties() throws Exception { Properties java = PropertiesLoaderUtils.loadProperties(this.resource); Properties ours = new Properties(); - new OriginTrackedPropertiesLoader(this.resource).load(false) - .forEach((k, v) -> ours.put(k, v.getValue())); + new OriginTrackedPropertiesLoader(this.resource).load(false).forEach((k, v) -> ours.put(k, v.getValue())); assertThat(ours).isEqualTo(java); } @@ -89,10 +88,8 @@ public class OriginTrackedPropertiesLoaderTests { @Test public void getMalformedUnicodeProperty() throws Exception { // gh-12716 - ClassPathResource resource = new ClassPathResource( - "test-properties-malformed-unicode.properties", getClass()); - assertThatIllegalStateException() - .isThrownBy(() -> new OriginTrackedPropertiesLoader(resource).load()) + ClassPathResource resource = new ClassPathResource("test-properties-malformed-unicode.properties", getClass()); + assertThatIllegalStateException().isThrownBy(() -> new OriginTrackedPropertiesLoader(resource).load()) .withMessageContaining("Malformed \\uxxxx encoding"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java index 89455e2b92c..ac536c964d7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java @@ -86,8 +86,7 @@ public class OriginTrackedYamlLoaderTests { @Test public void processMultiline() { OriginTrackedValue education = getValue("education"); - assertThat(education.toString()) - .isEqualTo("4 GCSEs\n3 A-Levels\nBSc in the Internet of Things\n"); + assertThat(education.toString()).isEqualTo("4 GCSEs\n3 A-Levels\nBSc in the Internet of Things\n"); assertThat(getLocation(education)).isEqualTo("16:12"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java index d5c7e0e37cc..f8b37780a78 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class PropertiesPropertySourceLoaderTests { @Test public void getFileExtensions() { - assertThat(this.loader.getFileExtensions()) - .isEqualTo(new String[] { "properties", "xml" }); + assertThat(this.loader.getFileExtensions()).isEqualTo(new String[] { "properties", "xml" }); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index 4fe37dc780a..91107ec7f89 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,10 +45,9 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { @Test public void error() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.application.json=foo:bar"); - assertThatExceptionOfType(JsonParseException.class).isThrownBy( - () -> this.processor.postProcessEnvironment(this.environment, null)) + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); + assertThatExceptionOfType(JsonParseException.class) + .isThrownBy(() -> this.processor.postProcessEnvironment(this.environment, null)) .withMessageContaining("Cannot parse JSON"); } @@ -62,8 +61,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { @Test public void empty() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.application.json={}"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={}"); this.processor.postProcessEnvironment(this.environment, null); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @@ -120,8 +118,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[{\"bar\":\"spam\"}]}"); this.processor.postProcessEnvironment(this.environment, null); - assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")) - .isEqualTo("spam"); + assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")).isEqualTo("spam"); } @Test @@ -130,12 +127,9 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={\"foo\":\"bar\"}"); this.processor.postProcessEnvironment(this.environment, null); - PropertySource propertySource = this.environment.getPropertySources() - .get("spring.application.json"); - PropertySourceOrigin origin = (PropertySourceOrigin) PropertySourceOrigin - .get(propertySource, "foo"); - assertThat(origin.getPropertySource().getName()) - .isEqualTo("Inlined Test Properties"); + PropertySource propertySource = this.environment.getPropertySources().get("spring.application.json"); + PropertySourceOrigin origin = (PropertySourceOrigin) PropertySourceOrigin.get(propertySource, "foo"); + assertThat(origin.getPropertySource().getName()).isEqualTo("Inlined Test Properties"); assertThat(origin.getPropertyName()).isEqualTo("spring.application.json"); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEqualTo("bar"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java index 6010a362e23..be580546a86 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,18 +49,15 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { public void postProcessShouldReplaceSystemEnvironmentPropertySource() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); postProcessor.postProcessEnvironment(this.environment, null); - PropertySource replaced = this.environment.getPropertySources() - .get("systemEnvironment"); - assertThat(replaced) - .isInstanceOf(OriginAwareSystemEnvironmentPropertySource.class); + PropertySource replaced = this.environment.getPropertySources().get("systemEnvironment"); + assertThat(replaced).isInstanceOf(OriginAwareSystemEnvironmentPropertySource.class); } @Test @SuppressWarnings("unchecked") public void replacedPropertySourceShouldBeOriginAware() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); - PropertySource original = this.environment.getPropertySources() - .get("systemEnvironment"); + PropertySource original = this.environment.getPropertySources().get("systemEnvironment"); postProcessor.postProcessEnvironment(this.environment, null); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment .getPropertySources().get("systemEnvironment"); @@ -69,8 +66,7 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { originalMap.forEach((key, value) -> { Object actual = replacedMap.get(key); assertThat(actual).isEqualTo(value); - assertThat(replaced.getOrigin(key)) - .isInstanceOf(SystemEnvironmentOrigin.class); + assertThat(replaced.getOrigin(key)).isInstanceOf(SystemEnvironmentOrigin.class); }); } @@ -92,8 +88,7 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { postProcessor.postProcessEnvironment(this.environment, null); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment .getPropertySources().get("systemEnvironment"); - SystemEnvironmentOrigin origin = (SystemEnvironmentOrigin) replaced - .getOrigin("foo.bar.baz"); + SystemEnvironmentOrigin origin = (SystemEnvironmentOrigin) replaced.getOrigin("foo.bar.baz"); assertThat(origin.getProperty()).isEqualTo("FOO_BAR_BAZ"); assertThat(replaced.getProperty("foo.bar.baz")).isEqualTo("hello"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java index 22a72bffe38..bcc5d109cf8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java @@ -43,8 +43,7 @@ public class YamlPropertySourceLoaderTests { @Test public void load() throws Exception { - ByteArrayResource resource = new ByteArrayResource( - "foo:\n bar: spam".getBytes()); + ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); PropertySource source = this.loader.load("resource", resource).get(0); assertThat(source).isNotNull(); assertThat(source.getProperty("foo.bar")).isEqualTo("spam"); @@ -59,11 +58,10 @@ public class YamlPropertySourceLoaderTests { expected.add(String.valueOf(c)); } ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes()); - EnumerablePropertySource source = (EnumerablePropertySource) this.loader - .load("resource", resource).get(0); + EnumerablePropertySource source = (EnumerablePropertySource) this.loader.load("resource", resource) + .get(0); assertThat(source).isNotNull(); - assertThat(source.getPropertyNames()) - .isEqualTo(StringUtils.toStringArray(expected)); + assertThat(source.getPropertyNames()).isEqualTo(StringUtils.toStringArray(expected)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java index 66c2704f52f..cb66aaaeaea 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,15 +35,13 @@ public class BuildPropertiesTests { @Test public void basicInfo() { Instant instant = Instant.now(); - BuildProperties properties = new BuildProperties(createProperties("com.example", - "demo", "0.0.1", DateTimeFormatter.ISO_INSTANT.format(instant))); + BuildProperties properties = new BuildProperties( + createProperties("com.example", "demo", "0.0.1", DateTimeFormatter.ISO_INSTANT.format(instant))); assertThat(properties.getGroup()).isEqualTo("com.example"); assertThat(properties.getArtifact()).isEqualTo("demo"); assertThat(properties.getVersion()).isEqualTo("0.0.1"); - assertThat(properties.getTime()) - .isEqualTo(instant.truncatedTo(ChronoUnit.MILLIS)); - assertThat(properties.get("time")) - .isEqualTo(String.valueOf(instant.toEpochMilli())); + assertThat(properties.getTime()).isEqualTo(instant.truncatedTo(ChronoUnit.MILLIS)); + assertThat(properties.get("time")).isEqualTo(String.valueOf(instant.toEpochMilli())); } @Test @@ -55,8 +53,7 @@ public class BuildPropertiesTests { assertThat(properties.getTime()).isNull(); } - private static Properties createProperties(String group, String artifact, - String version, String buildTime) { + private static Properties createProperties(String group, String artifact, String version, String buildTime) { Properties properties = new Properties(); properties.put("group", group); properties.put("artifact", artifact); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java index 3817575d02c..da2c0c3db36 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class GitPropertiesTests { @Test public void coerceEpochSecond() { - GitProperties properties = new GitProperties( - createProperties("master", "abcdefg", null, "1457527123")); + GitProperties properties = new GitProperties(createProperties("master", "abcdefg", null, "1457527123")); assertThat(properties.getCommitTime()).isNotNull(); assertThat(properties.get("commit.time")).isEqualTo("1457527123000"); assertThat(properties.getCommitTime().toEpochMilli()).isEqualTo(1457527123000L); @@ -83,22 +82,20 @@ public class GitPropertiesTests { @Test public void shortenCommitIdShorterThan7() { - GitProperties properties = new GitProperties( - createProperties("master", "abc", null, "1457527123")); + GitProperties properties = new GitProperties(createProperties("master", "abc", null, "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abc"); assertThat(properties.getShortCommitId()).isEqualTo("abc"); } @Test public void shortenCommitIdLongerThan7() { - GitProperties properties = new GitProperties( - createProperties("master", "abcdefghijklmno", null, "1457527123")); + GitProperties properties = new GitProperties(createProperties("master", "abcdefghijklmno", null, "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abcdefghijklmno"); assertThat(properties.getShortCommitId()).isEqualTo("abcdefg"); } - private static Properties createProperties(String branch, String commitId, - String commitIdAbbrev, String commitTime) { + private static Properties createProperties(String branch, String commitId, String commitIdAbbrev, + String commitTime) { Properties properties = new Properties(); properties.put("branch", branch); properties.put("commit.id", commitId); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java index 0ada1aff568..b9eb272c749 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ public class InfoPropertiesTests { Properties p = new Properties(); p.put("foo", "bar"); InfoProperties infoProperties = new InfoProperties(p); - assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(infoProperties.iterator()::remove); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(infoProperties.iterator()::remove); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java index 7a9af5f2dfc..635dd81f0b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java @@ -74,8 +74,8 @@ public class JsonComponentModuleTests { @Test public void moduleShouldAllowInnerAbstractClasses() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - JsonComponentModule.class, ComponentWithInnerAbstractClass.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JsonComponentModule.class, + ComponentWithInnerAbstractClass.class); JsonComponentModule module = context.getBean(JsonComponentModule.class); assertSerialize(module); context.close(); @@ -107,8 +107,7 @@ public class JsonComponentModuleTests { public void moduleShouldRegisterOnlyForSpecifiedClasses() throws Exception { load(NameAndCareerJsonComponent.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); - assertSerialize(module, new NameAndCareer("spring", "developer"), - "{\"name\":\"spring\"}"); + assertSerialize(module, new NameAndCareer("spring", "developer"), "{\"name\":\"spring\"}"); assertSerialize(module); assertDeserializeForSpecifiedClasses(module); } @@ -121,8 +120,7 @@ public class JsonComponentModuleTests { this.context = context; } - private void assertSerialize(Module module, Name value, String expectedJson) - throws Exception { + private void assertSerialize(Module module, Name value, String expectedJson) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); String json = mapper.writeValueAsString(value); @@ -130,27 +128,24 @@ public class JsonComponentModuleTests { } private void assertSerialize(Module module) throws Exception { - assertSerialize(module, new NameAndAge("spring", 100), - "{\"name\":\"spring\",\"age\":100}"); + assertSerialize(module, new NameAndAge("spring", 100), "{\"name\":\"spring\",\"age\":100}"); } private void assertDeserialize(Module module) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); - NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", - NameAndAge.class); + NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class); assertThat(nameAndAge.getName()).isEqualTo("spring"); assertThat(nameAndAge.getAge()).isEqualTo(100); } - private void assertDeserializeForSpecifiedClasses(JsonComponentModule module) - throws IOException { + private void assertDeserializeForSpecifiedClasses(JsonComponentModule module) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); - assertThatExceptionOfType(JsonMappingException.class).isThrownBy(() -> mapper - .readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class)); - NameAndCareer nameAndCareer = mapper.readValue( - "{\"name\":\"spring\",\"career\":\"developer\"}", NameAndCareer.class); + assertThatExceptionOfType(JsonMappingException.class) + .isThrownBy(() -> mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class)); + NameAndCareer nameAndCareer = mapper.readValue("{\"name\":\"spring\",\"career\":\"developer\"}", + NameAndCareer.class); assertThat(nameAndCareer.getName()).isEqualTo("spring"); assertThat(nameAndCareer.getCareer()).isEqualTo("developer"); } @@ -169,8 +164,7 @@ public class JsonComponentModuleTests { mapper.registerModule(module); TypeReference> typeRef = new TypeReference>() { }; - Map map = mapper.readValue("{\"spring is 100\": true}", - typeRef); + Map map = mapper.readValue("{\"spring is 100\": true}", typeRef); assertThat(map).containsEntry(new NameAndAge("spring", 100), true); } @@ -187,8 +181,7 @@ public class JsonComponentModuleTests { @JsonComponent static class ComponentWithInnerAbstractClass { - private abstract static class AbstractSerializer - extends NameAndAgeJsonComponent.Serializer { + private abstract static class AbstractSerializer extends NameAndAgeJsonComponent.Serializer { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java index acbffe5a7b6..3a94fb019f4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,7 @@ public class JsonObjectDeserializerTests { module.addDeserializer(NameAndAge.class, deserializer); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); - NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", - NameAndAge.class); + NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class); assertThat(nameAndAge.getName()).isEqualTo("spring"); assertThat(nameAndAge.getAge()).isEqualTo(100); } @@ -67,8 +66,8 @@ public class JsonObjectDeserializerTests { @Test public void nullSafeValueWhenClassIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) .withMessageContaining("Type must not be null"); } @@ -132,8 +131,7 @@ public class JsonObjectDeserializerTests { public void nullSafeValueWhenClassIsBigDecimalShouldReturnBigDecimal() { JsonNode node = mock(JsonNode.class); given(node.decimalValue()).willReturn(BigDecimal.TEN); - BigDecimal value = this.testDeserializer.testNullSafeValue(node, - BigDecimal.class); + BigDecimal value = this.testDeserializer.testNullSafeValue(node, BigDecimal.class); assertThat(value).isEqualTo(BigDecimal.TEN); } @@ -141,24 +139,21 @@ public class JsonObjectDeserializerTests { public void nullSafeValueWhenClassIsBigIntegerShouldReturnBigInteger() { JsonNode node = mock(JsonNode.class); given(node.bigIntegerValue()).willReturn(BigInteger.TEN); - BigInteger value = this.testDeserializer.testNullSafeValue(node, - BigInteger.class); + BigInteger value = this.testDeserializer.testNullSafeValue(node, BigInteger.class); assertThat(value).isEqualTo(BigInteger.TEN); } @Test public void nullSafeValueWhenClassIsUnknownShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.testDeserializer - .testNullSafeValue(mock(JsonNode.class), InputStream.class)) + .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class)) .withMessageContaining("Unsupported value type java.io.InputStream"); } @Test public void getRequiredNodeWhenTreeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.testDeserializer.testGetRequiredNode(null, "test")) + assertThatIllegalArgumentException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(null, "test")) .withMessageContaining("Tree must not be null"); } @@ -166,8 +161,7 @@ public class JsonObjectDeserializerTests { public void getRequiredNodeWhenNodeIsNullShouldThrowException() { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(null); - assertThatIllegalStateException() - .isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) + assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) .withMessageContaining("Missing JSON field 'test'"); } @@ -175,8 +169,7 @@ public class JsonObjectDeserializerTests { public void getRequiredNodeWhenNodeIsNullNodeShouldThrowException() { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(NullNode.instance); - assertThatIllegalStateException() - .isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) + assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) .withMessageContaining("Missing JSON field 'test'"); } @@ -185,15 +178,14 @@ public class JsonObjectDeserializerTests { JsonNode node = mock(JsonNode.class); JsonNode tree = node; given(tree.get("test")).willReturn(node); - assertThat(this.testDeserializer.testGetRequiredNode(tree, "test")) - .isEqualTo(node); + assertThat(this.testDeserializer.testGetRequiredNode(tree, "test")).isEqualTo(node); } static class TestJsonObjectDeserializer extends JsonObjectDeserializer { @Override - protected T deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) { + protected T deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) { return null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java index cc6c42beb38..8f75e7a6c8b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ public class NameAndAgeJsonComponent { public static class Serializer extends JsonObjectSerializer { @Override - protected void serializeObject(NameAndAge value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + protected void serializeObject(NameAndAge value, JsonGenerator jgen, SerializerProvider provider) + throws IOException { jgen.writeStringField("name", value.getName()); jgen.writeNumberField("age", value.getAge()); } @@ -47,9 +47,8 @@ public class NameAndAgeJsonComponent { public static class Deserializer extends JsonObjectDeserializer { @Override - protected NameAndAge deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException { + protected NameAndAge deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) throws IOException { String name = nullSafeValue(tree.get("name"), String.class); Integer age = nullSafeValue(tree.get("age"), Integer.class); return new NameAndAge(name, age); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonKeyComponent.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonKeyComponent.java index 10d2dc2d6b4..4c7e801dc68 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonKeyComponent.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonKeyComponent.java @@ -35,8 +35,7 @@ public class NameAndAgeJsonKeyComponent { public static class Serializer extends JsonSerializer { @Override - public void serialize(NameAndAge value, JsonGenerator jgen, - SerializerProvider serializers) throws IOException { + public void serialize(NameAndAge value, JsonGenerator jgen, SerializerProvider serializers) throws IOException { jgen.writeFieldName(value.asKey()); } @@ -45,8 +44,7 @@ public class NameAndAgeJsonKeyComponent { public static class Deserializer extends KeyDeserializer { @Override - public NameAndAge deserializeKey(String key, DeserializationContext ctxt) - throws IOException { + public NameAndAge deserializeKey(String key, DeserializationContext ctxt) throws IOException { String[] keys = key.split("is"); return new NameAndAge(keys[0].trim(), Integer.valueOf(keys[1].trim())); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndCareerJsonComponent.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndCareerJsonComponent.java index 9eeafc17a55..3a2dc131496 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndCareerJsonComponent.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndCareerJsonComponent.java @@ -36,8 +36,7 @@ public class NameAndCareerJsonComponent { public static class Serializer extends JsonObjectSerializer { @Override - protected void serializeObject(Name value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + protected void serializeObject(Name value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStringField("name", value.getName()); } @@ -46,9 +45,8 @@ public class NameAndCareerJsonComponent { public static class Deserializer extends JsonObjectDeserializer { @Override - protected Name deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException { + protected Name deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) throws IOException { String name = nullSafeValue(tree.get("name"), String.class); String career = nullSafeValue(tree.get("career"), String.class); return new NameAndCareer(name, career); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java index c8da2c42087..510c60b9fcc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,26 +55,22 @@ public class DataSourceBuilderTests { @Test public void defaultToTomcatIfHikariIsNotAvailable() { - this.dataSource = DataSourceBuilder - .create(new HidePackagesClassLoader("com.zaxxer.hikari")) - .url("jdbc:h2:test").build(); - assertThat(this.dataSource) - .isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); + this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")).url("jdbc:h2:test") + .build(); + assertThat(this.dataSource).isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); } @Test public void defaultToCommonsDbcp2AsLastResort() { this.dataSource = DataSourceBuilder - .create(new HidePackagesClassLoader("com.zaxxer.hikari", - "org.apache.tomcat.jdbc.pool")) + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) .url("jdbc:h2:test").build(); assertThat(this.dataSource).isInstanceOf(BasicDataSource.class); } @Test public void specificTypeOfDataSource() { - HikariDataSource hikariDataSource = DataSourceBuilder.create() - .type(HikariDataSource.class).build(); + HikariDataSource hikariDataSource = DataSourceBuilder.create().type(HikariDataSource.class).build(); assertThat(hikariDataSource).isInstanceOf(HikariDataSource.class); } @@ -88,8 +84,7 @@ public class DataSourceBuilderTests { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (Arrays.stream(this.hiddenPackages).anyMatch(name::startsWith)) { throw new ClassNotFoundException(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java index 17a02043803..768b864cdfc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,16 +42,14 @@ public class DataSourceUnwrapperNoSpringJdbcTests { public void unwrapWithProxy() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); - assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test public void unwrapDataSourceProxy() { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); - assertThat(DataSourceUnwrapper.unwrap(actual, DataSourceProxy.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(actual, DataSourceProxy.class)).isSameAs(dataSource); } private DataSource wrapInProxy(DataSource dataSource) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java index 4d1bae4104e..737840893a4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java @@ -43,65 +43,54 @@ public class DataSourceUnwrapperTests { @Test public void unwrapWithTarget() { DataSource dataSource = new HikariDataSource(); - assertThat(DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class)).isSameAs(dataSource); } @Test public void unwrapWithWrongTarget() { DataSource dataSource = new HikariDataSource(); - assertThat( - DataSourceUnwrapper.unwrap(dataSource, SingleConnectionDataSource.class)) - .isNull(); + assertThat(DataSourceUnwrapper.unwrap(dataSource, SingleConnectionDataSource.class)).isNull(); } @Test public void unwrapWithDelegate() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInDelegate(wrapInDelegate(dataSource)); - assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test public void unwrapWithProxy() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); - assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test public void unwrapWithProxyAndDelegate() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(dataSource)); - assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test public void unwrapWithSeveralLevelOfWrapping() { DataSource dataSource = new HikariDataSource(); - DataSource actual = wrapInProxy( - wrapInDelegate(wrapInDelegate(wrapInProxy(wrapInDelegate(dataSource))))); - assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)) - .isSameAs(dataSource); + DataSource actual = wrapInProxy(wrapInDelegate(wrapInDelegate(wrapInProxy(wrapInDelegate(dataSource))))); + assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test public void unwrapDataSourceProxy() { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInDelegate(wrapInProxy(dataSource)); - assertThat(DataSourceUnwrapper.unwrap(actual, DataSourceProxy.class)) - .isSameAs(dataSource); + assertThat(DataSourceUnwrapper.unwrap(actual, DataSourceProxy.class)).isSameAs(dataSource); } @Test - public void unwrappingIsNotAttemptedWhenDataSourceIsNotWrapperForTarget() - throws SQLException { + public void unwrappingIsNotAttemptedWhenDataSourceIsNotWrapperForTarget() throws SQLException { DataSource dataSource = mock(DataSource.class); - DataSource actual = DataSourceUnwrapper.unwrap(dataSource, - HikariDataSource.class); + DataSource actual = DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class); assertThat(actual).isNull(); verify(dataSource).isWrapperFor(HikariDataSource.class); verifyNoMoreInteractions(dataSource); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java index 3ecd28e6027..c6b1afb75e5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java @@ -43,11 +43,9 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class DatabaseDriverClassNameTests { - private static final Set EXCLUDED_DRIVERS = Collections - .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.ORACLE, - DatabaseDriver.DB2, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, - DatabaseDriver.HANA, DatabaseDriver.TERADATA, - DatabaseDriver.REDSHIFT)); + private static final Set EXCLUDED_DRIVERS = Collections.unmodifiableSet( + EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.ORACLE, DatabaseDriver.DB2, DatabaseDriver.DB2_AS400, + DatabaseDriver.INFORMIX, DatabaseDriver.HANA, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); private final String className; @@ -61,18 +59,16 @@ public class DatabaseDriverClassNameTests { if (EXCLUDED_DRIVERS.contains(databaseDriver)) { continue; } - parameters.add(new Object[] { databaseDriver, - databaseDriver.getDriverClassName(), Driver.class }); + parameters.add(new Object[] { databaseDriver, databaseDriver.getDriverClassName(), Driver.class }); if (databaseDriver.getXaDataSourceClassName() != null) { - parameters.add(new Object[] { databaseDriver, - databaseDriver.getXaDataSourceClassName(), XADataSource.class }); + parameters.add( + new Object[] { databaseDriver, databaseDriver.getXaDataSourceClassName(), XADataSource.class }); } } return parameters; } - public DatabaseDriverClassNameTests(DatabaseDriver driver, String className, - Class requiredType) { + public DatabaseDriverClassNameTests(DatabaseDriver driver, String className, Class requiredType) { this.className = className; this.requiredType = requiredType; } @@ -85,8 +81,7 @@ public class DatabaseDriverClassNameTests { private List getInterfaceNames(String className) throws IOException { // Use ASM to avoid unwanted side-effects of loading JDBC drivers - ClassReader classReader = new ClassReader( - getClass().getResourceAsStream("/" + className + ".class")); + ClassReader classReader = new ClassReader(getClass().getResourceAsStream("/" + className + ".class")); List interfaceNames = new ArrayList<>(); for (String name : classReader.getInterfaces()) { interfaceNames.add(name); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java index a9697d54bdb..4d14659f49e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java @@ -32,15 +32,13 @@ public class DatabaseDriverTests { @Test public void classNameForKnownDatabase() { - String driverClassName = DatabaseDriver - .fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName(); + String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName(); assertThat(driverClassName).isEqualTo("org.postgresql.Driver"); } @Test public void nullClassNameForUnknownDatabase() { - String driverClassName = DatabaseDriver - .fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName(); + String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName(); assertThat(driverClassName).isNull(); } @@ -52,8 +50,7 @@ public class DatabaseDriverTests { @Test public void failureOnMalformedJdbcUrl() { - assertThatIllegalArgumentException() - .isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url")) + assertThatIllegalArgumentException().isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url")) .withMessageContaining("URL must start with"); } @@ -65,59 +62,36 @@ public class DatabaseDriverTests { @Test public void databaseProductNameLookups() { - assertThat(DatabaseDriver.fromProductName("newone")) - .isEqualTo(DatabaseDriver.UNKNOWN); - assertThat(DatabaseDriver.fromProductName("Apache Derby")) - .isEqualTo(DatabaseDriver.DERBY); + assertThat(DatabaseDriver.fromProductName("newone")).isEqualTo(DatabaseDriver.UNKNOWN); + assertThat(DatabaseDriver.fromProductName("Apache Derby")).isEqualTo(DatabaseDriver.DERBY); assertThat(DatabaseDriver.fromProductName("H2")).isEqualTo(DatabaseDriver.H2); assertThat(DatabaseDriver.fromProductName("HDB")).isEqualTo(DatabaseDriver.HANA); - assertThat(DatabaseDriver.fromProductName("HSQL Database Engine")) - .isEqualTo(DatabaseDriver.HSQLDB); - assertThat(DatabaseDriver.fromProductName("SQLite")) - .isEqualTo(DatabaseDriver.SQLITE); - assertThat(DatabaseDriver.fromProductName("MySQL")) - .isEqualTo(DatabaseDriver.MYSQL); - assertThat(DatabaseDriver.fromProductName("Oracle")) - .isEqualTo(DatabaseDriver.ORACLE); - assertThat(DatabaseDriver.fromProductName("PostgreSQL")) - .isEqualTo(DatabaseDriver.POSTGRESQL); - assertThat(DatabaseDriver.fromProductName("Amazon Redshift")) - .isEqualTo(DatabaseDriver.REDSHIFT); - assertThat(DatabaseDriver.fromProductName("Microsoft SQL Server")) - .isEqualTo(DatabaseDriver.SQLSERVER); - assertThat(DatabaseDriver.fromProductName("SQL SERVER")) - .isEqualTo(DatabaseDriver.SQLSERVER); + assertThat(DatabaseDriver.fromProductName("HSQL Database Engine")).isEqualTo(DatabaseDriver.HSQLDB); + assertThat(DatabaseDriver.fromProductName("SQLite")).isEqualTo(DatabaseDriver.SQLITE); + assertThat(DatabaseDriver.fromProductName("MySQL")).isEqualTo(DatabaseDriver.MYSQL); + assertThat(DatabaseDriver.fromProductName("Oracle")).isEqualTo(DatabaseDriver.ORACLE); + assertThat(DatabaseDriver.fromProductName("PostgreSQL")).isEqualTo(DatabaseDriver.POSTGRESQL); + assertThat(DatabaseDriver.fromProductName("Amazon Redshift")).isEqualTo(DatabaseDriver.REDSHIFT); + assertThat(DatabaseDriver.fromProductName("Microsoft SQL Server")).isEqualTo(DatabaseDriver.SQLSERVER); + assertThat(DatabaseDriver.fromProductName("SQL SERVER")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromProductName("DB2")).isEqualTo(DatabaseDriver.DB2); - assertThat(DatabaseDriver.fromProductName("Firebird 2.5.WI")) - .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromProductName("Firebird 2.1.LI")) - .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromProductName("DB2/LINUXX8664")) - .isEqualTo(DatabaseDriver.DB2); - assertThat(DatabaseDriver.fromProductName("DB2 UDB for AS/400")) - .isEqualTo(DatabaseDriver.DB2_AS400); - assertThat(DatabaseDriver.fromProductName("DB3 XDB for AS/400")) - .isEqualTo(DatabaseDriver.DB2_AS400); - assertThat(DatabaseDriver.fromProductName("Teradata")) - .isEqualTo(DatabaseDriver.TERADATA); - assertThat(DatabaseDriver.fromProductName("Informix Dynamic Server")) - .isEqualTo(DatabaseDriver.INFORMIX); + assertThat(DatabaseDriver.fromProductName("Firebird 2.5.WI")).isEqualTo(DatabaseDriver.FIREBIRD); + assertThat(DatabaseDriver.fromProductName("Firebird 2.1.LI")).isEqualTo(DatabaseDriver.FIREBIRD); + assertThat(DatabaseDriver.fromProductName("DB2/LINUXX8664")).isEqualTo(DatabaseDriver.DB2); + assertThat(DatabaseDriver.fromProductName("DB2 UDB for AS/400")).isEqualTo(DatabaseDriver.DB2_AS400); + assertThat(DatabaseDriver.fromProductName("DB3 XDB for AS/400")).isEqualTo(DatabaseDriver.DB2_AS400); + assertThat(DatabaseDriver.fromProductName("Teradata")).isEqualTo(DatabaseDriver.TERADATA); + assertThat(DatabaseDriver.fromProductName("Informix Dynamic Server")).isEqualTo(DatabaseDriver.INFORMIX); } @Test public void databaseJdbcUrlLookups() { - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:newone://localhost")) - .isEqualTo(DatabaseDriver.UNKNOWN); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:derby:sample")) - .isEqualTo(DatabaseDriver.DERBY); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:h2:~/sample")) - .isEqualTo(DatabaseDriver.H2); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:hsqldb:hsql://localhost")) - .isEqualTo(DatabaseDriver.HSQLDB); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")) - .isEqualTo(DatabaseDriver.SQLITE); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")) - .isEqualTo(DatabaseDriver.MYSQL); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:newone://localhost")).isEqualTo(DatabaseDriver.UNKNOWN); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:derby:sample")).isEqualTo(DatabaseDriver.DERBY); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:h2:~/sample")).isEqualTo(DatabaseDriver.H2); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:hsqldb:hsql://localhost")).isEqualTo(DatabaseDriver.HSQLDB); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")).isEqualTo(DatabaseDriver.SQLITE); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")).isEqualTo(DatabaseDriver.MYSQL); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl")) .isEqualTo(DatabaseDriver.ORACLE); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:postgresql://127.0.0.1:5432/sample")) @@ -125,28 +99,19 @@ public class DatabaseDriverTests { assertThat(DatabaseDriver.fromJdbcUrl( "jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/sample")) .isEqualTo(DatabaseDriver.REDSHIFT); - assertThat( - DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) - .isEqualTo(DatabaseDriver.JTDS); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sap:localhost")) - .isEqualTo(DatabaseDriver.HANA); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")) - .isEqualTo(DatabaseDriver.SQLSERVER); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) + .isEqualTo(DatabaseDriver.JTDS); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sap:localhost")).isEqualTo(DatabaseDriver.HANA); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebirdsql://localhost/sample")) .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebird://localhost/sample")) - .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")) - .isEqualTo(DatabaseDriver.DB2); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")) - .isEqualTo(DatabaseDriver.DB2_AS400); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")) - .isEqualTo(DatabaseDriver.TERADATA); - assertThat( - DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample")) - .isEqualTo(DatabaseDriver.INFORMIX); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")) + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebird://localhost/sample")).isEqualTo(DatabaseDriver.FIREBIRD); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")).isEqualTo(DatabaseDriver.DB2); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")).isEqualTo(DatabaseDriver.DB2_AS400); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")).isEqualTo(DatabaseDriver.TERADATA); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample")) .isEqualTo(DatabaseDriver.INFORMIX); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")).isEqualTo(DatabaseDriver.INFORMIX); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java index 75c2290bd43..4ca78d32766 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,21 +42,18 @@ public class EmbeddedDatabaseConnectionTests { @Test public void hsqlCustomDatabaseName() { - assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql")) - .isEqualTo("jdbc:hsqldb:mem:myhsql"); + assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql")).isEqualTo("jdbc:hsqldb:mem:myhsql"); } @Test public void getUrlWithNullDatabaseName() { - assertThatIllegalArgumentException() - .isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(null)) + assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(null)) .withMessageContaining("DatabaseName must not be empty"); } @Test public void getUrlWithEmptyDatabaseName() { - assertThatIllegalArgumentException() - .isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(" ")) + assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(" ")) .withMessageContaining("DatabaseName must not be empty"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index 47f4a17880d..f88490ec281 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,7 @@ public abstract class AbstractDataSourcePoolMetadataTests) (connection) -> null); assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(0)); assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0)); @@ -60,8 +59,7 @@ public abstract class AbstractDataSourcePoolMetadataTests) (connection) -> { assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(1)); assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0.5F)); @@ -71,8 +69,7 @@ public abstract class AbstractDataSourcePoolMetadataTests) (connection) -> { jdbcTemplate.execute((ConnectionCallback) (connection1) -> { assertThat(getDataSourceMetadata().getActive()).isEqualTo(2); @@ -90,8 +87,8 @@ public abstract class AbstractDataSourcePoolMetadataTests initializeBuilder() { - return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver") - .url("jdbc:hsqldb:mem:test").username("sa"); + return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test") + .username("sa"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java index 8ebaa9183d9..7f47549a7f3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,7 @@ public class CommonsDbcp2DataSourcePoolMetadataTests @Test public void getPoolUsageWithNoCurrent() { - CommonsDbcp2DataSourcePoolMetadata dsm = new CommonsDbcp2DataSourcePoolMetadata( - createDataSource()) { + CommonsDbcp2DataSourcePoolMetadata dsm = new CommonsDbcp2DataSourcePoolMetadata(createDataSource()) { @Override public Integer getActive() { return null; @@ -56,8 +55,7 @@ public class CommonsDbcp2DataSourcePoolMetadataTests @Test public void getPoolUsageWithNoMax() { - CommonsDbcp2DataSourcePoolMetadata dsm = new CommonsDbcp2DataSourcePoolMetadata( - createDataSource()) { + CommonsDbcp2DataSourcePoolMetadata dsm = new CommonsDbcp2DataSourcePoolMetadata(createDataSource()) { @Override public Integer getMax() { return null; @@ -76,22 +74,18 @@ public class CommonsDbcp2DataSourcePoolMetadataTests public void getValidationQuery() { BasicDataSource dataSource = createDataSource(); dataSource.setValidationQuery("SELECT FROM FOO"); - assertThat( - new CommonsDbcp2DataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT FROM FOO"); + assertThat(new CommonsDbcp2DataSourcePoolMetadata(dataSource).getValidationQuery()) + .isEqualTo("SELECT FROM FOO"); } @Override public void getDefaultAutoCommit() { BasicDataSource dataSource = createDataSource(); dataSource.setDefaultAutoCommit(false); - assertThat( - new CommonsDbcp2DataSourcePoolMetadata(dataSource).getDefaultAutoCommit()) - .isFalse(); + assertThat(new CommonsDbcp2DataSourcePoolMetadata(dataSource).getDefaultAutoCommit()).isFalse(); } - private CommonsDbcp2DataSourcePoolMetadata createDataSourceMetadata(int minSize, - int maxSize) { + private CommonsDbcp2DataSourcePoolMetadata createDataSourceMetadata(int minSize, int maxSize) { BasicDataSource dataSource = createDataSource(); dataSource.setMinIdle(minSize); dataSource.setMaxTotal(maxSize); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java index 5d53d43fe73..7762f6314e5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,20 +59,16 @@ public class CompositeDataSourcePoolMetadataProviderTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - given(this.firstProvider.getDataSourcePoolMetadata(this.firstDataSource)) - .willReturn(this.first); - given(this.firstProvider.getDataSourcePoolMetadata(this.secondDataSource)) - .willReturn(this.second); + given(this.firstProvider.getDataSourcePoolMetadata(this.firstDataSource)).willReturn(this.first); + given(this.firstProvider.getDataSourcePoolMetadata(this.secondDataSource)).willReturn(this.second); } @Test public void createWithProviders() { CompositeDataSourcePoolMetadataProvider provider = new CompositeDataSourcePoolMetadataProvider( Arrays.asList(this.firstProvider, this.secondProvider)); - assertThat(provider.getDataSourcePoolMetadata(this.firstDataSource)) - .isSameAs(this.first); - assertThat(provider.getDataSourcePoolMetadata(this.secondDataSource)) - .isSameAs(this.second); + assertThat(provider.getDataSourcePoolMetadata(this.firstDataSource)).isSameAs(this.first); + assertThat(provider.getDataSourcePoolMetadata(this.secondDataSource)).isSameAs(this.second); assertThat(provider.getDataSourcePoolMetadata(this.unknownDataSource)).isNull(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java index 5a92dda8e71..e7ced968322 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class HikariDataSourcePoolMetadataTests @Before public void setup() { - this.dataSourceMetadata = new HikariDataSourcePoolMetadata( - createDataSource(0, 2)); + this.dataSourceMetadata = new HikariDataSourcePoolMetadata(createDataSource(0, 2)); } @Override @@ -46,21 +45,18 @@ public class HikariDataSourcePoolMetadataTests public void getValidationQuery() { HikariDataSource dataSource = createDataSource(0, 4); dataSource.setConnectionTestQuery("SELECT FROM FOO"); - assertThat(new HikariDataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT FROM FOO"); + assertThat(new HikariDataSourcePoolMetadata(dataSource).getValidationQuery()).isEqualTo("SELECT FROM FOO"); } @Override public void getDefaultAutoCommit() { HikariDataSource dataSource = createDataSource(0, 4); dataSource.setAutoCommit(false); - assertThat(new HikariDataSourcePoolMetadata(dataSource).getDefaultAutoCommit()) - .isFalse(); + assertThat(new HikariDataSourcePoolMetadata(dataSource).getDefaultAutoCommit()).isFalse(); } private HikariDataSource createDataSource(int minSize, int maxSize) { - HikariDataSource dataSource = initializeBuilder().type(HikariDataSource.class) - .build(); + HikariDataSource dataSource = initializeBuilder().type(HikariDataSource.class).build(); dataSource.setMinimumIdle(minSize); dataSource.setMaximumPoolSize(maxSize); return dataSource; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java index c421aca46dd..91c5fcf57dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class TomcatDataSourcePoolMetadataTests @Before public void setup() { - this.dataSourceMetadata = new TomcatDataSourcePoolMetadata( - createDataSource(0, 2)); + this.dataSourceMetadata = new TomcatDataSourcePoolMetadata(createDataSource(0, 2)); } @Override @@ -46,16 +45,14 @@ public class TomcatDataSourcePoolMetadataTests public void getValidationQuery() { DataSource dataSource = createDataSource(0, 4); dataSource.setValidationQuery("SELECT FROM FOO"); - assertThat(new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT FROM FOO"); + assertThat(new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery()).isEqualTo("SELECT FROM FOO"); } @Override public void getDefaultAutoCommit() { DataSource dataSource = createDataSource(0, 4); dataSource.setDefaultAutoCommit(false); - assertThat(new TomcatDataSourcePoolMetadata(dataSource).getDefaultAutoCommit()) - .isFalse(); + assertThat(new TomcatDataSourcePoolMetadata(dataSource).getDefaultAutoCommit()).isFalse(); } private DataSource createDataSource(int minSize, int maxSize) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index 412f90455ef..fa6d9d0d47d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,8 +89,7 @@ public abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test public void listOfMaps() { - List list = this.parser - .parseList("[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]"); + List list = this.parser.parseList("[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]"); assertThat(list).hasSize(2); assertThat(((Map) list.get(1))).hasSize(2); } @@ -98,46 +97,40 @@ public abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test public void mapOfLists() { - Map map = this.parser.parseMap( - "{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); + Map map = this.parser + .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); assertThat(map).hasSize(1); assertThat(((List) map.get("foo"))).hasSize(2); } @Test public void mapWithNullThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseMap(null)); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap(null)); } @Test public void listWithNullThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseList(null)); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList(null)); } @Test public void mapWithEmptyStringThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseMap("")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap("")); } @Test public void listWithEmptyStringThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseList("")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList("")); } @Test public void mapWithListThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseMap("[]")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap("[]")); } @Test public void listWithMapThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseList("{}")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList("{}")); } @Test @@ -156,14 +149,12 @@ public abstract class AbstractJsonParserTests { @Test public void mapWithLeadingWhitespaceListThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseMap("\n\t[]")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap("\n\t[]")); } @Test public void listWithLeadingWhitespaceMapThrowsARuntimeException() { - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> this.parser.parseList("\n\t{}")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList("\n\t{}")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java index 1d2485d5098..2ddaf56f1c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ public class AtomikosConnectionFactoryBeanTests { @Test public void beanMethods() throws Exception { - MockAtomikosConnectionFactoryBean bean = spy( - new MockAtomikosConnectionFactoryBean()); + MockAtomikosConnectionFactoryBean bean = spy(new MockAtomikosConnectionFactoryBean()); bean.setBeanName("bean"); bean.afterPropertiesSet(); assertThat(bean.getUniqueResourceName()).isEqualTo("bean"); @@ -44,8 +43,7 @@ public class AtomikosConnectionFactoryBeanTests { } @SuppressWarnings("serial") - private static class MockAtomikosConnectionFactoryBean - extends AtomikosConnectionFactoryBean { + private static class MockAtomikosConnectionFactoryBean extends AtomikosConnectionFactoryBean { @Override public synchronized void init() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java index bc91e83cee0..68b735f6513 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java @@ -59,8 +59,7 @@ public class AtomikosDependsOnBeanFactoryPostProcessorTests { assertThat(expected).as("No dependsOn expected for " + bean).isEmpty(); return; } - HashSet dependsOn = new HashSet<>( - Arrays.asList(definition.getDependsOn())); + HashSet dependsOn = new HashSet<>(Arrays.asList(definition.getDependsOn())); assertThat(dependsOn).isEqualTo(new HashSet<>(Arrays.asList(expected))); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java index 962848c6c15..2e29fe17c75 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class AtomikosPropertiesTests { this.properties.setLogBaseDir("logBaseDir"); this.properties.setCheckpointInterval(4); this.properties.setThreadedTwoPhaseCommit(true); - this.properties.getRecovery() - .setForgetOrphanedLogEntriesDelay(Duration.ofMillis(2000)); + this.properties.getRecovery().setForgetOrphanedLogEntriesDelay(Duration.ofMillis(2000)); this.properties.getRecovery().setDelay(Duration.ofMillis(3000)); this.properties.getRecovery().setMaxRetries(10); this.properties.getRecovery().setRetryInterval(Duration.ofMillis(4000)); @@ -84,19 +83,13 @@ public class AtomikosPropertiesTests { public void testDefaultProperties() { Properties defaultSettings = loadDefaultSettings(); Properties properties = this.properties.asProperties(); - assertThat(properties).contains(defaultOf(defaultSettings, - "com.atomikos.icatch.max_timeout", - "com.atomikos.icatch.default_jta_timeout", - "com.atomikos.icatch.max_actives", "com.atomikos.icatch.enable_logging", - "com.atomikos.icatch.serial_jta_transactions", - "com.atomikos.icatch.allow_subtransactions", - "com.atomikos.icatch.force_shutdown_on_vm_exit", - "com.atomikos.icatch.default_max_wait_time_on_shutdown", - "com.atomikos.icatch.log_base_name", - "com.atomikos.icatch.checkpoint_interval", - "com.atomikos.icatch.threaded_2pc", - "com.atomikos.icatch.forget_orphaned_log_entries_delay", - "com.atomikos.icatch.oltp_max_retries", + assertThat(properties).contains(defaultOf(defaultSettings, "com.atomikos.icatch.max_timeout", + "com.atomikos.icatch.default_jta_timeout", "com.atomikos.icatch.max_actives", + "com.atomikos.icatch.enable_logging", "com.atomikos.icatch.serial_jta_transactions", + "com.atomikos.icatch.allow_subtransactions", "com.atomikos.icatch.force_shutdown_on_vm_exit", + "com.atomikos.icatch.default_max_wait_time_on_shutdown", "com.atomikos.icatch.log_base_name", + "com.atomikos.icatch.checkpoint_interval", "com.atomikos.icatch.threaded_2pc", + "com.atomikos.icatch.forget_orphaned_log_entries_delay", "com.atomikos.icatch.oltp_max_retries", "com.atomikos.icatch.oltp_retry_interval")); assertThat(properties).contains(entry("com.atomikos.icatch.recovery_delay", defaultSettings.get("com.atomikos.icatch.default_jta_timeout"))); @@ -115,8 +108,7 @@ public class AtomikosPropertiesTests { private Properties loadDefaultSettings() { try { - return PropertiesLoaderUtils.loadProperties( - new ClassPathResource("transactions-defaults.properties")); + return PropertiesLoaderUtils.loadProperties(new ClassPathResource("transactions-defaults.properties")); } catch (Exception ex) { throw new IllegalStateException("Failed to get default from Atomikos", ex); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java index 0bc1d120dd0..db9f2b50228 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class AtomikosXAConnectionFactoryWrapperTests { AtomikosXAConnectionFactoryWrapper wrapper = new AtomikosXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); assertThat(wrapped).isInstanceOf(AtomikosConnectionFactoryBean.class); - assertThat(((AtomikosConnectionFactoryBean) wrapped).getXaConnectionFactory()) - .isSameAs(connectionFactory); + assertThat(((AtomikosConnectionFactoryBean) wrapped).getXaConnectionFactory()).isSameAs(connectionFactory); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java index fba710320f6..e1373022d7e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class AtomikosXADataSourceWrapperTests { AtomikosXADataSourceWrapper wrapper = new AtomikosXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); assertThat(wrapped).isInstanceOf(AtomikosDataSourceBean.class); - assertThat(((AtomikosDataSourceBean) wrapped).getXaDataSource()) - .isSameAs(dataSource); + assertThat(((AtomikosDataSourceBean) wrapped).getXaDataSource()).isSameAs(dataSource); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java index 91743b64fd5..11a3de361b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class BitronixXAConnectionFactoryWrapperTests { BitronixXAConnectionFactoryWrapper wrapper = new BitronixXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); assertThat(wrapped).isInstanceOf(PoolingConnectionFactoryBean.class); - assertThat(((PoolingConnectionFactoryBean) wrapped).getConnectionFactory()) - .isSameAs(connectionFactory); + assertThat(((PoolingConnectionFactoryBean) wrapped).getConnectionFactory()).isSameAs(connectionFactory); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java index a6388bb5b74..c0866b5e94d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class BitronixXADataSourceWrapperTests { BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); assertThat(wrapped).isInstanceOf(PoolingDataSourceBean.class); - assertThat(((PoolingDataSourceBean) wrapped).getDataSource()) - .isSameAs(dataSource); + assertThat(((PoolingDataSourceBean) wrapped).getDataSource()).isSameAs(dataSource); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java index 5bd8fbdfd84..021097b9fb6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java @@ -64,13 +64,11 @@ public class LiquibaseServiceLocatorApplicationListenerTests { } @Test - public void replaceServiceLocatorBacksOffIfNotPresent() - throws IllegalAccessException { + public void replaceServiceLocatorBacksOffIfNotPresent() throws IllegalAccessException { SpringApplication application = new SpringApplication(Conf.class); application.setWebApplicationType(WebApplicationType.NONE); DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); - resourceLoader.setClassLoader( - new ClassHidingClassLoader(CustomResolverServiceLocator.class)); + resourceLoader.setClassLoader(new ClassHidingClassLoader(CustomResolverServiceLocator.class)); application.setResourceLoader(resourceLoader); this.context = application.run(); Object resolver = getClassResolver(); @@ -94,8 +92,7 @@ public class LiquibaseServiceLocatorApplicationListenerTests { private final List> hiddenClasses; private ClassHidingClassLoader(Class... hiddenClasses) { - super(new URL[0], LiquibaseServiceLocatorApplicationListenerTests.class - .getClassLoader()); + super(new URL[0], LiquibaseServiceLocatorApplicationListenerTests.class.getClassLoader()); this.hiddenClasses = Arrays.asList(hiddenClasses); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java index b31d8902e8f..7166b6f88e9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,11 +33,9 @@ public class SpringPackageScanClassResolverTests { @Test public void testScan() { - SpringPackageScanClassResolver resolver = new SpringPackageScanClassResolver( - LogFactory.getLog(getClass())); + SpringPackageScanClassResolver resolver = new SpringPackageScanClassResolver(LogFactory.getLog(getClass())); resolver.addClassLoader(getClass().getClassLoader()); - Set> implementations = resolver.findImplementations(Logger.class, - "liquibase.logging.core"); + Set> implementations = resolver.findImplementations(Logger.class, "liquibase.logging.core"); assertThat(implementations).isNotEmpty(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java index 3065cf35811..00afb27c062 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +65,7 @@ public abstract class AbstractLoggingSystemTests { return getLogFile(file, path, true); } - protected final LogFile getLogFile(String file, String path, - boolean applyToSystemProperties) { + protected final LogFile getLogFile(String file, String path, boolean applyToSystemProperties) { LogFile logFile = new LogFile(file, path); if (applyToSystemProperties) { logFile.applyToSystemProperties(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java index 884fcd1686f..c895807cffb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -174,8 +174,7 @@ public class DeferredLogTests { @SuppressWarnings("unchecked") @Test public void switchTo() { - List lines = (List) ReflectionTestUtils.getField(this.deferredLog, - "lines"); + List lines = (List) ReflectionTestUtils.getField(this.deferredLog, "lines"); assertThat(lines).isEmpty(); this.deferredLog.error(this.message, this.throwable); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index ac8168da1a8..4fa12bdce5a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,16 +48,14 @@ public class LogFileTests { @Test public void loggingFile() { - PropertyResolver resolver = getPropertyResolver( - Collections.singletonMap("logging.file.name", "log.file")); + PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.file.name", "log.file")); testLoggingFile(resolver); } @Test @Deprecated public void loggingFileWithDeprecatedProperties() { - PropertyResolver resolver = getPropertyResolver( - Collections.singletonMap("logging.file", "log.file")); + PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.file", "log.file")); testLoggingFile(resolver); } @@ -66,23 +64,20 @@ public class LogFileTests { Properties properties = new Properties(); logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("log.file"); - assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo("log.file"); + assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)).isEqualTo("log.file"); assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)).isNull(); } @Test public void loggingPath() { - PropertyResolver resolver = getPropertyResolver( - Collections.singletonMap("logging.file.path", "logpath")); + PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.file.path", "logpath")); testLoggingPath(resolver); } @Test @Deprecated public void loggingPathWithDeprecatedProperties() { - PropertyResolver resolver = getPropertyResolver( - Collections.singletonMap("logging.path", "logpath")); + PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.path", "logpath")); testLoggingPath(resolver); } @@ -90,12 +85,10 @@ public class LogFileTests { LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); - assertThat(logFile.toString()) - .isEqualTo("logpath" + File.separatorChar + "spring.log"); + assertThat(logFile.toString()).isEqualTo("logpath" + File.separatorChar + "spring.log"); assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)) .isEqualTo("logpath" + File.separatorChar + "spring.log"); - assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)) - .isEqualTo("logpath"); + assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("logpath"); } @Test @@ -122,15 +115,12 @@ public class LogFileTests { Properties properties = new Properties(); logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("log.file"); - assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo("log.file"); - assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)) - .isEqualTo("logpath"); + assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)).isEqualTo("log.file"); + assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("logpath"); } private PropertyResolver getPropertyResolver(Map properties) { - PropertySource propertySource = new MapPropertySource("properties", - properties); + PropertySource propertySource = new MapPropertySource("properties", properties); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(propertySource); return new PropertySourcesPropertyResolver(propertySources); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java index ddedd55232b..af2b09cb2c1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class LoggerConfigurationComparatorTests { - private final LoggerConfigurationComparator comparator = new LoggerConfigurationComparator( - "ROOT"); + private final LoggerConfigurationComparator comparator = new LoggerConfigurationComparator("ROOT"); @Test public void rootLoggerFirst() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java index 01b90c65ce0..36a16d042f3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,40 +58,33 @@ public class LoggingSystemPropertiesTests { @Test public void consoleLogPatternIsSet() { - new LoggingSystemProperties(new MockEnvironment() - .withProperty("logging.pattern.console", "console pattern")).apply(null); - assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo("console pattern"); + new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.console", "console pattern")) + .apply(null); + assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).isEqualTo("console pattern"); } @Test public void fileLogPatternIsSet() { - new LoggingSystemProperties(new MockEnvironment() - .withProperty("logging.pattern.file", "file pattern")).apply(null); - assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)) - .isEqualTo("file pattern"); + new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.file", "file pattern")) + .apply(null); + assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).isEqualTo("file pattern"); } @Test public void consoleLogPatternCanReferencePid() { - new LoggingSystemProperties( - environment("logging.pattern.console", "${PID:unknown}")).apply(null); - assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .matches("[0-9]+"); + new LoggingSystemProperties(environment("logging.pattern.console", "${PID:unknown}")).apply(null); + assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).matches("[0-9]+"); } @Test public void fileLogPatternCanReferencePid() { - new LoggingSystemProperties(environment("logging.pattern.file", "${PID:unknown}")) - .apply(null); - assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)) - .matches("[0-9]+"); + new LoggingSystemProperties(environment("logging.pattern.file", "${PID:unknown}")).apply(null); + assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).matches("[0-9]+"); } private Environment environment(String key, Object value) { StandardEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addLast( - new MapPropertySource("test", Collections.singletonMap(key, value))); + environment.getPropertySources().addLast(new MapPropertySource("test", Collections.singletonMap(key, value))); return environment; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java index aeccce738a0..f6d81368cb7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java @@ -45,8 +45,8 @@ public class LoggingSystemTests { @Test public void getLoggerConfigurationIsUnsupported() { - assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( - () -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index 891bc0a7b08..0ec3bf21a0b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -50,11 +50,9 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; */ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { - private static final FileFilter SPRING_LOG_FILTER = (pathname) -> pathname.getName() - .startsWith("spring.log"); + private static final FileFilter SPRING_LOG_FILTER = (pathname) -> pathname.getName().startsWith("spring.log"); - private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem( - getClass().getClassLoader()); + private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem(getClass().getClassLoader()); @Rule public OutputCapture output = new OutputCapture(); @@ -120,8 +118,8 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { public void testSystemPropertyInitializesFormat() { System.setProperty(LoggingSystemProperties.PID_KEY, "1234"); this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "logging.properties"), null); + this.loggingSystem.initialize(null, + "classpath:" + ClassUtils.addResourcePathToPackagePath(getClass(), "logging.properties"), null); this.logger.info("Hello world"); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -131,8 +129,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonDefaultConfigLocation() { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:logging-nondefault.properties", - null); + this.loggingSystem.initialize(null, "classpath:logging-nondefault.properties", null); this.logger.info("Hello world"); String output = this.output.toString().trim(); assertThat(output).contains("INFO: Hello"); @@ -141,15 +138,14 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - assertThatIllegalStateException().isThrownBy(() -> this.loggingSystem - .initialize(null, "classpath:logging-nonexistent.properties", null)); + assertThatIllegalStateException().isThrownBy( + () -> this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null)); } @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, - LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo( + EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); } @Test @@ -159,8 +155,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.fine("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.fine("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -172,8 +167,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.fine("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", null); this.logger.fine("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -181,11 +175,9 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - List configurations = this.loggingSystem - .getLoggerConfigurations(); + List configurations = this.loggingSystem.getLoggerConfigurations(); assertThat(configurations).isNotEmpty(); - assertThat(configurations.get(0).getName()) - .isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); + assertThat(configurations.get(0).getName()).isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); } @Test @@ -193,10 +185,9 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java index 734d045c376..60deec87ad8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ public class TestFormatter extends Formatter { @Override public String format(LogRecord record) { - return String.format("foo: %s -- %s\n", record.getLoggerName(), - record.getMessage()); + return String.format("foo: %s -- %s\n", record.getLoggerName(), record.getMessage()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java index ba7a117cef3..f96aa2aab4b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,7 @@ public class ExtendedWhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder).startsWith(System.lineSeparator()) - .endsWith(System.lineSeparator()); + assertThat(builder).startsWith(System.lineSeparator()).endsWith(System.lineSeparator()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index 5897dbd9af4..43b95b77e50 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -114,8 +114,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonDefaultConfigLocation() { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:log4j2-nondefault.xml", - getLogFile(tmpDir() + "/tmp.log", null)); + this.loggingSystem.initialize(null, "classpath:log4j2-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); String output = this.output.toString().trim(); Configuration configuration = this.loggingSystem.getConfiguration(); @@ -129,14 +128,13 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - assertThatIllegalStateException().isThrownBy(() -> this.loggingSystem - .initialize(null, "classpath:log4j2-nonexistent.xml", null)); + assertThatIllegalStateException() + .isThrownBy(() -> this.loggingSystem.initialize(null, "classpath:log4j2-nonexistent.xml", null)); } @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.allOf(LogLevel.class)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo(EnumSet.allOf(LogLevel.class)); } @Test @@ -146,8 +144,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -159,8 +156,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", null); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -168,11 +164,9 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - List configurations = this.loggingSystem - .getLoggerConfigurations(); + List configurations = this.loggingSystem.getLoggerConfigurations(); assertThat(configurations).isNotEmpty(); - assertThat(configurations.get(0).getName()) - .isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); + assertThat(configurations.get(0).getName()).isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); } @Test @@ -180,10 +174,9 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test @@ -200,8 +193,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { public void loggingThatUsesJulIsCaptured() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(getClass().getName()); + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.severe("Hello world"); String output = this.output.toString().trim(); assertThat(output).contains("Hello world"); @@ -209,39 +201,33 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void configLocationsWithNoExtraDependencies() { - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.properties", "log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.properties", "log4j2.xml"); } @Test public void configLocationsWithJacksonDatabind() { this.loggingSystem.availableClasses(ObjectMapper.class.getName()); - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.json", "log4j2.jsn", "log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.json", "log4j2.jsn", "log4j2.xml"); } @Test public void configLocationsWithJacksonDataformatYaml() { - this.loggingSystem - .availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser"); - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.yaml", "log4j2.yml", "log4j2.xml"); + this.loggingSystem.availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.yaml", "log4j2.yml", "log4j2.xml"); } @Test public void configLocationsWithJacksonDatabindAndDataformatYaml() { - this.loggingSystem.availableClasses( - "com.fasterxml.jackson.dataformat.yaml.YAMLParser", + this.loggingSystem.availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser", ObjectMapper.class.getName()); - assertThat(this.loggingSystem.getStandardConfigLocations()).contains( - "log4j2.yaml", "log4j2.yml", "log4j2.json", "log4j2.jsn", "log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.yaml", "log4j2.yml", "log4j2.json", + "log4j2.jsn", "log4j2.xml"); } @Test public void springConfigLocations() { String[] locations = getSpringConfigLocations(this.loggingSystem); - assertThat(locations).containsExactly("log4j2-spring.properties", - "log4j2-spring.xml"); + assertThat(locations).containsExactly("log4j2-spring.properties", "log4j2-spring.xml"); } @Test @@ -269,12 +255,10 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); - Matcher expectedOutput = Matchers.allOf( - containsString("java.lang.RuntimeException: Expected"), + Matcher expectedOutput = Matchers.allOf(containsString("java.lang.RuntimeException: Expected"), not(containsString("Wrapped by:"))); this.output.expect(expectedOutput); - this.logger.warn("Expected exception", - new RuntimeException("Expected", new RuntimeException("Cause"))); + this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); String fileContents = contentOf(new File(tmpDir() + "/spring.log")); assertThat(fileContents).is(Matched.by(expectedOutput)); } @@ -310,8 +294,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } public Configuration getConfiguration() { - return ((org.apache.logging.log4j.core.LoggerContext) LogManager - .getContext(false)).getConfiguration(); + return ((org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)).getConfiguration(); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java index 3c9a39d0792..ccb496f83f3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,11 +34,9 @@ public class SpringBootConfigurationFactoryTests { @Test public void producesConfigurationWithShutdownHookDisabled() throws IOException { - ConfigurationSource source = new ConfigurationSource( - new ByteArrayInputStream(new byte[0])); - assertThat(new SpringBootConfigurationFactory() - .getConfiguration(new LoggerContext(""), source).isShutdownHookEnabled()) - .isFalse(); + ConfigurationSource source = new ConfigurationSource(new ByteArrayInputStream(new byte[0])); + assertThat(new SpringBootConfigurationFactory().getConfiguration(new LoggerContext(""), source) + .isShutdownHookEnabled()).isFalse(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java index b612d757d5d..d2a3ba961a2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ public class WhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder.toString()).startsWith(System.lineSeparator()) - .endsWith(System.lineSeparator()); + assertThat(builder.toString()).startsWith(System.lineSeparator()).endsWith(System.lineSeparator()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java index 561ce03c722..2e9d7a53acf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,8 @@ public class LogbackConfigurationTests { JoranConfigurator configurator = new JoranConfigurator(); LoggerContext context = new LoggerContext(); configurator.setContext(context); - configurator.doConfigure( - new File("src/test/resources/custom-console-log-pattern.xml")); - Appender appender = context.getLogger("ROOT") - .getAppender("CONSOLE"); + configurator.doConfigure(new File("src/test/resources/custom-console-log-pattern.xml")); + Appender appender = context.getLogger("ROOT").getAppender("CONSOLE"); assertThat(appender).isInstanceOf(ConsoleAppender.class); Encoder encoder = ((ConsoleAppender) appender).getEncoder(); assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class); @@ -58,8 +56,7 @@ public class LogbackConfigurationTests { JoranConfigurator configurator = new JoranConfigurator(); LoggerContext context = new LoggerContext(); configurator.setContext(context); - configurator - .doConfigure(new File("src/test/resources/custom-file-log-pattern.xml")); + configurator.doConfigure(new File("src/test/resources/custom-file-log-pattern.xml")); Appender appender = context.getLogger("ROOT").getAppender("FILE"); assertThat(appender).isInstanceOf(FileAppender.class); Encoder encoder = ((FileAppender) appender).getEncoder(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index d09aae93127..be304b287f4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -82,8 +82,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Rule public OutputCapture output = new OutputCapture(); - private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem( - getClass().getClassLoader()); + private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem(getClass().getClassLoader()); private Logger logger; @@ -92,8 +91,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Before public void setup() { this.loggingSystem.cleanUp(); - this.logger = ((LoggerContext) StaticLoggerBinder.getSingleton() - .getLoggerFactory()).getLogger(getClass()); + this.logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()).getLogger(getClass()); MockEnvironment environment = new MockEnvironment(); this.initializationContext = new LoggingInitializationContext(environment); } @@ -122,8 +120,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void withFile() { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); - this.loggingSystem.initialize(this.initializationContext, null, - getLogFile(null, tmpDir())); + this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); String output = this.output.toString().trim(); File file = new File(tmpDir() + "/spring.log"); @@ -131,8 +128,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { assertThat(getLineWithText(output, "Hello world")).contains("INFO"); assertThat(file.exists()).isTrue(); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); - assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize") - .toString()).isEqualTo("10 MB"); + assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize").toString()).isEqualTo("10 MB"); assertThat(getRollingPolicy().getMaxHistory()).isEqualTo(7); } @@ -147,8 +143,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testNonDefaultConfigLocation() { int existingOutputLength = this.output.toString().length(); this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(this.initializationContext, - "classpath:logback-nondefault.xml", + this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -165,8 +160,8 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); String output = this.output.toString().trim(); - assertThat(output).contains("Ignoring 'logback.configurationFile' " - + "system property. Please use 'logging.config' instead."); + assertThat(output).contains( + "Ignoring 'logback.configurationFile' " + "system property. Please use 'logging.config' instead."); } finally { System.clearProperty("logback.configurationFile"); @@ -176,15 +171,14 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - assertThatIllegalStateException().isThrownBy(() -> this.loggingSystem.initialize( - this.initializationContext, "classpath:logback-nonexistent.xml", null)); + assertThatIllegalStateException().isThrownBy(() -> this.loggingSystem.initialize(this.initializationContext, + "classpath:logback-nonexistent.xml", null)); } @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, - LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo( + EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); } @Test @@ -194,8 +188,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -207,8 +200,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", null); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -216,11 +208,9 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - List configurations = this.loggingSystem - .getLoggerConfigurations(); + List configurations = this.loggingSystem.getLoggerConfigurations(); assertThat(configurations).isNotEmpty(); - assertThat(configurations.get(0).getName()) - .isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); + assertThat(configurations.get(0).getName()).isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); } @Test @@ -228,23 +218,20 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test public void getLoggingConfigurationForALL() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory() - .getLogger(getClass().getName()); + Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger(getClass().getName()); logger.setLevel(Level.ALL); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.TRACE, LogLevel.TRACE)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); } @Test @@ -252,8 +239,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.TRACE); - Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory() - .getLogger(getClass().getName()); + Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger(getClass().getName()); assertThat(logger.getLevel()).isEqualTo(Level.TRACE); } @@ -261,8 +247,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void loggingThatUsesJulIsCaptured() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(getClass().getName()); + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.info("Hello world"); String output = this.output.toString().trim(); assertThat(output).contains("Hello world"); @@ -273,8 +258,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(getClass().getName()); + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.fine("Hello debug world"); String output = this.output.toString().trim(); assertThat(output).contains("Hello debug world"); @@ -292,15 +276,15 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void standardConfigLocations() { String[] locations = this.loggingSystem.getStandardConfigLocations(); - assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml", - "logback.groovy", "logback.xml"); + assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml", "logback.groovy", + "logback.xml"); } @Test public void springConfigLocations() { String[] locations = getSpringConfigLocations(this.loggingSystem); - assertThat(locations).containsExactly("logback-test-spring.groovy", - "logback-test-spring.xml", "logback-spring.groovy", "logback-spring.xml"); + assertThat(locations).containsExactly("logback-test-spring.groovy", "logback-test-spring.xml", + "logback-spring.groovy", "logback-spring.xml"); } private boolean bridgeHandlerInstalled() { @@ -318,8 +302,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testConsolePatternProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.console", "%logger %msg"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -330,8 +313,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testLevelPatternProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.level", "X%clr(%p)X"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -342,8 +324,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testFilePatternProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.file", "%logger %msg"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); @@ -357,8 +338,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testCleanHistoryOnStartProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.clean-history-on-start", "true"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); @@ -371,12 +351,10 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testCleanHistoryOnStartPropertyWithXmlConfiguration() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.clean-history-on-start", "true"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); - this.loggingSystem.initialize(loggingInitializationContext, - "classpath:logback-include-base.xml", logFile); + this.loggingSystem.initialize(loggingInitializationContext, "classpath:logback-include-base.xml", logFile); this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); assertThat(getRollingPolicy().isCleanHistoryOnStart()).isTrue(); @@ -400,39 +378,34 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { private void testMaxFileSizeProperty(String sizeValue, String expectedFileSize) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-size", sizeValue); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); - assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize") - .toString()).isEqualTo(expectedFileSize); + assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize").toString()) + .isEqualTo(expectedFileSize); } @Test public void testMaxFileSizePropertyWithXmlConfiguration() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-size", "100MB"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); - this.loggingSystem.initialize(loggingInitializationContext, - "classpath:logback-include-base.xml", logFile); + this.loggingSystem.initialize(loggingInitializationContext, "classpath:logback-include-base.xml", logFile); this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); - assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize") - .toString()).isEqualTo("100 MB"); + assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize").toString()).isEqualTo("100 MB"); } @Test public void testMaxHistoryProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-history", "30"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); @@ -445,12 +418,10 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testMaxHistoryPropertyWithXmlConfiguration() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-history", "30"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); - this.loggingSystem.initialize(loggingInitializationContext, - "classpath:logback-include-base.xml", logFile); + this.loggingSystem.initialize(loggingInitializationContext, "classpath:logback-include-base.xml", logFile); this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); assertThat(getRollingPolicy().getMaxHistory()).isEqualTo(30); @@ -474,15 +445,14 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { private void testTotalSizeCapProperty(String sizeValue, String expectedFileSize) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.total-size-cap", sizeValue); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); - assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap") - .toString()).isEqualTo(expectedFileSize); + assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap").toString()) + .isEqualTo(expectedFileSize); } @Test @@ -490,23 +460,19 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { String expectedSize = "101 MB"; MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.total-size-cap", expectedSize); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); - this.loggingSystem.initialize(loggingInitializationContext, - "classpath:logback-include-base.xml", logFile); + this.loggingSystem.initialize(loggingInitializationContext, "classpath:logback-include-base.xml", logFile); this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); - assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap") - .toString()).isEqualTo(expectedSize); + assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap").toString()).isEqualTo(expectedSize); } @Test public void exceptionsIncludeClassPackaging() { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(this.initializationContext, null, - getLogFile(null, tmpDir())); + this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); Matcher expectedOutput = containsString("[junit-"); this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected")); @@ -520,14 +486,11 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { try { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); - this.loggingSystem.initialize(this.initializationContext, null, - getLogFile(null, tmpDir())); - Matcher expectedOutput = Matchers.allOf( - containsString("java.lang.RuntimeException: Expected"), + this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); + Matcher expectedOutput = Matchers.allOf(containsString("java.lang.RuntimeException: Expected"), not(containsString("Wrapped by:"))); this.output.expect(expectedOutput); - this.logger.warn("Expected exception", - new RuntimeException("Expected", new RuntimeException("Cause"))); + this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); String fileContents = contentOf(new File(tmpDir() + "/spring.log")); assertThat(fileContents).is(Matched.by(expectedOutput)); } @@ -542,16 +505,13 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); LogFile logFile = getLogFile(tmpDir() + "/example.log", null, false); - this.loggingSystem.initialize(this.initializationContext, - "classpath:logback-nondefault.xml", logFile); - assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .endsWith("example.log"); + this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nondefault.xml", logFile); + assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)).endsWith("example.log"); } @Test public void initializationIsOnlyPerformedOnceUntilCleanedUp() { - LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton() - .getLoggerFactory(); + LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); LoggerContextListener listener = mock(LoggerContextListener.class); loggerContext.addListener(listener); this.loggingSystem.beforeInitialize(); @@ -569,10 +529,8 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testDateformatPatternProperty() { MockEnvironment environment = new MockEnvironment(); - environment.setProperty("logging.pattern.dateformat", - "yyyy-MM-dd'T'hh:mm:ss.SSSZ"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + environment.setProperty("logging.pattern.dateformat", "yyyy-MM-dd'T'hh:mm:ss.SSSZ"); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java index 883e64cbdf0..bf22347db6e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,7 @@ public class SpringBootJoranConfiguratorTests { @After public void reset() { this.context.stop(); - new BasicConfigurator() - .configure((LoggerContext) LoggerFactory.getILoggerFactory()); + new BasicConfigurator().configure((LoggerContext) LoggerFactory.getILoggerFactory()); } @Test @@ -154,16 +153,14 @@ public class SpringBootJoranConfiguratorTests { @Test public void springProperty() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "my.example-property=test"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "my.example-property=test"); initialize("property.xml"); assertThat(this.context.getProperty("MINE")).isEqualTo("test"); } @Test public void relaxedSpringProperty() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "my.EXAMPLE_PROPERTY=test"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "my.EXAMPLE_PROPERTY=test"); ConfigurationPropertySources.attach(this.environment); initialize("property.xml"); assertThat(this.context.getProperty("MINE")).isEqualTo("test"); @@ -193,8 +190,7 @@ public class SpringBootJoranConfiguratorTests { assertThat(this.context.getProperty("MINE")).isEqualTo("bar"); } - private void doTestNestedProfile(boolean expected, String... profiles) - throws JoranException { + private void doTestNestedProfile(boolean expected, String... profiles) throws JoranException { this.environment.setActiveProfiles(profiles); initialize("nested.xml"); this.logger.trace("Hello"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java index ad1a639c223..b5551bf7649 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,7 @@ public class SpringProfileActionTests { private final Context context = new ContextBase(); - private final InterpretationContext interpretationContext = new InterpretationContext( - this.context, null); + private final InterpretationContext interpretationContext = new InterpretationContext(this.context, null); private final Attributes attributes = mock(Attributes.class); @@ -61,8 +60,7 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithProfileFromNameAttribute() - throws ActionException { + public void environmentIsQueriedWithProfileFromNameAttribute() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("dev"); this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); @@ -76,8 +74,7 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithMultipleProfilesFromCommaSeparatedNameAttribute() - throws ActionException { + public void environmentIsQueriedWithMultipleProfilesFromCommaSeparatedNameAttribute() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("dev,qa"); this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); @@ -91,8 +88,7 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithResolvedValueWhenNameAttributeUsesAPlaceholder() - throws ActionException { + public void environmentIsQueriedWithResolvedValueWhenNameAttributeUsesAPlaceholder() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("${profile}"); this.context.putProperty("profile", "dev"); this.action.begin(this.interpretationContext, null, this.attributes); @@ -109,8 +105,7 @@ public class SpringProfileActionTests { @Test public void environmentIsQueriedWithResolvedValuesFromCommaSeparatedNameNameAttributeWithPlaceholders() throws ActionException { - given(this.attributes.getValue(Action.NAME_ATTRIBUTE)) - .willReturn("${profile1},${profile2}"); + given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("${profile1},${profile2}"); this.context.putProperty("profile1", "dev"); this.context.putProperty("profile2", "qa"); this.action.begin(this.interpretationContext, null, this.attributes); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java index 37db3990e92..a5e7bade4db 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,7 @@ public class OriginTests { assertThat(Origin.from(exception)).isEqualTo(origin); } - private static class TestException extends RuntimeException - implements OriginProvider { + private static class TestException extends RuntimeException implements OriginProvider { private final Origin origin; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java index 8e34685cf2b..2013259bef5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,7 @@ public class OriginTrackedValueTests { OriginTrackedValue tracked2 = OriginTrackedValue.of(value1, mock(Origin.class)); OriginTrackedValue tracked3 = OriginTrackedValue.of(new Object()); assertThat(tracked1.hashCode()).isEqualTo(tracked2.hashCode()); - assertThat(tracked1).isEqualTo(tracked1).isEqualTo(tracked2) - .isNotEqualTo(tracked3); + assertThat(tracked1).isEqualTo(tracked1).isEqualTo(tracked2).isNotEqualTo(tracked3); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java index 668f31aacac..60a94a5c469 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,24 +38,20 @@ public class PropertySourceOriginTests { @Test public void createWhenPropertySourceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new PropertySourceOrigin(null, "name")) + assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(null, "name")) .withMessageContaining("PropertySource must not be null"); } @Test public void createWhenPropertyNameIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new PropertySourceOrigin(mock(PropertySource.class), null)) + .isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), null)) .withMessageContaining("PropertyName must not be empty"); } @Test public void createWhenPropertyNameIsEmptyShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> new PropertySourceOrigin(mock(PropertySource.class), "")) + assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), "")) .withMessageContaining("PropertyName must not be empty"); } @@ -95,8 +91,7 @@ public class PropertySourceOriginTests { public void getWhenPropertySourceSupportsOriginLookupButNoOriginShouldWrap() { PropertySource propertySource = mock(PropertySource.class, withSettings().extraInterfaces(OriginLookup.class)); - assertThat(PropertySourceOrigin.get(propertySource, "foo")) - .isInstanceOf(PropertySourceOrigin.class); + assertThat(PropertySourceOrigin.get(propertySource, "foo")).isInstanceOf(PropertySourceOrigin.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java index 708262dd942..c6b162e150f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,14 +30,12 @@ public class SystemEnvironmentOriginTests { @Test public void createWhenPropertyIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SystemEnvironmentOrigin(null)); + assertThatIllegalArgumentException().isThrownBy(() -> new SystemEnvironmentOrigin(null)); } @Test public void createWhenPropertyNameIsEmptyShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SystemEnvironmentOrigin("")); + assertThatIllegalArgumentException().isThrownBy(() -> new SystemEnvironmentOrigin("")); } @Test @@ -49,8 +47,7 @@ public class SystemEnvironmentOriginTests { @Test public void toStringShouldReturnStringWithDetails() { SystemEnvironmentOrigin origin = new SystemEnvironmentOrigin("FOO_BAR"); - assertThat(origin.toString()) - .isEqualTo("System Environment Property \"FOO_BAR\""); + assertThat(origin.toString()).isEqualTo("System Environment Property \"FOO_BAR\""); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java index 85b8785aeb9..199442aa09c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,14 +112,10 @@ public class TextResourceOriginTests { @Test public void equalsAndHashCodeShouldResourceAndLocation() { - TextResourceOrigin origin1 = new TextResourceOrigin( - new ClassPathResource("foo.txt"), new Location(1, 2)); - TextResourceOrigin origin2 = new TextResourceOrigin( - new ClassPathResource("foo.txt"), new Location(1, 2)); - TextResourceOrigin origin3 = new TextResourceOrigin( - new ClassPathResource("foo.txt"), new Location(2, 2)); - TextResourceOrigin origin4 = new TextResourceOrigin( - new ClassPathResource("foo2.txt"), new Location(1, 2)); + TextResourceOrigin origin1 = new TextResourceOrigin(new ClassPathResource("foo.txt"), new Location(1, 2)); + TextResourceOrigin origin2 = new TextResourceOrigin(new ClassPathResource("foo.txt"), new Location(1, 2)); + TextResourceOrigin origin3 = new TextResourceOrigin(new ClassPathResource("foo.txt"), new Location(2, 2)); + TextResourceOrigin origin4 = new TextResourceOrigin(new ClassPathResource("foo2.txt"), new Location(1, 2)); assertThat(origin1.hashCode()).isEqualTo(origin1.hashCode()); assertThat(origin1.hashCode()).isEqualTo(origin2.hashCode()); assertThat(origin1.hashCode()).isNotEqualTo(origin3.hashCode()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java index 3721eb323a3..7b4c78a0828 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,24 +50,20 @@ public class SpringPhysicalNamingStrategyTests { } private StandardServiceRegistry createServiceRegistry() { - return new StandardServiceRegistryBuilder() - .applySetting(AvailableSettings.DIALECT, H2Dialect.class).build(); + return new StandardServiceRegistryBuilder().applySetting(AvailableSettings.DIALECT, H2Dialect.class).build(); } @Test public void tableNameShouldBeLowercaseUnderscore() { - PersistentClass binding = this.metadata - .getEntityBinding(TelephoneNumber.class.getName()); + PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); assertThat(binding.getTable().getQuotedName()).isEqualTo("telephone_number"); } @Test public void tableNameShouldNotBeLowerCaseIfCaseSensitive() { this.metadata = this.metadataSources.getMetadataBuilder() - .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()) - .build(); - PersistentClass binding = this.metadata - .getEntityBinding(TelephoneNumber.class.getName()); + .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()).build(); + PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); assertThat(binding.getTable().getQuotedName()).isEqualTo("Telephone_Number"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java index 98cab4ce5e8..6faaa0539c5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java @@ -96,8 +96,7 @@ public class NettyRSocketServerFactoryTests { this.rSocketServer.start(); this.requester = createRSocketTcpClient(); String payload = "test payload"; - String response = this.requester.route("test").data(payload) - .retrieveMono(String.class).block(TIMEOUT); + String response = this.requester.route("test").data(payload).retrieveMono(String.class).block(TIMEOUT); assertThat(response).isEqualTo(payload); assertThat(this.rSocketServer.address().getPort()).isEqualTo(specificPort); @@ -111,8 +110,7 @@ public class NettyRSocketServerFactoryTests { this.rSocketServer.start(); this.requester = createRSocketWebSocketClient(); String payload = "test payload"; - String response = this.requester.route("test").data(payload) - .retrieveMono(String.class).block(TIMEOUT); + String response = this.requester.route("test").data(payload).retrieveMono(String.class).block(TIMEOUT); assertThat(response).isEqualTo(payload); } @@ -129,40 +127,33 @@ public class NettyRSocketServerFactoryTests { this.rSocketServer = factory.create(new EchoRequestResponseAcceptor()); InOrder ordered = inOrder((Object[]) customizers); for (ServerRSocketFactoryCustomizer customizer : customizers) { - ordered.verify(customizer) - .apply(any(RSocketFactory.ServerRSocketFactory.class)); + ordered.verify(customizer).apply(any(RSocketFactory.ServerRSocketFactory.class)); } } private RSocketRequester createRSocketTcpClient() { Assertions.assertThat(this.rSocketServer).isNotNull(); InetSocketAddress address = this.rSocketServer.address(); - return createRSocketRequesterBuilder() - .connectTcp(address.getHostString(), address.getPort()).block(); + return createRSocketRequesterBuilder().connectTcp(address.getHostString(), address.getPort()).block(); } private RSocketRequester createRSocketWebSocketClient() { Assertions.assertThat(this.rSocketServer).isNotNull(); InetSocketAddress address = this.rSocketServer.address(); - return createRSocketRequesterBuilder() - .connect(WebsocketClientTransport.create(address)).block(); + return createRSocketRequesterBuilder().connect(WebsocketClientTransport.create(address)).block(); } private RSocketRequester.Builder createRSocketRequesterBuilder() { - RSocketStrategies strategies = RSocketStrategies.builder() - .decoder(StringDecoder.allMimeTypes()) + RSocketStrategies strategies = RSocketStrategies.builder().decoder(StringDecoder.allMimeTypes()) .encoder(CharSequenceEncoder.allMimeTypes()) - .dataBufferFactory( - new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)) - .build(); + .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)).build(); return RSocketRequester.builder().rsocketStrategies(strategies); } static class EchoRequestResponseAcceptor implements SocketAcceptor { @Override - public Mono accept(ConnectionSetupPayload setupPayload, - RSocket rSocket) { + public Mono accept(ConnectionSetupPayload setupPayload, RSocket rSocket) { return Mono.just(new AbstractRSocket() { @Override public Mono requestResponse(Payload payload) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java index 93d1e8759f0..0a84182202a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,60 +49,49 @@ public class ApplicationContextServerWebExchangeMatcherTests { @Test public void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new TestApplicationContextServerWebExchangeMatcher<>(null)) + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(null)) .withMessageContaining("Context class must not be null"); } @Test public void matchesWhenContextClassIsApplicationContextShouldProvideContext() { ServerWebExchange exchange = createExchange(); - StaticApplicationContext context = (StaticApplicationContext) exchange - .getApplicationContext(); - assertThat(new TestApplicationContextServerWebExchangeMatcher<>( - ApplicationContext.class).callMatchesAndReturnProvidedContext(exchange) - .get()).isEqualTo(context); + StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); + assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ApplicationContext.class) + .callMatchesAndReturnProvidedContext(exchange).get()).isEqualTo(context); } @Test public void matchesWhenContextClassIsExistingBeanShouldProvideBean() { ServerWebExchange exchange = createExchange(); - StaticApplicationContext context = (StaticApplicationContext) exchange - .getApplicationContext(); + StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); - assertThat( - new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange).get()) - .isEqualTo(context.getBean(ExistingBean.class)); + assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(exchange).get()).isEqualTo(context.getBean(ExistingBean.class)); } @Test public void matchesWhenContextClassIsMissingBeanShouldProvideException() { ServerWebExchange exchange = createExchange(); - Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>( - ExistingBean.class).callMatchesAndReturnProvidedContext(exchange); - assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(supplier::get); + Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(exchange); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(supplier::get); } @Test public void matchesWhenContextIsNull() { - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/path").build()); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").build()); assertThatIllegalStateException() - .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>( - ExistingBean.class).callMatchesAndReturnProvidedContext(exchange)) - .withMessageContaining( - "No ApplicationContext found on ServerWebExchange."); + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(exchange)) + .withMessageContaining("No ApplicationContext found on ServerWebExchange."); } private ServerWebExchange createExchange() { StaticApplicationContext context = new StaticApplicationContext(); - TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter( - mock(WebHandler.class)); + TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(mock(WebHandler.class)); adapter.setApplicationContext(context); - return adapter.createExchange(MockServerHttpRequest.get("/path").build(), - new MockServerHttpResponse()); + return adapter.createExchange(MockServerHttpRequest.get("/path").build(), new MockServerHttpResponse()); } static class TestHttpWebHandlerAdapter extends HttpWebHandlerAdapter { @@ -112,8 +101,7 @@ public class ApplicationContextServerWebExchangeMatcherTests { } @Override - protected ServerWebExchange createExchange(ServerHttpRequest request, - ServerHttpResponse response) { + protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { return super.createExchange(request, response); } @@ -152,8 +140,7 @@ public class ApplicationContextServerWebExchangeMatcherTests { } @Override - protected Mono matches(ServerWebExchange exchange, - Supplier context) { + protected Mono matches(ServerWebExchange exchange, Supplier context) { this.providedContext = context; return MatchResult.match(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java index 50e34c9522b..bbb63f06665 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class ApplicationContextRequestMatcherTests { @Test public void createWhenContextClassIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new TestApplicationContextRequestMatcher<>(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new TestApplicationContextRequestMatcher<>(null)) .withMessageContaining("Context class must not be null"); } @@ -59,25 +58,22 @@ public class ApplicationContextRequestMatcherTests { StaticWebApplicationContext context = createWebApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); assertThat(new TestApplicationContextRequestMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(context).get()) - .isEqualTo(context.getBean(ExistingBean.class)); + .callMatchesAndReturnProvidedContext(context).get()).isEqualTo(context.getBean(ExistingBean.class)); } @Test public void matchesWhenContextClassIsBeanThatDoesNotExistShouldSupplyException() { StaticWebApplicationContext context = createWebApplicationContext(); - Supplier supplier = new TestApplicationContextRequestMatcher<>( - ExistingBean.class).callMatchesAndReturnProvidedContext(context); - assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(supplier::get); + Supplier supplier = new TestApplicationContextRequestMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(context); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(supplier::get); } private StaticWebApplicationContext createWebApplicationContext() { StaticWebApplicationContext context = new StaticWebApplicationContext(); MockServletContext servletContext = new MockServletContext(); context.setServletContext(servletContext); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); return context; } @@ -99,8 +95,7 @@ public class ApplicationContextRequestMatcherTests { } - static class TestApplicationContextRequestMatcher - extends ApplicationContextRequestMatcher { + static class TestApplicationContextRequestMatcher extends ApplicationContextRequestMatcher { private Supplier providedContext; @@ -108,14 +103,11 @@ public class ApplicationContextRequestMatcherTests { super(context); } - public Supplier callMatchesAndReturnProvidedContext( - WebApplicationContext context) { - return callMatchesAndReturnProvidedContext( - new MockHttpServletRequest(context.getServletContext())); + public Supplier callMatchesAndReturnProvidedContext(WebApplicationContext context) { + return callMatchesAndReturnProvidedContext(new MockHttpServletRequest(context.getServletContext())); } - public Supplier callMatchesAndReturnProvidedContext( - HttpServletRequest request) { + public Supplier callMatchesAndReturnProvidedContext(HttpServletRequest request) { matches(request); return getProvidedContext(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java index c8f3000495e..1d2c9b6ce64 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java @@ -49,8 +49,7 @@ public class ApplicationPidTests { @Test public void throwIllegalStateWritingMissingPid() { ApplicationPid pid = new ApplicationPid(null); - assertThatIllegalStateException() - .isThrownBy(() -> pid.write(this.temporaryFolder.newFile())) + assertThatIllegalStateException().isThrownBy(() -> pid.write(this.temporaryFolder.newFile())) .withMessageContaining("No PID available"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java index be0fa7c37f0..daaed9117c7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java @@ -45,9 +45,8 @@ public class TaskExecutorBuilderTests { @Test public void poolSettingsShouldApply() { - ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10).corePoolSize(4) - .maxPoolSize(8).allowCoreThreadTimeOut(true) - .keepAlive(Duration.ofMinutes(1)).build(); + ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8) + .allowCoreThreadTimeOut(true).keepAlive(Duration.ofMinutes(1)).build(); assertThat(executor).hasFieldOrPropertyWithValue("queueCapacity", 10); assertThat(executor.getCorePoolSize()).isEqualTo(4); assertThat(executor.getMaxPoolSize()).isEqualTo(8); @@ -58,14 +57,12 @@ public class TaskExecutorBuilderTests { @Test public void awaitTerminationShouldApply() { ThreadPoolTaskExecutor executor = this.builder.awaitTermination(true).build(); - assertThat(executor) - .hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(executor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); } @Test public void awaitTerminationPeriodShouldApply() { - ThreadPoolTaskExecutor executor = this.builder - .awaitTerminationPeriod(Duration.ofMinutes(1)).build(); + ThreadPoolTaskExecutor executor = this.builder.awaitTerminationPeriod(Duration.ofMinutes(1)).build(); assertThat(executor).hasFieldOrPropertyWithValue("awaitTerminationSeconds", 60); } @@ -78,24 +75,20 @@ public class TaskExecutorBuilderTests { @Test public void taskDecoratorShouldApply() { TaskDecorator taskDecorator = mock(TaskDecorator.class); - ThreadPoolTaskExecutor executor = this.builder.taskDecorator(taskDecorator) - .build(); - assertThat(ReflectionTestUtils.getField(executor, "taskDecorator")) - .isSameAs(taskDecorator); + ThreadPoolTaskExecutor executor = this.builder.taskDecorator(taskDecorator).build(); + assertThat(ReflectionTestUtils.getField(executor, "taskDecorator")).isSameAs(taskDecorator); } @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.builder.customizers((TaskExecutorCustomizer[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((TaskExecutorCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.customizers((Set) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.customizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @@ -110,11 +103,9 @@ public class TaskExecutorBuilderTests { public void customizersShouldBeAppliedLast() { TaskDecorator taskDecorator = mock(TaskDecorator.class); ThreadPoolTaskExecutor executor = spy(new ThreadPoolTaskExecutor()); - this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8) - .allowCoreThreadTimeOut(true).keepAlive(Duration.ofMinutes(1)) - .awaitTermination(true).awaitTerminationPeriod(Duration.ofSeconds(30)) - .threadNamePrefix("test-").taskDecorator(taskDecorator) - .additionalCustomizers((taskExecutor) -> { + this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8).allowCoreThreadTimeOut(true) + .keepAlive(Duration.ofMinutes(1)).awaitTermination(true).awaitTerminationPeriod(Duration.ofSeconds(30)) + .threadNamePrefix("test-").taskDecorator(taskDecorator).additionalCustomizers((taskExecutor) -> { verify(taskExecutor).setQueueCapacity(10); verify(taskExecutor).setCorePoolSize(4); verify(taskExecutor).setMaxPoolSize(8); @@ -140,16 +131,15 @@ public class TaskExecutorBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalCustomizers((Set) null)) + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @@ -157,8 +147,8 @@ public class TaskExecutorBuilderTests { public void additionalCustomizersShouldAddToExisting() { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); - ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1) - .additionalCustomizers(customizer2).build(); + ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1).additionalCustomizers(customizer2) + .build(); verify(customizer1).customize(executor); verify(customizer2).customize(executor); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java index 4e069004268..940ae3d0549 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java @@ -49,36 +49,32 @@ public class TaskSchedulerBuilderTests { @Test public void awaitTerminationShouldApply() { ThreadPoolTaskScheduler executor = this.builder.awaitTermination(true).build(); - assertThat(executor) - .hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(executor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); } @Test public void awaitTerminationPeriodShouldApply() { - ThreadPoolTaskScheduler executor = this.builder - .awaitTerminationPeriod(Duration.ofMinutes(1)).build(); + ThreadPoolTaskScheduler executor = this.builder.awaitTerminationPeriod(Duration.ofMinutes(1)).build(); assertThat(executor).hasFieldOrPropertyWithValue("awaitTerminationSeconds", 60); } @Test public void threadNamePrefixShouldApply() { - ThreadPoolTaskScheduler scheduler = this.builder.threadNamePrefix("test-") - .build(); + ThreadPoolTaskScheduler scheduler = this.builder.threadNamePrefix("test-").build(); assertThat(scheduler.getThreadNamePrefix()).isEqualTo("test-"); } @Test public void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) + .isThrownBy(() -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.customizers((Set) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.customizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @@ -92,11 +88,10 @@ public class TaskSchedulerBuilderTests { @Test public void customizersShouldBeAppliedLast() { ThreadPoolTaskScheduler scheduler = spy(new ThreadPoolTaskScheduler()); - this.builder.poolSize(4).threadNamePrefix("test-") - .additionalCustomizers((taskScheduler) -> { - verify(taskScheduler).setPoolSize(4); - verify(taskScheduler).setThreadNamePrefix("test-"); - }); + this.builder.poolSize(4).threadNamePrefix("test-").additionalCustomizers((taskScheduler) -> { + verify(taskScheduler).setPoolSize(4); + verify(taskScheduler).setThreadNamePrefix("test-"); + }); this.builder.configure(scheduler); } @@ -113,16 +108,14 @@ public class TaskSchedulerBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalCustomizers((TaskSchedulerCustomizer[]) null)) + .isThrownBy(() -> this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalCustomizers((Set) null)) + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @@ -130,8 +123,8 @@ public class TaskSchedulerBuilderTests { public void additionalCustomizersShouldAddToExisting() { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); - ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1) - .additionalCustomizers(customizer2).build(); + ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1).additionalCustomizers(customizer2) + .build(); verify(customizer1).customize(scheduler); verify(customizer2).customize(scheduler); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java index 937c79ad1a7..0c874cb0719 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,15 +46,13 @@ public class LambdaSafeTests { @Test public void callbackWhenCallbackTypeIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> LambdaSafe.callback(null, new Object(), null)) + assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(null, new Object(), null)) .withMessageContaining("CallbackType must not be null"); } @Test public void callbackWhenCallbackInstanceIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> LambdaSafe.callback(Object.class, null, null)) + assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(Object.class, null, null)) .withMessageContaining("CallbackInstance must not be null"); } @@ -62,8 +60,7 @@ public class LambdaSafeTests { public void callbackInvokeWhenNoGenericShouldInvokeCallback() { NonGenericCallback callbackInstance = mock(NonGenericCallback.class); String argument = "foo"; - LambdaSafe.callback(NonGenericCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(argument)); + LambdaSafe.callback(NonGenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); } @@ -72,8 +69,7 @@ public class LambdaSafeTests { public void callbackInvokeWhenHasGenericShouldInvokeCallback() { StringCallback callbackInstance = mock(StringCallback.class); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(argument)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); } @@ -82,8 +78,7 @@ public class LambdaSafeTests { public void callbackInvokeWhenHasResolvableGenericMatchShouldInvokeCallback() { StringBuilderCallback callbackInstance = mock(StringBuilderCallback.class); StringBuilder argument = new StringBuilder("foo"); - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(argument)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); } @@ -92,26 +87,22 @@ public class LambdaSafeTests { public void callbackInvokeWhenHasResolvableGenericNonMatchShouldNotInvokeCallback() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(argument)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); verifyZeroInteractions(callbackInstance); } @Test @SuppressWarnings("unchecked") public void callbackInvokeWhenLambdaMismatchShouldSwallowException() { - GenericCallback callbackInstance = (s) -> fail( - "Should not get here"); + GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(argument)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); } @Test @SuppressWarnings("unchecked") public void callbackInvokeWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { - GenericMultiArgCallback callbackInstance = (n, s, - b) -> fail("Should not get here"); + GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callback(GenericMultiArgCallback.class, callbackInstance, argument) .invoke((c) -> c.handle(1, argument, false)); @@ -122,8 +113,7 @@ public class LambdaSafeTests { NonGenericFactory callbackInstance = mock(NonGenericFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); - InvocationResult result = LambdaSafe - .callback(NonGenericFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(NonGenericFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); @@ -135,8 +125,7 @@ public class LambdaSafeTests { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); - InvocationResult result = LambdaSafe - .callback(GenericFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); @@ -148,8 +137,7 @@ public class LambdaSafeTests { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); - InvocationResult result = LambdaSafe - .callback(GenericFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isNull(); @@ -161,8 +149,7 @@ public class LambdaSafeTests { StringBuilderFactory callbackInstance = mock(StringBuilderFactory.class); StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); - InvocationResult result = LambdaSafe - .callback(GenericFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); assertThat(result.hasResult()).isTrue(); @@ -174,8 +161,7 @@ public class LambdaSafeTests { public void callbackInvokeAndWhenHasResolvableGenericNonMatchShouldReturnNoResult() { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; - InvocationResult result = LambdaSafe - .callback(GenericFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isFalse(); verifyZeroInteractions(callbackInstance); @@ -189,8 +175,7 @@ public class LambdaSafeTests { return 123; }; String argument = "foo"; - InvocationResult result = LambdaSafe - .callback(GenericFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isFalse(); } @@ -203,8 +188,7 @@ public class LambdaSafeTests { return 123; }; String argument = "foo"; - InvocationResult result = LambdaSafe - .callback(GenericMultiArgFactory.class, callbackInstance, argument) + InvocationResult result = LambdaSafe.callback(GenericMultiArgFactory.class, callbackInstance, argument) .invokeAnd((c) -> c.handle(1, argument, false)); assertThat(result.hasResult()).isFalse(); } @@ -213,9 +197,7 @@ public class LambdaSafeTests { public void callbacksInvokeWhenNoGenericShouldInvokeCallbacks() { NonGenericCallback callbackInstance = mock(NonGenericCallback.class); String argument = "foo"; - LambdaSafe - .callbacks(NonGenericCallback.class, - Collections.singleton(callbackInstance), argument) + LambdaSafe.callbacks(NonGenericCallback.class, Collections.singleton(callbackInstance), argument) .invoke((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); } @@ -225,8 +207,7 @@ public class LambdaSafeTests { public void callbacksInvokeWhenHasGenericShouldInvokeCallback() { StringCallback callbackInstance = mock(StringCallback.class); String argument = "foo"; - LambdaSafe.callbacks(GenericCallback.class, - Collections.singleton(callbackInstance), argument) + LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) .invoke((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); } @@ -236,8 +217,7 @@ public class LambdaSafeTests { public void callbacksInvokeWhenHasResolvableGenericMatchShouldInvokeCallback() { StringBuilderCallback callbackInstance = mock(StringBuilderCallback.class); StringBuilder argument = new StringBuilder("foo"); - LambdaSafe.callbacks(GenericCallback.class, - Collections.singleton(callbackInstance), argument) + LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) .invoke((c) -> c.handle(argument)); verify(callbackInstance).handle(argument); } @@ -247,8 +227,7 @@ public class LambdaSafeTests { public void callbacksInvokeWhenHasResolvableGenericNonMatchShouldNotInvokeCallback() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; - LambdaSafe.callbacks(GenericCallback.class, - Collections.singleton(callbackInstance), argument) + LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) .invoke((c) -> c.handle(null)); verifyZeroInteractions(callbackInstance); } @@ -256,23 +235,18 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") public void callbacksInvokeWhenLambdaMismatchShouldSwallowException() { - GenericCallback callbackInstance = (s) -> fail( - "Should not get here"); + GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; - LambdaSafe.callbacks(GenericCallback.class, - Collections.singleton(callbackInstance), argument) + LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) .invoke((c) -> c.handle(argument)); } @Test @SuppressWarnings("unchecked") public void callbacksInvokeWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { - GenericMultiArgCallback callbackInstance = (n, s, - b) -> fail("Should not get here"); + GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; - LambdaSafe - .callbacks(GenericMultiArgCallback.class, - Collections.singleton(callbackInstance), argument) + LambdaSafe.callbacks(GenericMultiArgCallback.class, Collections.singleton(callbackInstance), argument) .invoke((c) -> c.handle(1, argument, false)); } @@ -282,8 +256,7 @@ public class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); Stream result = LambdaSafe - .callbacks(NonGenericFactory.class, - Collections.singleton(callbackInstance), argument) + .callbacks(NonGenericFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -294,8 +267,8 @@ public class LambdaSafeTests { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); - Stream result = LambdaSafe.callbacks(GenericFactory.class, - Collections.singleton(callbackInstance), argument) + Stream result = LambdaSafe + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -306,8 +279,8 @@ public class LambdaSafeTests { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); - Stream result = LambdaSafe.callbacks(GenericFactory.class, - Collections.singleton(callbackInstance), argument) + Stream result = LambdaSafe + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly((Integer) null); } @@ -318,8 +291,8 @@ public class LambdaSafeTests { StringBuilderFactory callbackInstance = mock(StringBuilderFactory.class); StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); - Stream result = LambdaSafe.callbacks(GenericFactory.class, - Collections.singleton(callbackInstance), argument) + Stream result = LambdaSafe + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -329,8 +302,8 @@ public class LambdaSafeTests { public void callbacksInvokeAndWhenHasResolvableGenericNonMatchShouldReturnNoResult() { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; - Stream result = LambdaSafe.callbacks(GenericFactory.class, - Collections.singleton(callbackInstance), argument) + Stream result = LambdaSafe + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result).isEmpty(); } @@ -343,8 +316,8 @@ public class LambdaSafeTests { return 123; }; String argument = "foo"; - Stream result = LambdaSafe.callbacks(GenericFactory.class, - Collections.singleton(callbackInstance), argument) + Stream result = LambdaSafe + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> (c).handle(argument)); assertThat(result).isEmpty(); } @@ -358,8 +331,7 @@ public class LambdaSafeTests { }; String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericMultiArgFactory.class, - Collections.singleton(callbackInstance), argument) + .callbacks(GenericMultiArgFactory.class, Collections.singleton(callbackInstance), argument) .invokeAnd((c) -> c.handle(1, argument, false)); assertThat(result).isEmpty(); } @@ -381,8 +353,7 @@ public class LambdaSafeTests { callbackInstances.add(callback4); callbackInstances.add(callback5); String argument = "foo"; - Stream result = LambdaSafe - .callbacks(GenericFactory.class, callbackInstances, argument) + Stream result = LambdaSafe.callbacks(GenericFactory.class, callbackInstances, argument) .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(1, 2, 4); } @@ -392,8 +363,8 @@ public class LambdaSafeTests { public void callbackWithFilterShouldUseFilter() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) - .withFilter(Filter.allowAll()).invoke((c) -> c.handle(null)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withFilter(Filter.allowAll()) + .invoke((c) -> c.handle(null)); verify(callbackInstance).handle(null); } @@ -402,13 +373,13 @@ public class LambdaSafeTests { public void callbackWithLoggerShouldUseLogger() { Log logger = mock(Log.class); given(logger.isDebugEnabled()).willReturn(true); - GenericCallback callbackInstance = (s) -> fail( - "Should not get here"); + GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) - .withLogger(logger).invoke((c) -> c.handle(argument)); - verify(logger).debug(contains("Non-matching CharSequence type for callback " - + "LambdaSafeTests.GenericCallback"), any(Throwable.class)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withLogger(logger) + .invoke((c) -> c.handle(argument)); + verify(logger).debug( + contains("Non-matching CharSequence type for callback " + "LambdaSafeTests.GenericCallback"), + any(Throwable.class)); } interface NonGenericCallback { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java index ef825f02688..41936b88f71 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ public class MessageInterpolatorFactoryWithoutElIntegrationTests { @Test public void defaultMessageInterpolatorShouldFail() { // Sanity test - assertThatExceptionOfType(ValidationException.class).isThrownBy( - Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) + assertThatExceptionOfType(ValidationException.class) + .isThrownBy(Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) .withMessageContaining("javax.el.ExpressionFactory"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java index 3562de4b4dd..01cc0203755 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java @@ -41,8 +41,7 @@ public class BasicAuthenticationClientHttpRequestFactoryTests { private final HttpHeaders headers = new HttpHeaders(); - private final BasicAuthentication authentication = new BasicAuthentication("spring", - "boot", null); + private final BasicAuthentication authentication = new BasicAuthentication("spring", "boot", null); private ClientHttpRequestFactory requestFactory; @@ -52,30 +51,25 @@ public class BasicAuthenticationClientHttpRequestFactoryTests { ClientHttpRequest request = mock(ClientHttpRequest.class); given(requestFactory.createRequest(any(), any())).willReturn(request); given(request.getHeaders()).willReturn(this.headers); - this.requestFactory = new BasicAuthenticationClientHttpRequestFactory( - this.authentication, requestFactory); + this.requestFactory = new BasicAuthenticationClientHttpRequestFactory(this.authentication, requestFactory); } @Test public void shouldAddAuthorizationHeader() throws IOException { ClientHttpRequest request = createRequest(); - assertThat(request.getHeaders().get(HttpHeaders.AUTHORIZATION)) - .containsExactly("Basic c3ByaW5nOmJvb3Q="); + assertThat(request.getHeaders().get(HttpHeaders.AUTHORIZATION)).containsExactly("Basic c3ByaW5nOmJvb3Q="); } @Test - public void shouldNotAddAuthorizationHeaderAuthorizationAlreadySet() - throws IOException { + public void shouldNotAddAuthorizationHeaderAuthorizationAlreadySet() throws IOException { this.headers.setBasicAuth("boot", "spring"); ClientHttpRequest request = createRequest(); - assertThat(request.getHeaders().get(HttpHeaders.AUTHORIZATION)) - .doesNotContain("Basic c3ByaW5nOmJvb3Q="); + assertThat(request.getHeaders().get(HttpHeaders.AUTHORIZATION)).doesNotContain("Basic c3ByaW5nOmJvb3Q="); } private ClientHttpRequest createRequest() throws IOException { - return this.requestFactory.createRequest(URI.create("https://localhost:8080"), - HttpMethod.POST); + return this.requestFactory.createRequest(URI.create("https://localhost:8080"), HttpMethod.POST); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index d94cb43560c..1f6827266f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -84,8 +84,7 @@ public class RestTemplateBuilderTests { @Test public void createWhenCustomizersAreNullShouldThrowException() { RestTemplateCustomizer[] customizers = null; - assertThatIllegalArgumentException() - .isThrownBy(() -> new RestTemplateBuilder(customizers)) + assertThatIllegalArgumentException().isThrownBy(() -> new RestTemplateBuilder(customizers)) .withMessageContaining("Customizers must not be null"); } @@ -99,15 +98,13 @@ public class RestTemplateBuilderTests { @Test public void buildShouldDetectRequestFactory() { RestTemplate restTemplate = this.builder.build(); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test public void detectRequestFactoryWhenFalseShouldDisableDetection() { RestTemplate restTemplate = this.builder.detectRequestFactory(false).build(); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SimpleClientHttpRequestFactory.class); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test @@ -122,8 +119,8 @@ public class RestTemplateBuilderTests { @Test public void rootUriShouldApplyAfterUriTemplateHandler() { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); - RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler) - .rootUri("https://example.com").build(); + RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).rootUri("https://example.com") + .build(); UriTemplateHandler handler = template.getUriTemplateHandler(); handler.expand("/hello"); assertThat(handler).isInstanceOf(RootUriTemplateHandler.class); @@ -132,29 +129,27 @@ public class RestTemplateBuilderTests { @Test public void messageConvertersWhenConvertersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.messageConverters((HttpMessageConverter[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.messageConverters((HttpMessageConverter[]) null)) .withMessageContaining("MessageConverters must not be null"); } @Test public void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.messageConverters((Set>) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.messageConverters((Set>) null)) .withMessageContaining("MessageConverters must not be null"); } @Test public void messageConvertersShouldApply() { - RestTemplate template = this.builder.messageConverters(this.messageConverter) - .build(); + RestTemplate template = this.builder.messageConverters(this.messageConverter).build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test public void messageConvertersShouldReplaceExisting() { - RestTemplate template = this.builder - .messageConverters(new ResourceHttpMessageConverter()) + RestTemplate template = this.builder.messageConverters(new ResourceHttpMessageConverter()) .messageConverters(Collections.singleton(this.messageConverter)).build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @@ -162,16 +157,14 @@ public class RestTemplateBuilderTests { @Test public void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalMessageConverters((HttpMessageConverter[]) null)) + .isThrownBy(() -> this.builder.additionalMessageConverters((HttpMessageConverter[]) null)) .withMessageContaining("MessageConverters must not be null"); } @Test public void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalMessageConverters((Set>) null)) + .isThrownBy(() -> this.builder.additionalMessageConverters((Set>) null)) .withMessageContaining("MessageConverters must not be null"); } @@ -180,40 +173,34 @@ public class RestTemplateBuilderTests { HttpMessageConverter resourceConverter = new ResourceHttpMessageConverter(); RestTemplate template = this.builder.messageConverters(resourceConverter) .additionalMessageConverters(this.messageConverter).build(); - assertThat(template.getMessageConverters()).containsOnly(resourceConverter, - this.messageConverter); + assertThat(template.getMessageConverters()).containsOnly(resourceConverter, this.messageConverter); } @Test public void defaultMessageConvertersShouldSetDefaultList() { - RestTemplate template = new RestTemplate( - Collections.singletonList(new StringHttpMessageConverter())); + RestTemplate template = new RestTemplate(Collections.singletonList(new StringHttpMessageConverter())); this.builder.defaultMessageConverters().configure(template); - assertThat(template.getMessageConverters()) - .hasSameSizeAs(new RestTemplate().getMessageConverters()); + assertThat(template.getMessageConverters()).hasSameSizeAs(new RestTemplate().getMessageConverters()); } @Test public void defaultMessageConvertersShouldClearExisting() { - RestTemplate template = new RestTemplate( - Collections.singletonList(new StringHttpMessageConverter())); - this.builder.additionalMessageConverters(this.messageConverter) - .defaultMessageConverters().configure(template); - assertThat(template.getMessageConverters()) - .hasSameSizeAs(new RestTemplate().getMessageConverters()); + RestTemplate template = new RestTemplate(Collections.singletonList(new StringHttpMessageConverter())); + this.builder.additionalMessageConverters(this.messageConverter).defaultMessageConverters().configure(template); + assertThat(template.getMessageConverters()).hasSameSizeAs(new RestTemplate().getMessageConverters()); } @Test public void interceptorsWhenInterceptorsAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) .withMessageContaining("interceptors must not be null"); } @Test public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.interceptors((Set) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.interceptors((Set) null)) .withMessageContaining("interceptors must not be null"); } @@ -225,8 +212,7 @@ public class RestTemplateBuilderTests { @Test public void interceptorsShouldReplaceExisting() { - RestTemplate template = this.builder - .interceptors(mock(ClientHttpRequestInterceptor.class)) + RestTemplate template = this.builder.interceptors(mock(ClientHttpRequestInterceptor.class)) .interceptors(Collections.singleton(this.interceptor)).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @@ -234,57 +220,47 @@ public class RestTemplateBuilderTests { @Test public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalInterceptors((ClientHttpRequestInterceptor[]) null)) + .isThrownBy(() -> this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null)) .withMessageContaining("interceptors must not be null"); } @Test public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalInterceptors((Set) null)) + .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) .withMessageContaining("interceptors must not be null"); } @Test public void additionalInterceptorsShouldAddToExisting() { - ClientHttpRequestInterceptor interceptor = mock( - ClientHttpRequestInterceptor.class); - RestTemplate template = this.builder.interceptors(interceptor) - .additionalInterceptors(this.interceptor).build(); - assertThat(template.getInterceptors()).containsOnly(interceptor, - this.interceptor); + ClientHttpRequestInterceptor interceptor = mock(ClientHttpRequestInterceptor.class); + RestTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor).build(); + assertThat(template.getInterceptors()).containsOnly(interceptor, this.interceptor); } @Test public void requestFactoryClassWhenFactoryIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.requestFactory((Class) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.requestFactory((Class) null)) .withMessageContaining("RequestFactory must not be null"); } @Test public void requestFactoryClassShouldApply() { - RestTemplate template = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class).build(); - assertThat(template.getRequestFactory()) - .isInstanceOf(SimpleClientHttpRequestFactory.class); + RestTemplate template = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).build(); + assertThat(template.getRequestFactory()).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test public void requestFactoryPackagePrivateClassShouldApply() { - RestTemplate template = this.builder - .requestFactory(TestClientHttpRequestFactory.class).build(); - assertThat(template.getRequestFactory()) - .isInstanceOf(TestClientHttpRequestFactory.class); + RestTemplate template = this.builder.requestFactory(TestClientHttpRequestFactory.class).build(); + assertThat(template.getRequestFactory()).isInstanceOf(TestClientHttpRequestFactory.class); } @Test public void requestFactoryWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .requestFactory((Supplier) null)) + .isThrownBy(() -> this.builder.requestFactory((Supplier) null)) .withMessageContaining("RequestFactory Supplier must not be null"); } @@ -297,23 +273,20 @@ public class RestTemplateBuilderTests { @Test public void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.uriTemplateHandler(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.builder.uriTemplateHandler(null)) .withMessageContaining("UriTemplateHandler must not be null"); } @Test public void uriTemplateHandlerShouldApply() { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); - RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler) - .build(); + RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).build(); assertThat(template.getUriTemplateHandler()).isSameAs(uriTemplateHandler); } @Test public void errorHandlerWhenHandlerIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.errorHandler(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.builder.errorHandler(null)) .withMessageContaining("ErrorHandler must not be null"); } @@ -326,27 +299,23 @@ public class RestTemplateBuilderTests { @Test public void basicAuthenticationShouldApply() { - RestTemplate template = this.builder - .basicAuthentication("spring", "boot", StandardCharsets.UTF_8).build(); + RestTemplate template = this.builder.basicAuthentication("spring", "boot", StandardCharsets.UTF_8).build(); ClientHttpRequestFactory requestFactory = template.getRequestFactory(); - Object authentication = ReflectionTestUtils.getField(requestFactory, - "authentication"); - assertThat(authentication).extracting("username", "password", "charset") - .containsExactly("spring", "boot", StandardCharsets.UTF_8); + Object authentication = ReflectionTestUtils.getField(requestFactory, "authentication"); + assertThat(authentication).extracting("username", "password", "charset").containsExactly("spring", "boot", + StandardCharsets.UTF_8); } @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.builder.customizers((RestTemplateCustomizer[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((RestTemplateCustomizer[]) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.customizers((Set) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.customizers((Set) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @@ -360,8 +329,8 @@ public class RestTemplateBuilderTests { @Test public void customizersShouldBeAppliedLast() { RestTemplate template = spy(new RestTemplate()); - this.builder.additionalCustomizers((restTemplate) -> verify(restTemplate) - .setRequestFactory(any(ClientHttpRequestFactory.class))); + this.builder.additionalCustomizers( + (restTemplate) -> verify(restTemplate).setRequestFactory(any(ClientHttpRequestFactory.class))); this.builder.configure(template); } @@ -369,24 +338,23 @@ public class RestTemplateBuilderTests { public void customizersShouldReplaceExisting() { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); - RestTemplate template = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + RestTemplate template = this.builder.customizers(customizer1).customizers(Collections.singleton(customizer2)) + .build(); verifyZeroInteractions(customizer1); verify(customizer2).customize(template); } @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalCustomizers((Set) null)) + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @@ -394,8 +362,7 @@ public class RestTemplateBuilderTests { public void additionalCustomizersShouldAddToExisting() { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); - RestTemplate template = this.builder.customizers(customizer1) - .additionalCustomizers(customizer2).build(); + RestTemplate template = this.builder.customizers(customizer1).additionalCustomizers(customizer2).build(); InOrder ordered = inOrder(customizer1, customizer2); ordered.verify(customizer1).customize(template); ordered.verify(customizer2).customize(template); @@ -405,26 +372,19 @@ public class RestTemplateBuilderTests { public void customizerShouldBeAppliedAtTheEnd() { ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - this.builder.interceptors(this.interceptor) - .messageConverters(this.messageConverter).rootUri("http://localhost:8080") - .errorHandler(errorHandler).basicAuthentication("spring", "boot") + this.builder.interceptors(this.interceptor).messageConverters(this.messageConverter) + .rootUri("http://localhost:8080").errorHandler(errorHandler).basicAuthentication("spring", "boot") .requestFactory(() -> requestFactory).customizers((restTemplate) -> { assertThat(restTemplate.getInterceptors()).hasSize(1); - assertThat(restTemplate.getMessageConverters()) - .contains(this.messageConverter); - assertThat(restTemplate.getUriTemplateHandler()) - .isInstanceOf(RootUriTemplateHandler.class); + assertThat(restTemplate.getMessageConverters()).contains(this.messageConverter); + assertThat(restTemplate.getUriTemplateHandler()).isInstanceOf(RootUriTemplateHandler.class); assertThat(restTemplate.getErrorHandler()).isEqualTo(errorHandler); - ClientHttpRequestFactory actualRequestFactory = restTemplate - .getRequestFactory(); - assertThat(actualRequestFactory) - .isInstanceOf(InterceptingClientHttpRequestFactory.class); + ClientHttpRequestFactory actualRequestFactory = restTemplate.getRequestFactory(); + assertThat(actualRequestFactory).isInstanceOf(InterceptingClientHttpRequestFactory.class); ClientHttpRequestFactory authRequestFactory = (ClientHttpRequestFactory) ReflectionTestUtils .getField(actualRequestFactory, "requestFactory"); - assertThat(authRequestFactory).isInstanceOf( - BasicAuthenticationClientHttpRequestFactory.class); - assertThat(authRequestFactory).hasFieldOrPropertyWithValue( - "requestFactory", requestFactory); + assertThat(authRequestFactory).isInstanceOf(BasicAuthenticationClientHttpRequestFactory.class); + assertThat(authRequestFactory).hasFieldOrPropertyWithValue("requestFactory", requestFactory); }).build(); } @@ -444,117 +404,102 @@ public class RestTemplateBuilderTests { public void configureShouldApply() { RestTemplate template = new RestTemplate(); this.builder.configure(template); - assertThat(template.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + assertThat(template.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test public void connectTimeoutCanBeNullToUseDefault() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setConnectTimeout(null).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", -1); } @Test public void readTimeoutCanBeNullToUseDefault() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class).setReadTimeout(null) - .build().getRequestFactory(); + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) + .setReadTimeout(null).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", -1); } @Test public void connectTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); - assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, - "requestConfig")).getConnectTimeout()).isEqualTo(1234); + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setConnectTimeout(Duration.ofMillis(1234)) + .build().getRequestFactory(); + assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getConnectTimeout()) + .isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); - assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, - "requestConfig")).getSocketTimeout()).isEqualTo(1234); + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setReadTimeout(Duration.ofMillis(1234)) + .build().getRequestFactory(); + assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getSocketTimeout()) + .isEqualTo(1234); } @Test public void bufferRequestBodyCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setBufferRequestBody(false).build().getRequestFactory(); - assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", - false); - requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setBufferRequestBody(false).build() + .getRequestFactory(); + assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); + requestFactory = this.builder.requestFactory(HttpComponentsClientHttpRequestFactory.class) .setBufferRequestBody(true).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); - requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class).build() + requestFactory = this.builder.requestFactory(HttpComponentsClientHttpRequestFactory.class).build() .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); } @Test public void connectTimeoutCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 1234); } @Test public void readTimeoutCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 1234); } @Test public void bufferRequestBodyCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setBufferRequestBody(false).build().getRequestFactory(); - assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", - false); - requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) - .setBufferRequestBody(true).build().getRequestFactory(); - assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); - requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) + assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); + requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).setBufferRequestBody(true) .build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); + requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).build().getRequestFactory(); + assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); } @Test public void connectTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttp3ClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField( - ReflectionTestUtils.getField(requestFactory, "client"), "connectTimeout")) + assertThat( + ReflectionTestUtils.getField(ReflectionTestUtils.getField(requestFactory, "client"), "connectTimeout")) .isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttp3ClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField( - ReflectionTestUtils.getField(requestFactory, "client"), "readTimeout")) - .isEqualTo(1234); + assertThat(ReflectionTestUtils.getField(ReflectionTestUtils.getField(requestFactory, "client"), "readTimeout")) + .isEqualTo(1234); } @Test public void bufferRequestBodyCanNotBeConfiguredOnOkHttp3RequestFactory() { assertThatIllegalStateException() - .isThrownBy(() -> this.builder - .requestFactory(OkHttp3ClientHttpRequestFactory.class) + .isThrownBy(() -> this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setBufferRequestBody(false).build().getRequestFactory()) .withMessageContaining(OkHttp3ClientHttpRequestFactory.class.getName()); } @@ -562,9 +507,7 @@ public class RestTemplateBuilderTests { @Test public void connectTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setConnectTimeout(Duration.ofMillis(1234)).build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 1234); } @@ -572,9 +515,7 @@ public class RestTemplateBuilderTests { @Test public void readTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setReadTimeout(Duration.ofMillis(1234)).build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 1234); } @@ -582,33 +523,22 @@ public class RestTemplateBuilderTests { @Test public void bufferRequestBodyCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setBufferRequestBody(false).build(); - assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", - false); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) + assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setBufferRequestBody(true).build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) - .build(); + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)).build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); } @Test public void unwrappingDoesNotAffectRequestFactoryThatIsSetOnTheBuiltTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - RestTemplate template = this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) + RestTemplate template = this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .build(); - assertThat(template.getRequestFactory()) - .isInstanceOf(BufferingClientHttpRequestFactory.class); + assertThat(template.getRequestFactory()).isInstanceOf(BufferingClientHttpRequestFactory.class); } public static class RestTemplateSubclass extends RestTemplate { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java index f295deaee62..52d92fc6e6b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java @@ -57,21 +57,18 @@ public class RootUriTemplateHandlerTests { this.uri = new URI("https://example.com/hello"); this.handler = new RootUriTemplateHandler("https://example.com", this.delegate); given(this.delegate.expand(anyString(), any(Map.class))).willReturn(this.uri); - given(this.delegate.expand(anyString(), any(Object[].class))) - .willReturn(this.uri); + given(this.delegate.expand(anyString(), any(Object[].class))).willReturn(this.uri); } @Test public void createWithNullRootUriShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RootUriTemplateHandler((String) null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler((String) null)) .withMessageContaining("RootUri must not be null"); } @Test public void createWithNullHandlerShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RootUriTemplateHandler("https://example.com", null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler("https://example.com", null)) .withMessageContaining("Handler must not be null"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java index 7ac7082a039..d78a2e3a811 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java @@ -88,10 +88,9 @@ public class WebServerPortFileWriterTest { listener.onApplicationEvent(mockEvent("management", 9090)); assertThat(contentOf(file)).isEqualTo("8080"); String managementFile = file.getName(); - managementFile = managementFile.substring(0, managementFile.length() - - StringUtils.getFilenameExtension(managementFile).length() - 1); - managementFile = managementFile + "-management." - + StringUtils.getFilenameExtension(file.getName()); + managementFile = managementFile.substring(0, + managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); + managementFile = managementFile + "-management." + StringUtils.getFilenameExtension(file.getName()); String content = contentOf(new File(file.getParentFile(), managementFile)); assertThat(content).isEqualTo("9090"); assertThat(collectFileNames(file.getParentFile())).contains(managementFile); @@ -104,10 +103,9 @@ public class WebServerPortFileWriterTest { WebServerPortFileWriter listener = new WebServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("management", 9090)); String managementFile = file.getName(); - managementFile = managementFile.substring(0, managementFile.length() - - StringUtils.getFilenameExtension(managementFile).length() - 1); - managementFile = managementFile + "-MANAGEMENT." - + StringUtils.getFilenameExtension(file.getName()); + managementFile = managementFile.substring(0, + managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); + managementFile = managementFile + "-MANAGEMENT." + StringUtils.getFilenameExtension(file.getName()); String content = contentOf(new File(file.getParentFile(), managementFile)); assertThat(content).isEqualTo("9090"); assertThat(collectFileNames(file.getParentFile())).contains(managementFile); @@ -116,8 +114,7 @@ public class WebServerPortFileWriterTest { private WebServerInitializedEvent mockEvent(String namespace, int port) { WebServer webServer = mock(WebServer.class); given(webServer.getPort()).willReturn(port); - WebServerApplicationContext applicationContext = mock( - WebServerApplicationContext.class); + WebServerApplicationContext applicationContext = mock(WebServerApplicationContext.class); given(applicationContext.getServerNamespace()).willReturn(namespace); given(applicationContext.getWebServer()).willReturn(webServer); WebServerInitializedEvent event = mock(WebServerInitializedEvent.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java index bac3e80e3a9..9c1ecd53c29 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Madhura Bhave */ -public class JettyReactiveWebServerFactoryTests - extends AbstractReactiveWebServerFactoryTests { +public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Override protected JettyReactiveWebServerFactory getFactory() { @@ -52,16 +51,15 @@ public class JettyReactiveWebServerFactoryTests @Test public void setNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setServerCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setServerCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test public void addNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy( - () -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @@ -87,10 +85,8 @@ public class JettyReactiveWebServerFactoryTests factory.setAddress(InetAddress.getByAddress(localhost.getAddress())); this.webServer = factory.getWebServer(mock(HttpHandler.class)); this.webServer.start(); - Connector connector = ((JettyWebServer) this.webServer).getServer() - .getConnectors()[0]; - assertThat(((ServerConnector) connector).getHost()) - .isEqualTo(localhost.getHostAddress()); + Connector connector = ((JettyWebServer) this.webServer).getServer().getConnectors()[0]; + assertThat(((ServerConnector) connector).getHost()).isEqualTo(localhost.getHostAddress()); } @Test @@ -106,12 +102,10 @@ public class JettyReactiveWebServerFactoryTests resourceFactory.afterPropertiesSet(); JettyReactiveWebServerFactory factory = getFactory(); factory.setResourceFactory(resourceFactory); - JettyWebServer webServer = (JettyWebServer) factory - .getWebServer(new EchoHandler()); + JettyWebServer webServer = (JettyWebServer) factory.getWebServer(new EchoHandler()); webServer.start(); Connector connector = webServer.getServer().getConnectors()[0]; - assertThat(connector.getByteBufferPool()) - .isEqualTo(resourceFactory.getByteBufferPool()); + assertThat(connector.getByteBufferPool()).isEqualTo(resourceFactory.getByteBufferPool()); assertThat(connector.getExecutor()).isEqualTo(resourceFactory.getExecutor()); assertThat(connector.getScheduler()).isEqualTo(resourceFactory.getScheduler()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java index 6349e54f598..098069f06fc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java @@ -64,8 +64,7 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Henri Kerola */ -public class JettyServletWebServerFactoryTests - extends AbstractServletWebServerFactoryTests { +public class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { @Override protected JettyServletWebServerFactory getFactory() { @@ -129,14 +128,11 @@ public class JettyServletWebServerFactoryTests this.webServer.start(); JettyWebServer jettyWebServer = (JettyWebServer) this.webServer; - ServerConnector connector = (ServerConnector) jettyWebServer.getServer() - .getConnectors()[0]; - SslConnectionFactory connectionFactory = connector - .getConnectionFactory(SslConnectionFactory.class); - assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites()) - .containsExactly("ALPHA", "BRAVO", "CHARLIE"); - assertThat(connectionFactory.getSslContextFactory().getExcludeCipherSuites()) - .isEmpty(); + ServerConnector connector = (ServerConnector) jettyWebServer.getServer().getConnectors()[0]; + SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class); + assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites()).containsExactly("ALPHA", "BRAVO", + "CHARLIE"); + assertThat(connectionFactory.getSslContextFactory().getExcludeCipherSuites()).isEmpty(); } @Test @@ -164,12 +160,10 @@ public class JettyServletWebServerFactoryTests this.webServer = factory.getWebServer(); this.webServer.start(); JettyWebServer jettyWebServer = (JettyWebServer) this.webServer; - ServerConnector connector = (ServerConnector) jettyWebServer.getServer() - .getConnectors()[0]; - SslConnectionFactory connectionFactory = connector - .getConnectionFactory(SslConnectionFactory.class); - assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols()) - .containsExactly("TLSv1.1", "TLSv1.2"); + ServerConnector connector = (ServerConnector) jettyWebServer.getServer().getConnectors()[0]; + SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class); + assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols()).containsExactly("TLSv1.1", + "TLSv1.2"); } @Test @@ -179,12 +173,9 @@ public class JettyServletWebServerFactoryTests this.webServer = factory.getWebServer(); this.webServer.start(); JettyWebServer jettyWebServer = (JettyWebServer) this.webServer; - ServerConnector connector = (ServerConnector) jettyWebServer.getServer() - .getConnectors()[0]; - SslConnectionFactory connectionFactory = connector - .getConnectionFactory(SslConnectionFactory.class); - assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols()) - .containsExactly("TLSv1.1"); + ServerConnector connector = (ServerConnector) jettyWebServer.getServer().getConnectors()[0]; + SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class); + assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols()).containsExactly("TLSv1.1"); } private Ssl getSslSettings(String... enabledProtocols) { @@ -200,8 +191,7 @@ public class JettyServletWebServerFactoryTests private void assertTimeout(JettyServletWebServerFactory factory, int expected) { this.webServer = factory.getWebServer(); JettyWebServer jettyWebServer = (JettyWebServer) this.webServer; - Handler[] handlers = jettyWebServer.getServer() - .getChildHandlersByClass(WebAppContext.class); + Handler[] handlers = jettyWebServer.getServer().getChildHandlersByClass(WebAppContext.class); WebAppContext webAppContext = (WebAppContext) handlers[0]; int actual = webAppContext.getSessionHandler().getMaxInactiveInterval(); assertThat(actual).isEqualTo(expected); @@ -241,8 +231,7 @@ public class JettyServletWebServerFactoryTests factory.setThreadPool(null); assertThat(factory.getThreadPool()).isNull(); this.webServer = factory.getWebServer(); - assertThat(((JettyWebServer) this.webServer).getServer().getThreadPool()) - .isNotNull(); + assertThat(((JettyWebServer) this.webServer).getServer().getThreadPool()).isNotNull(); } @Test @@ -251,8 +240,7 @@ public class JettyServletWebServerFactoryTests ThreadPool threadPool = mock(ThreadPool.class); factory.setThreadPool(threadPool); this.webServer = factory.getWebServer(); - assertThat(((JettyWebServer) this.webServer).getServer().getThreadPool()) - .isSameAs(threadPool); + assertThat(((JettyWebServer) this.webServer).getServer().getThreadPool()).isSameAs(threadPool); } @Test @@ -263,8 +251,7 @@ public class JettyServletWebServerFactoryTests threadPool.setMaxThreads(2); threadPool.setMinThreads(2); }); - assertThatExceptionOfType(WebServerException.class) - .isThrownBy(factory.getWebServer()::start) + assertThatExceptionOfType(WebServerException.class).isThrownBy(factory.getWebServer()::start) .withCauseInstanceOf(IllegalStateException.class); } @@ -275,10 +262,8 @@ public class JettyServletWebServerFactoryTests factory.setAddress(InetAddress.getByAddress(localhost.getAddress())); this.webServer = factory.getWebServer(); this.webServer.start(); - Connector connector = ((JettyWebServer) this.webServer).getServer() - .getConnectors()[0]; - assertThat(((ServerConnector) connector).getHost()) - .isEqualTo(localhost.getHostAddress()); + Connector connector = ((JettyWebServer) this.webServer).getServer().getConnectors()[0]; + assertThat(((ServerConnector) connector).getHost()).isEqualTo(localhost.getHostAddress()); } @Test @@ -293,10 +278,8 @@ public class JettyServletWebServerFactoryTests factory.setSsl(ssl); this.webServer = factory.getWebServer(); this.webServer.start(); - Connector connector = ((JettyWebServer) this.webServer).getServer() - .getConnectors()[0]; - assertThat(((ServerConnector) connector).getHost()) - .isEqualTo(localhost.getHostAddress()); + Connector connector = ((JettyWebServer) this.webServer).getServer().getConnectors()[0]; + assertThat(((ServerConnector) connector).getHost()).isEqualTo(localhost.getHostAddress()); } @Test @@ -323,8 +306,7 @@ public class JettyServletWebServerFactoryTests jettyWebServer.start(); } finally { - QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer - .getServer().getThreadPool(); + QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer.getServer().getThreadPool(); assertThat(threadPool.isRunning()).isFalse(); } }); @@ -332,8 +314,7 @@ public class JettyServletWebServerFactoryTests @Override protected JspServlet getJspServlet() throws Exception { - WebAppContext context = (WebAppContext) ((JettyWebServer) this.webServer) - .getServer().getHandler(); + WebAppContext context = (WebAppContext) ((JettyWebServer) this.webServer).getServer().getHandler(); ServletHolder holder = context.getServletHandler().getServlet("jsp"); if (holder == null) { return null; @@ -345,22 +326,19 @@ public class JettyServletWebServerFactoryTests @Override protected Map getActualMimeMappings() { - WebAppContext context = (WebAppContext) ((JettyWebServer) this.webServer) - .getServer().getHandler(); + WebAppContext context = (WebAppContext) ((JettyWebServer) this.webServer).getServer().getHandler(); return context.getMimeTypes().getMimeMap(); } @Override protected Charset getCharset(Locale locale) { - WebAppContext context = (WebAppContext) ((JettyWebServer) this.webServer) - .getServer().getHandler(); + WebAppContext context = (WebAppContext) ((JettyWebServer) this.webServer).getServer().getHandler(); String charsetName = context.getLocaleEncoding(locale); return (charsetName != null) ? Charset.forName(charsetName) : null; } @Override - protected void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort) { + protected void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort) { assertThat(ex).isInstanceOf(PortInUseException.class); assertThat(((PortInUseException) ex).getPort()).isEqualTo(blockedPort); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java index 4a219323963..71b062d69a8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java @@ -48,8 +48,7 @@ public class SslServerCustomizerTests { public void whenHttp2IsNotEnabledServerConnectorHasSslAndHttpConnectionFactories() { Server server = createCustomizedServer(); assertThat(server.getConnectors()).hasSize(1); - List factories = new ArrayList<>( - server.getConnectors()[0].getConnectionFactories()); + List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); assertThat(factories).extracting((factory) -> (Class) factory.getClass()) .containsExactly(SslConnectionFactory.class, HttpConnectionFactory.class); } @@ -61,12 +60,10 @@ public class SslServerCustomizerTests { http2.setEnabled(true); Server server = createCustomizedServer(http2); assertThat(server.getConnectors()).hasSize(1); - List factories = new ArrayList<>( - server.getConnectors()[0].getConnectionFactories()); - assertThat(factories).extracting((factory) -> (Class) factory.getClass()) - .containsExactly(SslConnectionFactory.class, - ALPNServerConnectionFactory.class, - HTTP2ServerConnectionFactory.class, HttpConnectionFactory.class); + List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); + assertThat(factories).extracting((factory) -> (Class) factory.getClass()).containsExactly( + SslConnectionFactory.class, ALPNServerConnectionFactory.class, HTTP2ServerConnectionFactory.class, + HttpConnectionFactory.class); } @Test @@ -75,22 +72,19 @@ public class SslServerCustomizerTests { http2.setEnabled(true); Server server = createCustomizedServer(http2); assertThat(server.getConnectors()).hasSize(1); - List factories = new ArrayList<>( - server.getConnectors()[0].getConnectionFactories()); - assertThat(((ALPNServerConnectionFactory) factories.get(1)).getDefaultProtocol()) - .isNull(); + List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); + assertThat(((ALPNServerConnectionFactory) factories.get(1)).getDefaultProtocol()).isNull(); } @Test public void configureSslWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); - assertThatExceptionOfType(Exception.class).isThrownBy( - () -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) .satisfies((ex) -> { assertThat(ex).isInstanceOf(WebServerException.class); - assertThat(ex) - .hasMessageContaining("Could not load key store 'null'"); + assertThat(ex).hasMessageContaining("Could not load key store 'null'"); }); } @@ -106,8 +100,7 @@ public class SslServerCustomizerTests { private Server createCustomizedServer(Ssl ssl, Http2 http2) { Server server = new Server(); - new SslServerCustomizer(new InetSocketAddress(0), ssl, null, http2) - .customize(server); + new SslServerCustomizer(new InetSocketAddress(0), ssl, null, http2).customize(server); return server; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java index de5be390489..641a75bfb63 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class NettyReactiveWebServerFactoryTests - extends AbstractReactiveWebServerFactoryTests { +public class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Override protected NettyReactiveWebServerFactory getFactory() { @@ -53,8 +52,7 @@ public class NettyReactiveWebServerFactoryTests this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); factory.setPort(this.webServer.getPort()); - assertThatExceptionOfType(PortInUseException.class) - .isThrownBy(factory.getWebServer(new EchoHandler())::start) + assertThatExceptionOfType(PortInUseException.class).isThrownBy(factory.getWebServer(new EchoHandler())::start) .satisfies(this::portMatchesRequirement); } @@ -68,8 +66,7 @@ public class NettyReactiveWebServerFactoryTests NettyServerCustomizer[] customizers = new NettyServerCustomizer[2]; for (int i = 0; i < customizers.length; i++) { customizers[i] = mock(NettyServerCustomizer.class); - given(customizers[i].apply(any(HttpServer.class))) - .will((invocation) -> invocation.getArgument(0)); + given(customizers[i].apply(any(HttpServer.class))).will((invocation) -> invocation.getArgument(0)); } factory.setServerCustomizers(Arrays.asList(customizers[0], customizers[1])); this.webServer = factory.getWebServer(new EchoHandler()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java index e3857556aca..f27e7bc9677 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java @@ -40,8 +40,7 @@ public class SslServerCustomizerTests { ssl.setKeyStore("src/test/resources/test.jks"); ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); - assertThatIllegalStateException() - .isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) + assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) .withCauseInstanceOf(NoSuchProviderException.class) .withMessageContaining("com.example.KeyStoreProvider"); } @@ -53,21 +52,17 @@ public class SslServerCustomizerTests { ssl.setTrustStore("src/test/resources/test.jks"); ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); - assertThatIllegalStateException() - .isThrownBy(() -> customizer.getTrustManagerFactory(ssl, null)) + assertThatIllegalStateException().isThrownBy(() -> customizer.getTrustManagerFactory(ssl, null)) .withCauseInstanceOf(NoSuchProviderException.class) .withMessageContaining("com.example.TrustStoreProvider"); } @Test - public void getKeyManagerFactoryWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() - throws Exception { + public void getKeyManagerFactoryWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() throws Exception { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); - assertThatIllegalStateException() - .isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(WebServerException.class) - .withMessageContaining("Could not load key store 'null'"); + assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) + .withCauseInstanceOf(WebServerException.class).withMessageContaining("Could not load key store 'null'"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java index c2fc93382cf..b457972555a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java @@ -58,8 +58,7 @@ public class CompressionConnectorCustomizerTests { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.addUpgradeProtocol(new Http2Protocol()); compressionConnectorCustomizer.customize(connector); - AbstractHttp11Protocol abstractHttp11Protocol = (AbstractHttp11Protocol) connector - .getProtocolHandler(); + AbstractHttp11Protocol abstractHttp11Protocol = (AbstractHttp11Protocol) connector.getProtocolHandler(); verifyHttp1(abstractHttp11Protocol); Http2Protocol http2Protocol = (Http2Protocol) connector.findUpgradeProtocols()[0]; verifyHttp2Upgrade(http2Protocol); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java index e79535e0940..35c5fc91ecf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java @@ -72,8 +72,7 @@ public class SslConnectorCustomizerTests { @After public void stop() throws Exception { System.clearProperty("javax.net.ssl.trustStorePassword"); - ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", - null); + ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); this.tomcat.stop(); } @@ -88,8 +87,7 @@ public class SslConnectorCustomizerTests { Connector connector = this.tomcat.getConnector(); customizer.customize(connector); this.tomcat.start(); - SSLHostConfig[] sslHostConfigs = connector.getProtocolHandler() - .findSslHostConfigs(); + SSLHostConfig[] sslHostConfigs = connector.getProtocolHandler().findSslHostConfigs(); assertThat(sslHostConfigs[0].getCiphers()).isEqualTo("ALPHA:BRAVO:CHARLIE"); } @@ -104,11 +102,9 @@ public class SslConnectorCustomizerTests { Connector connector = this.tomcat.getConnector(); customizer.customize(connector); this.tomcat.start(); - SSLHostConfig sslHostConfig = connector.getProtocolHandler() - .findSslHostConfigs()[0]; + SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; assertThat(sslHostConfig.getSslProtocol()).isEqualTo("TLS"); - assertThat(sslHostConfig.getEnabledProtocols()) - .containsExactlyInAnyOrder("TLSv1.1", "TLSv1.2"); + assertThat(sslHostConfig.getEnabledProtocols()).containsExactlyInAnyOrder("TLSv1.1", "TLSv1.2"); } @Test @@ -122,49 +118,41 @@ public class SslConnectorCustomizerTests { Connector connector = this.tomcat.getConnector(); customizer.customize(connector); this.tomcat.start(); - SSLHostConfig sslHostConfig = connector.getProtocolHandler() - .findSslHostConfigs()[0]; + SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; assertThat(sslHostConfig.getSslProtocol()).isEqualTo("TLS"); assertThat(sslHostConfig.getEnabledProtocols()).containsExactly("TLSv1.2"); } @Test - public void customizeWhenSslStoreProviderProvidesOnlyKeyStoreShouldUseDefaultTruststore() - throws Exception { + public void customizeWhenSslStoreProviderProvidesOnlyKeyStoreShouldUseDefaultTruststore() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setTrustStore("src/test/resources/test.jks"); SslStoreProvider sslStoreProvider = mock(SslStoreProvider.class); given(sslStoreProvider.getKeyStore()).willReturn(loadStore()); - SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, - sslStoreProvider); + SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, sslStoreProvider); Connector connector = this.tomcat.getConnector(); customizer.customize(connector); this.tomcat.start(); - SSLHostConfig sslHostConfig = connector.getProtocolHandler() - .findSslHostConfigs()[0]; + SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; SSLHostConfig sslHostConfigWithDefaults = new SSLHostConfig(); - assertThat(sslHostConfig.getTruststoreFile()) - .isEqualTo(sslHostConfigWithDefaults.getTruststoreFile()); + assertThat(sslHostConfig.getTruststoreFile()).isEqualTo(sslHostConfigWithDefaults.getTruststoreFile()); assertThat(sslHostConfig.getCertificateKeystoreFile()) .isEqualTo(SslStoreProviderUrlStreamHandlerFactory.KEY_STORE_URL); } @Test - public void customizeWhenSslStoreProviderProvidesOnlyTrustStoreShouldUseDefaultKeystore() - throws Exception { + public void customizeWhenSslStoreProviderProvidesOnlyTrustStoreShouldUseDefaultKeystore() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); SslStoreProvider sslStoreProvider = mock(SslStoreProvider.class); given(sslStoreProvider.getTrustStore()).willReturn(loadStore()); - SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, - sslStoreProvider); + SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, sslStoreProvider); Connector connector = this.tomcat.getConnector(); customizer.customize(connector); this.tomcat.start(); - SSLHostConfig sslHostConfig = connector.getProtocolHandler() - .findSslHostConfigs()[0]; + SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; SSLHostConfig sslHostConfigWithDefaults = new SSLHostConfig(); assertThat(sslHostConfig.getTruststoreFile()) .isEqualTo(SslStoreProviderUrlStreamHandlerFactory.TRUST_STORE_URL); @@ -173,8 +161,7 @@ public class SslConnectorCustomizerTests { } @Test - public void customizeWhenSslStoreProviderPresentShouldIgnorePasswordFromSsl() - throws Exception { + public void customizeWhenSslStoreProviderPresentShouldIgnorePasswordFromSsl() throws Exception { System.setProperty("javax.net.ssl.trustStorePassword", "trustStoreSecret"); Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); @@ -182,8 +169,7 @@ public class SslConnectorCustomizerTests { SslStoreProvider sslStoreProvider = mock(SslStoreProvider.class); given(sslStoreProvider.getTrustStore()).willReturn(loadStore()); given(sslStoreProvider.getKeyStore()).willReturn(loadStore()); - SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, - sslStoreProvider); + SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, sslStoreProvider); Connector connector = this.tomcat.getConnector(); customizer.customize(connector); this.tomcat.start(); @@ -194,13 +180,11 @@ public class SslConnectorCustomizerTests { @Test public void customizeWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { assertThatExceptionOfType(WebServerException.class) - .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null) - .customize(this.tomcat.getConnector())) + .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null).customize(this.tomcat.getConnector())) .withMessageContaining("Could not load key store 'null'"); } - private KeyStore loadStore() throws KeyStoreException, IOException, - NoSuchAlgorithmException, CertificateException { + private KeyStore loadStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); Resource resource = new ClassPathResource("test.jks"); try (InputStream inputStream = resource.getInputStream()) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java index 24a0df889d5..af493468398 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,9 +51,8 @@ public class TomcatEmbeddedWebappClassLoaderTests { @Test public void getResourceFindsResourceFromParentClassLoader() throws Exception { File war = createWar(); - withWebappClassLoader(war, - (classLoader) -> assertThat(classLoader.getResource("test.txt")) - .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); + withWebappClassLoader(war, (classLoader) -> assertThat(classLoader.getResource("test.txt")) + .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); } @Test @@ -61,25 +60,19 @@ public class TomcatEmbeddedWebappClassLoaderTests { File warFile = createWar(); withWebappClassLoader(warFile, (classLoader) -> { List urls = new ArrayList<>(); - CollectionUtils.toIterator(classLoader.getResources("test.txt")) - .forEachRemaining(urls::add); - assertThat(urls).containsExactly( - new URL(webInfClassesUrlString(warFile) + "test.txt")); + CollectionUtils.toIterator(classLoader.getResources("test.txt")).forEachRemaining(urls::add); + assertThat(urls).containsExactly(new URL(webInfClassesUrlString(warFile) + "test.txt")); }); } - private void withWebappClassLoader(File war, ClassLoaderConsumer consumer) - throws Exception { - URLClassLoader parent = new URLClassLoader( - new URL[] { new URL(webInfClassesUrlString(war)) }, null); - try (ParallelWebappClassLoader classLoader = new TomcatEmbeddedWebappClassLoader( - parent)) { + private void withWebappClassLoader(File war, ClassLoaderConsumer consumer) throws Exception { + URLClassLoader parent = new URLClassLoader(new URL[] { new URL(webInfClassesUrlString(war)) }, null); + try (ParallelWebappClassLoader classLoader = new TomcatEmbeddedWebappClassLoader(parent)) { StandardContext context = new StandardContext(); context.setName("test"); StandardRoot resources = new StandardRoot(); resources.setContext(context); - resources.addJarResources( - new WarResourceSet(resources, "/", war.getAbsolutePath())); + resources.addJarResources(new WarResourceSet(resources, "/", war.getAbsolutePath())); resources.start(); classLoader.setResources(resources); classLoader.start(); @@ -93,10 +86,8 @@ public class TomcatEmbeddedWebappClassLoaderTests { private File createWar() throws IOException { File warFile = this.temp.newFile("test.war"); - try (JarOutputStream warOut = new JarOutputStream( - new FileOutputStream(warFile))) { - createEntries(warOut, "WEB-INF/", "WEB-INF/classes/", - "WEB-INF/classes/test.txt"); + try (JarOutputStream warOut = new JarOutputStream(new FileOutputStream(warFile))) { + createEntries(warOut, "WEB-INF/", "WEB-INF/classes/", "WEB-INF/classes/test.txt"); } return warFile; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java index eaba76e4494..1f3ad0006fe 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java @@ -48,8 +48,7 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Madhura Bhave */ -public class TomcatReactiveWebServerFactoryTests - extends AbstractReactiveWebServerFactoryTests { +public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Override protected TomcatReactiveWebServerFactory getFactory() { @@ -61,8 +60,7 @@ public class TomcatReactiveWebServerFactoryTests TomcatReactiveWebServerFactory factory = getFactory(); TomcatContextCustomizer[] customizers = new TomcatContextCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatContextCustomizer.class)); - factory.setTomcatContextCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setTomcatContextCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addContextCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(mock(HttpHandler.class)); InOrder ordered = inOrder((Object[]) customizers); @@ -111,35 +109,31 @@ public class TomcatReactiveWebServerFactoryTests @Test public void setNullConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test public void addNullAddConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy( - () -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void setNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) - .withMessageContaining( - "TomcatProtocolHandlerCustomizers must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test public void addNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy(() -> factory - .addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) - .withMessageContaining( - "TomcatProtocolHandlerCustomizers must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test @@ -148,8 +142,7 @@ public class TomcatReactiveWebServerFactoryTests HttpHandler handler = mock(HttpHandler.class); TomcatConnectorCustomizer[] customizers = new TomcatConnectorCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatConnectorCustomizer.class)); - factory.setTomcatConnectorCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setTomcatConnectorCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addConnectorCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(handler); InOrder ordered = inOrder((Object[]) customizers); @@ -165,8 +158,7 @@ public class TomcatReactiveWebServerFactoryTests HttpHandler handler = mock(HttpHandler.class); TomcatProtocolHandlerCustomizer>[] customizers = new TomcatProtocolHandlerCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatProtocolHandlerCustomizer.class)); - factory.setTomcatProtocolHandlerCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setTomcatProtocolHandlerCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addProtocolHandlerCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(handler); InOrder ordered = inOrder((Object[]) customizers); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java index aa58b0b22d2..c064b8e244f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java @@ -97,8 +97,7 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Stephane Nicoll */ -public class TomcatServletWebServerFactoryTests - extends AbstractServletWebServerFactoryTests { +public class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { @Rule public OutputCapture outputCapture = new OutputCapture(); @@ -110,8 +109,7 @@ public class TomcatServletWebServerFactoryTests @After public void restoreTccl() { - ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", - null); + ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } @@ -124,11 +122,9 @@ public class TomcatServletWebServerFactoryTests factory.setPort(0); TomcatWebServer tomcatWebServer = (TomcatWebServer) factory.getWebServer(); // Make sure that the names are different - String firstName = ((TomcatWebServer) this.webServer).getTomcat().getEngine() - .getName(); + String firstName = ((TomcatWebServer) this.webServer).getTomcat().getEngine().getName(); String secondName = tomcatWebServer.getTomcat().getEngine().getName(); - assertThat(firstName).as("Tomcat engines must have different names") - .isNotEqualTo(secondName); + assertThat(firstName).as("Tomcat engines must have different names").isNotEqualTo(secondName); tomcatWebServer.stop(); } @@ -163,8 +159,7 @@ public class TomcatServletWebServerFactoryTests TomcatServletWebServerFactory factory = getFactory(); TomcatContextCustomizer[] customizers = new TomcatContextCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatContextCustomizer.class)); - factory.setTomcatContextCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setTomcatContextCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addContextCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(); InOrder ordered = inOrder((Object[]) customizers); @@ -189,8 +184,7 @@ public class TomcatServletWebServerFactoryTests TomcatServletWebServerFactory factory = getFactory(); TomcatConnectorCustomizer[] customizers = new TomcatConnectorCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatConnectorCustomizer.class)); - factory.setTomcatConnectorCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setTomcatConnectorCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addConnectorCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(); InOrder ordered = inOrder((Object[]) customizers); @@ -205,8 +199,7 @@ public class TomcatServletWebServerFactoryTests TomcatServletWebServerFactory factory = getFactory(); TomcatProtocolHandlerCustomizer>[] customizers = new TomcatProtocolHandlerCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatProtocolHandlerCustomizer.class)); - factory.setTomcatProtocolHandlerCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setTomcatProtocolHandlerCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addProtocolHandlerCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(); InOrder ordered = inOrder((Object[]) customizers); @@ -218,14 +211,12 @@ public class TomcatServletWebServerFactoryTests @Test public void tomcatProtocolHandlerCanBeCustomized() { TomcatServletWebServerFactory factory = getFactory(); - TomcatProtocolHandlerCustomizer> customizer = ( - protocolHandler) -> protocolHandler.setProcessorCache(250); + TomcatProtocolHandlerCustomizer> customizer = (protocolHandler) -> protocolHandler + .setProcessorCache(250); factory.addProtocolHandlerCustomizers(customizer); Tomcat tomcat = getTomcat(factory); - Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors() - .get(tomcat.getService())[0]; - AbstractHttp11Protocol protocolHandler = (AbstractHttp11Protocol) connector - .getProtocolHandler(); + Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0]; + AbstractHttp11Protocol protocolHandler = (AbstractHttp11Protocol) connector.getProtocolHandler(); assertThat(protocolHandler.getProcessorCache()).isEqualTo(250); } @@ -236,18 +227,14 @@ public class TomcatServletWebServerFactoryTests Arrays.setAll(connectors, (i) -> new Connector()); factory.addAdditionalTomcatConnectors(connectors); this.webServer = factory.getWebServer(); - Map connectorsByService = ((TomcatWebServer) this.webServer) - .getServiceConnectors(); - assertThat(connectorsByService.values().iterator().next().length) - .isEqualTo(connectors.length + 1); + Map connectorsByService = ((TomcatWebServer) this.webServer).getServiceConnectors(); + assertThat(connectorsByService.values().iterator().next().length).isEqualTo(connectors.length + 1); } @Test public void addNullAdditionalConnectorThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy( - () -> factory.addAdditionalTomcatConnectors((Connector[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.addAdditionalTomcatConnectors((Connector[]) null)) .withMessageContaining("Connectors must not be null"); } @@ -284,51 +271,46 @@ public class TomcatServletWebServerFactoryTests @Test public void setNullTomcatContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setTomcatContextCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatContextCustomizers(null)) .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test public void addNullContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy( - () -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test public void setNullTomcatConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test public void addNullConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy( - () -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test public void setNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) - .withMessageContaining( - "TomcatProtocolHandlerCustomizers must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test public void addNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy(() -> factory - .addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) - .withMessageContaining( - "TomcatProtocolHandlerCustomizers must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test @@ -336,8 +318,7 @@ public class TomcatServletWebServerFactoryTests TomcatServletWebServerFactory factory = getFactory(); factory.setUriEncoding(StandardCharsets.US_ASCII); Tomcat tomcat = getTomcat(factory); - Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors() - .get(tomcat.getService())[0]; + Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0]; assertThat(connector.getURIEncoding()).isEqualTo("US-ASCII"); } @@ -345,8 +326,7 @@ public class TomcatServletWebServerFactoryTests public void defaultUriEncoding() { TomcatServletWebServerFactory factory = getFactory(); Tomcat tomcat = getTomcat(factory); - Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors() - .get(tomcat.getService())[0]; + Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0]; assertThat(connector.getURIEncoding()).isEqualTo("UTF-8"); } @@ -363,12 +343,10 @@ public class TomcatServletWebServerFactoryTests } @Test - public void startupFailureDoesNotResultInUnstoppedThreadsBeingReported() - throws IOException { + public void startupFailureDoesNotResultInUnstoppedThreadsBeingReported() throws IOException { super.portClashOfPrimaryConnectorResultsInPortInUseException(); String string = this.outputCapture.toString(); - assertThat(string) - .doesNotContain("appears to have started a thread named [main]"); + assertThat(string).doesNotContain("appears to have started a thread named [main]"); } @Test @@ -384,8 +362,7 @@ public class TomcatServletWebServerFactoryTests protected void addConnector(int port, AbstractServletWebServerFactory factory) { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setPort(port); - ((TomcatServletWebServerFactory) factory) - .addAdditionalTomcatConnectors(connector); + ((TomcatServletWebServerFactory) factory).addAdditionalTomcatConnectors(connector); } @Test @@ -416,8 +393,7 @@ public class TomcatServletWebServerFactoryTests } @Test - public void jndiLookupsCanBePerformedDuringApplicationContextRefresh() - throws NamingException { + public void jndiLookupsCanBePerformedDuringApplicationContextRefresh() throws NamingException { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0) { @@ -436,8 +412,7 @@ public class TomcatServletWebServerFactoryTests // and avoid a leak this.webServer.start(); // Lookups should no longer be possible - assertThatExceptionOfType(NamingException.class) - .isThrownBy(() -> new InitialContext().lookup("java:comp/env")); + assertThatExceptionOfType(NamingException.class).isThrownBy(() -> new InitialContext().lookup("java:comp/env")); } @Test @@ -462,8 +437,7 @@ public class TomcatServletWebServerFactoryTests } Tomcat tomcat = ((TomcatWebServer) this.webServer).getTomcat(); Context context = (Context) tomcat.getHost().findChildren()[0]; - SessionIdGenerator sessionIdGenerator = context.getManager() - .getSessionIdGenerator(); + SessionIdGenerator sessionIdGenerator = context.getManager().getSessionIdGenerator(); assertThat(sessionIdGenerator).isInstanceOf(LazySessionIdGenerator.class); assertThat(sessionIdGenerator.getJvmRoute()).isEqualTo("test"); } @@ -501,10 +475,9 @@ public class TomcatServletWebServerFactoryTests ((StandardContext) context).setFailCtxIfServletStartFails(true); } }); - this.webServer = factory.getWebServer((context) -> context - .addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); - assertThatExceptionOfType(WebServerException.class) - .isThrownBy(this.webServer::start); + this.webServer = factory + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + assertThatExceptionOfType(WebServerException.class).isThrownBy(this.webServer::start); } @Test @@ -515,8 +488,8 @@ public class TomcatServletWebServerFactoryTests ((StandardContext) context).setFailCtxIfServletStartFails(false); } }); - this.webServer = factory.getWebServer((context) -> context - .addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + this.webServer = factory + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); this.webServer.start(); } @@ -533,8 +506,7 @@ public class TomcatServletWebServerFactoryTests } @Test - public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() - throws IOException, URISyntaxException { + public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0); AtomicReference servletContextReference = new AtomicReference<>(); factory.addInitializers((servletContext) -> { @@ -553,18 +525,16 @@ public class TomcatServletWebServerFactoryTests }); this.webServer = factory.getWebServer(); this.webServer.start(); - File temp = (File) servletContextReference.get() - .getAttribute(ServletContext.TEMPDIR); + File temp = (File) servletContextReference.get().getAttribute(ServletContext.TEMPDIR); FileSystemUtils.deleteRecursively(temp); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MultiValueMap body = new LinkedMultiValueMap<>(); body.add("file", new ByteArrayResource(new byte[1024 * 1024])); headers.setContentType(MediaType.MULTIPART_FORM_DATA); - HttpEntity> requestEntity = new HttpEntity<>(body, - headers); - ResponseEntity response = restTemplate - .postForEntity(getLocalUrl("/upload"), requestEntity, String.class); + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + ResponseEntity response = restTemplate.postForEntity(getLocalUrl("/upload"), requestEntity, + String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -578,15 +548,13 @@ public class TomcatServletWebServerFactoryTests return super.getTomcatWebServer(tomcat); } finally { - assertThat(tomcat.getServer().getState()) - .isEqualTo(LifecycleState.DESTROYED); + assertThat(tomcat.getServer().getState()).isEqualTo(LifecycleState.DESTROYED); } } }; - assertThatExceptionOfType(WebServerException.class) - .isThrownBy(() -> factory.getWebServer((context) -> context - .addListener(new FailingServletContextListener()))); + assertThatExceptionOfType(WebServerException.class).isThrownBy( + () -> factory.getWebServer((context) -> context.addListener(new FailingServletContextListener()))); } @Override @@ -603,8 +571,7 @@ public class TomcatServletWebServerFactoryTests @Override protected Map getActualMimeMappings() { - Context context = (Context) ((TomcatWebServer) this.webServer).getTomcat() - .getHost().findChildren()[0]; + Context context = (Context) ((TomcatWebServer) this.webServer).getTomcat().getHost().findChildren()[0]; Map mimeMappings = new HashMap<>(); for (String extension : context.findMimeMappings()) { mimeMappings.put(extension, context.findMimeMapping(extension)); @@ -614,8 +581,7 @@ public class TomcatServletWebServerFactoryTests @Override protected Charset getCharset(Locale locale) { - Context context = (Context) ((TomcatWebServer) this.webServer).getTomcat() - .getHost().findChildren()[0]; + Context context = (Context) ((TomcatWebServer) this.webServer).getTomcat().getHost().findChildren()[0]; CharsetMapper mapper = ((TomcatEmbeddedContext) context).getCharsetMapper(); String charsetName = mapper.getCharset(locale); return (charsetName != null) ? Charset.forName(charsetName) : null; @@ -633,8 +599,7 @@ public class TomcatServletWebServerFactoryTests } @Override - protected void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort) { + protected void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort) { assertThat(ex).isInstanceOf(ConnectorStartFailedException.class); assertThat(((ConnectorStartFailedException) ex).getPort()).isEqualTo(blockedPort); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java index e3d5d73af79..71e8ef55714 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ public class FileSessionPersistenceTests { @Test public void loadsNullForMissingFile() { - Map attributes = this.persistence - .loadSessionAttributes("test", this.classLoader); + Map attributes = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(attributes).isNull(); } @@ -69,8 +68,7 @@ public class FileSessionPersistenceTests { PersistentSession session = new PersistentSession(this.expiration, data); sessionData.put("abc", session); this.persistence.persistSessions("test", sessionData); - Map restored = this.persistence - .loadSessionAttributes("test", this.classLoader); + Map restored = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(restored).isNotNull(); assertThat(restored.get("abc").getExpiration()).isEqualTo(this.expiration); assertThat(restored.get("abc").getSessionData().get("spring")).isEqualTo("boot"); @@ -85,8 +83,7 @@ public class FileSessionPersistenceTests { PersistentSession session = new PersistentSession(expired, data); sessionData.put("abc", session); this.persistence.persistSessions("test", sessionData); - Map restored = this.persistence - .loadSessionAttributes("test", this.classLoader); + Map restored = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(restored).isNotNull(); assertThat(restored.containsKey("abc")).isFalse(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java index c6b578ca210..77e9bab1373 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java @@ -43,12 +43,10 @@ public class SslBuilderCustomizerTests { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); - SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, - InetAddress.getLocalHost(), ssl, null); - KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(customizer, - "getKeyManagers", ssl, null); - Class name = Class.forName("org.springframework.boot.web.embedded.undertow" - + ".SslBuilderCustomizer$ConfigurableAliasKeyManager"); + SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); + KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); + Class name = Class.forName( + "org.springframework.boot.web.embedded.undertow" + ".SslBuilderCustomizer$ConfigurableAliasKeyManager"); assertThat(keyManagers[0]).isNotInstanceOf(name); } @@ -58,11 +56,9 @@ public class SslBuilderCustomizerTests { ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); - SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, - InetAddress.getLocalHost(), ssl, null); + SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, - "getKeyManagers", ssl, null)) + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) .withCauseInstanceOf(NoSuchProviderException.class) .withMessageContaining("com.example.KeyStoreProvider"); } @@ -73,26 +69,20 @@ public class SslBuilderCustomizerTests { ssl.setTrustStorePassword("password"); ssl.setTrustStore("src/test/resources/test.jks"); ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); - SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, - InetAddress.getLocalHost(), ssl, null); + SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, - "getTrustManagers", ssl, null)) + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null)) .withCauseInstanceOf(NoSuchProviderException.class) .withMessageContaining("com.example.TrustStoreProvider"); } @Test - public void getKeyManagersWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() - throws Exception { + public void getKeyManagersWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() throws Exception { Ssl ssl = new Ssl(); - SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, - InetAddress.getLocalHost(), ssl, null); + SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, - "getKeyManagers", ssl, null)) - .withCauseInstanceOf(WebServerException.class) - .withMessageContaining("Could not load key store 'null'"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(WebServerException.class).withMessageContaining("Could not load key store 'null'"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java index ca7bc6d161e..29893894340 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Madhura Bhave */ -public class UndertowReactiveWebServerFactoryTests - extends AbstractReactiveWebServerFactoryTests { +public class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -61,16 +60,15 @@ public class UndertowReactiveWebServerFactoryTests @Test public void setNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setBuilderCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test public void addNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy( - () -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @@ -97,14 +95,12 @@ public class UndertowReactiveWebServerFactoryTests } @Test - public void accessLogCanBeEnabled() - throws IOException, URISyntaxException, InterruptedException { + public void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { testAccessLog(null, null, "access_log.log"); } @Test - public void accessLogCanBeCustomized() - throws IOException, URISyntaxException, InterruptedException { + public void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { testAccessLog("my_access.", "logz", "my_access.logz"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java index f26868fa38d..951db0f1078 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java @@ -63,8 +63,7 @@ import static org.mockito.Mockito.mock; * @author Ivan Sopov * @author Andy Wilkinson */ -public class UndertowServletWebServerFactoryTests - extends AbstractServletWebServerFactoryTests { +public class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { @Override protected UndertowServletWebServerFactory getFactory() { @@ -75,8 +74,7 @@ public class UndertowServletWebServerFactoryTests public void errorPage404() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/hello")); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); this.webServer.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); assertThat(getResponse(getLocalUrl("/not-found"))).isEqualTo("Hello World"); @@ -85,16 +83,15 @@ public class UndertowServletWebServerFactoryTests @Test public void setNullBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setBuilderCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test public void addNullAddBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException().isThrownBy( - () -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @@ -115,8 +112,7 @@ public class UndertowServletWebServerFactoryTests @Test public void setNullDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - assertThatIllegalArgumentException() - .isThrownBy(() -> factory.setDeploymentInfoCustomizers(null)) + assertThatIllegalArgumentException().isThrownBy(() -> factory.setDeploymentInfoCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @@ -124,8 +120,7 @@ public class UndertowServletWebServerFactoryTests public void addNullAddDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addDeploymentInfoCustomizers( - (UndertowDeploymentInfoCustomizer[]) null)) + .isThrownBy(() -> factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @@ -134,8 +129,7 @@ public class UndertowServletWebServerFactoryTests UndertowServletWebServerFactory factory = getFactory(); UndertowDeploymentInfoCustomizer[] customizers = new UndertowDeploymentInfoCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(UndertowDeploymentInfoCustomizer.class)); - factory.setDeploymentInfoCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setDeploymentInfoCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addDeploymentInfoCustomizers(customizers[2], customizers[3]); this.webServer = factory.getWebServer(); InOrder ordered = inOrder((Object[]) customizers); @@ -153,8 +147,7 @@ public class UndertowServletWebServerFactoryTests public void defaultContextPath() { UndertowServletWebServerFactory factory = getFactory(); final AtomicReference contextPath = new AtomicReference<>(); - factory.addDeploymentInfoCustomizers( - (deploymentInfo) -> contextPath.set(deploymentInfo.getContextPath())); + factory.addDeploymentInfoCustomizers((deploymentInfo) -> contextPath.set(deploymentInfo.getContextPath())); this.webServer = factory.getWebServer(); assertThat(contextPath.get()).isEqualTo("/"); } @@ -168,19 +161,16 @@ public class UndertowServletWebServerFactoryTests @Test public void eachFactoryUsesADiscreteServletContainer() { - assertThat(getServletContainerFromNewFactory()) - .isNotEqualTo(getServletContainerFromNewFactory()); + assertThat(getServletContainerFromNewFactory()).isNotEqualTo(getServletContainerFromNewFactory()); } @Test - public void accessLogCanBeEnabled() - throws IOException, URISyntaxException, InterruptedException { + public void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { testAccessLog(null, null, "access_log.log"); } @Test - public void accessLogCanBeCustomized() - throws IOException, URISyntaxException, InterruptedException { + public void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { testAccessLog("my_access.", "logz", "my_access.logz"); } @@ -193,8 +183,7 @@ public class UndertowServletWebServerFactoryTests File accessLogDirectory = this.temporaryFolder.getRoot(); factory.setAccessLogDirectory(accessLogDirectory); assertThat(accessLogDirectory.listFiles()).isEmpty(); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); this.webServer.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); File accessLog = new File(accessLogDirectory, expectedFile); @@ -204,25 +193,22 @@ public class UndertowServletWebServerFactoryTests @Override protected void addConnector(int port, AbstractServletWebServerFactory factory) { - ((UndertowServletWebServerFactory) factory).addBuilderCustomizers( - (builder) -> builder.addHttpListener(port, "0.0.0.0")); + ((UndertowServletWebServerFactory) factory) + .addBuilderCustomizers((builder) -> builder.addHttpListener(port, "0.0.0.0")); } @Test public void sslRestrictedProtocolsEmptyCipherFailure() throws Exception { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites( - new String[] { "TLSv1.2" }, + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) - .isInstanceOfAny(SSLException.class, SSLHandshakeException.class, - SocketException.class); + .isInstanceOfAny(SSLException.class, SSLHandshakeException.class, SocketException.class); } @Test public void sslRestrictedProtocolsECDHETLS1Failure() throws Exception { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites( - new String[] { "TLSv1" }, + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) .isInstanceOfAny(SSLException.class, SocketException.class); } @@ -242,8 +228,7 @@ public class UndertowServletWebServerFactoryTests @Test public void sslRestrictedProtocolsRSATLS11Failure() throws Exception { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites( - new String[] { "TLSv1.1" }, + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) .isInstanceOfAny(SSLException.class, SocketException.class); } @@ -261,8 +246,7 @@ public class UndertowServletWebServerFactoryTests } private ServletContainer getServletContainerFromNewFactory() { - UndertowServletWebServer container = (UndertowServletWebServer) getFactory() - .getWebServer(); + UndertowServletWebServer container = (UndertowServletWebServer) getFactory().getWebServer(); try { return container.getDeploymentManager().getDeployment().getServletContainer(); } @@ -273,8 +257,8 @@ public class UndertowServletWebServerFactoryTests @Override protected Map getActualMimeMappings() { - return ((UndertowServletWebServer) this.webServer).getDeploymentManager() - .getDeployment().getMimeExtensionMappings(); + return ((UndertowServletWebServer) this.webServer).getDeploymentManager().getDeployment() + .getMimeExtensionMappings(); } @Override @@ -288,19 +272,17 @@ public class UndertowServletWebServerFactoryTests @Override protected Charset getCharset(Locale locale) { - DeploymentInfo info = ((UndertowServletWebServer) this.webServer) - .getDeploymentManager().getDeployment().getDeploymentInfo(); + DeploymentInfo info = ((UndertowServletWebServer) this.webServer).getDeploymentManager().getDeployment() + .getDeploymentInfo(); String charsetName = info.getLocaleCharsetMapping().get(locale.toString()); return (charsetName != null) ? Charset.forName(charsetName) : null; } @Override - protected void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort) { + protected void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort) { assertThat(ex).isInstanceOf(PortInUseException.class); assertThat(((PortInUseException) ex).getPort()).isEqualTo(blockedPort); - Undertow undertow = (Undertow) ReflectionTestUtils.getField(this.webServer, - "undertow"); + Undertow undertow = (Undertow) ReflectionTestUtils.getField(this.webServer, "undertow"); assertThat(undertow.getWorker()).isNull(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java index 0078f7f589f..f60c12f71dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java @@ -45,8 +45,7 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { @Test public void createFromScan() { this.context = new AnnotationConfigReactiveWebServerApplicationContext( - ExampleReactiveWebServerApplicationConfiguration.class.getPackage() - .getName()); + ExampleReactiveWebServerApplicationConfiguration.class.getPackage().getName()); verifyContext(); } @@ -72,15 +71,13 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { this.context.register(HttpHandlerConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(WebServerConfiguration.class)).hasSize(1); - assertThat(this.context.getBeansOfType(HttpHandlerConfiguration.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(HttpHandlerConfiguration.class)).hasSize(1); } @Test public void scanAndRefresh() { this.context = new AnnotationConfigReactiveWebServerApplicationContext(); - this.context.scan(ExampleReactiveWebServerApplicationConfiguration.class - .getPackage().getName()); + this.context.scan(ExampleReactiveWebServerApplicationConfiguration.class.getPackage().getName()); this.context.refresh(); verifyContext(); } @@ -88,14 +85,12 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { @Test public void httpHandlerInitialization() { // gh-14666 - this.context = new AnnotationConfigReactiveWebServerApplicationContext( - InitializationTestConfig.class); + this.context = new AnnotationConfigReactiveWebServerApplicationContext(InitializationTestConfig.class); verifyContext(); } private void verifyContext() { - MockReactiveWebServerFactory factory = this.context - .getBean(MockReactiveWebServerFactory.class); + MockReactiveWebServerFactory factory = this.context.getBean(MockReactiveWebServerFactory.class); HttpHandler expectedHandler = this.context.getBean(HttpHandler.class); HttpHandler actualHandler = factory.getWebServer().getHttpHandler(); if (actualHandler instanceof ServerManager) { @@ -163,8 +158,7 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { }; } - private static class Listener - implements ApplicationListener { + private static class Listener implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent event) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java index 400fdc02ac3..c97bc87caf7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ public class GenericReactiveWebApplicationContextTests { GenericReactiveWebApplicationContext context = new GenericReactiveWebApplicationContext(); Resource rootResource = context.getResourceByPath("/"); assertThat(rootResource.exists()).isFalse(); - assertThat(rootResource.createRelative("application.properties").exists()) - .isFalse(); + assertThat(rootResource.createRelative("application.properties").exists()).isFalse(); context.close(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java index ebd8180686a..50d89bebf96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java @@ -50,30 +50,25 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; */ public class DefaultErrorAttributesTests { - private static final ResponseStatusException NOT_FOUND = new ResponseStatusException( - HttpStatus.NOT_FOUND); + private static final ResponseStatusException NOT_FOUND = new ResponseStatusException(HttpStatus.NOT_FOUND); private DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes(); - private List> readers = ServerCodecConfigurer.create() - .getReaders(); + private List> readers = ServerCodecConfigurer.create().getReaders(); @Test public void missingExceptionAttribute() { - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/test").build()); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); ServerRequest request = ServerRequest.create(exchange, this.readers); - assertThatIllegalStateException() - .isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, false)) - .withMessageContaining( - "Missing exception attribute in ServerWebExchange"); + assertThatIllegalStateException().isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, false)) + .withMessageContaining("Missing exception attribute in ServerWebExchange"); } @Test public void includeTimeStamp() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, NOT_FOUND), false); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, NOT_FOUND), + false); assertThat(attributes.get("timestamp")).isInstanceOf(Date.class); } @@ -81,10 +76,9 @@ public class DefaultErrorAttributesTests { public void defaultStatusCode() { Error error = new OutOfMemoryError("Test error"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, error), false); - assertThat(attributes.get("error")) - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, error), + false); + assertThat(attributes.get("error")).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); assertThat(attributes.get("status")).isEqualTo(500); } @@ -92,10 +86,9 @@ public class DefaultErrorAttributesTests { public void annotatedResponseStatusCode() { Exception error = new CustomException(); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, error), false); - assertThat(attributes.get("error")) - .isEqualTo(HttpStatus.I_AM_A_TEAPOT.getReasonPhrase()); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, error), + false); + assertThat(attributes.get("error")).isEqualTo(HttpStatus.I_AM_A_TEAPOT.getReasonPhrase()); assertThat(attributes.get("status")).isEqualTo(HttpStatus.I_AM_A_TEAPOT.value()); } @@ -103,10 +96,9 @@ public class DefaultErrorAttributesTests { public void annotatedResponseStatusCodeWithCustomReasonPhrase() { Exception error = new Custom2Exception(); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, error), false); - assertThat(attributes.get("error")) - .isEqualTo(HttpStatus.I_AM_A_TEAPOT.getReasonPhrase()); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, error), + false); + assertThat(attributes.get("error")).isEqualTo(HttpStatus.I_AM_A_TEAPOT.getReasonPhrase()); assertThat(attributes.get("status")).isEqualTo(HttpStatus.I_AM_A_TEAPOT.value()); assertThat(attributes.get("message")).isEqualTo("Nope!"); } @@ -114,10 +106,9 @@ public class DefaultErrorAttributesTests { @Test public void includeStatusCode() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, NOT_FOUND), false); - assertThat(attributes.get("error")) - .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, NOT_FOUND), + false); + assertThat(attributes.get("error")).isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); assertThat(attributes.get("status")).isEqualTo(404); } @@ -126,8 +117,7 @@ public class DefaultErrorAttributesTests { Error error = new OutOfMemoryError("Test error"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, error); - Map attributes = this.errorAttributes - .getErrorAttributes(serverRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(serverRequest, false); assertThat(this.errorAttributes.getError(serverRequest)).isSameAs(error); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test error"); @@ -139,44 +129,37 @@ public class DefaultErrorAttributesTests { this.errorAttributes = new DefaultErrorAttributes(true); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, error); - Map attributes = this.errorAttributes - .getErrorAttributes(serverRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(serverRequest, false); assertThat(this.errorAttributes.getError(serverRequest)).isSameAs(error); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test"); } @Test public void processResponseStatusException() { RuntimeException nested = new RuntimeException("Test"); - ResponseStatusException error = new ResponseStatusException( - HttpStatus.BAD_REQUEST, "invalid request", nested); + ResponseStatusException error = new ResponseStatusException(HttpStatus.BAD_REQUEST, "invalid request", nested); this.errorAttributes = new DefaultErrorAttributes(true); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, error); - Map attributes = this.errorAttributes - .getErrorAttributes(serverRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(serverRequest, false); assertThat(attributes.get("status")).isEqualTo(400); assertThat(attributes.get("message")).isEqualTo("invalid request"); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(this.errorAttributes.getError(serverRequest)).isSameAs(error); } @Test public void processResponseStatusExceptionWithNoNestedCause() { - ResponseStatusException error = new ResponseStatusException( - HttpStatus.NOT_ACCEPTABLE, "could not process request"); + ResponseStatusException error = new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE, + "could not process request"); this.errorAttributes = new DefaultErrorAttributes(true); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, error); - Map attributes = this.errorAttributes - .getErrorAttributes(serverRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(serverRequest, false); assertThat(attributes.get("status")).isEqualTo(406); assertThat(attributes.get("message")).isEqualTo("could not process request"); - assertThat(attributes.get("exception")) - .isEqualTo(ResponseStatusException.class.getName()); + assertThat(attributes.get("exception")).isEqualTo(ResponseStatusException.class.getName()); assertThat(this.errorAttributes.getError(serverRequest)).isSameAs(error); } @@ -184,8 +167,8 @@ public class DefaultErrorAttributesTests { public void notIncludeTrace() { RuntimeException ex = new RuntimeException("Test"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, ex), false); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), + false); assertThat(attributes.get("trace")).isNull(); } @@ -193,16 +176,15 @@ public class DefaultErrorAttributesTests { public void includeTrace() { RuntimeException ex = new RuntimeException("Test"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, ex), true); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), true); assertThat(attributes.get("trace").toString()).startsWith("java.lang"); } @Test public void includePath() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, NOT_FOUND), false); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, NOT_FOUND), + false); assertThat(attributes.get("path")).isEqualTo("/test"); } @@ -210,23 +192,20 @@ public class DefaultErrorAttributesTests { public void includeLogPrefix() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, NOT_FOUND); - Map attributes = this.errorAttributes - .getErrorAttributes(serverRequest, false); - assertThat(attributes.get("requestId")) - .isEqualTo(serverRequest.exchange().getRequest().getId()); + Map attributes = this.errorAttributes.getErrorAttributes(serverRequest, false); + assertThat(attributes.get("requestId")).isEqualTo(serverRequest.exchange().getRequest().getId()); } @Test public void extractBindingResultErrors() throws Exception { Method method = getClass().getMethod("method", String.class); MethodParameter stringParam = new MethodParameter(method, 0); - BindingResult bindingResult = new MapBindingResult( - Collections.singletonMap("a", "b"), "objectName"); + BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new WebExchangeBindException(stringParam, bindingResult); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); - Map attributes = this.errorAttributes - .getErrorAttributes(buildServerRequest(request, ex), false); + Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), + false); assertThat(attributes.get("message")).asString() .startsWith("Validation failed for argument at index 0 in method: " + "public int org.springframework.boot.web.reactive.error.DefaultErrorAttributesTests" @@ -234,8 +213,7 @@ public class DefaultErrorAttributesTests { assertThat(attributes.get("errors")).isEqualTo(bindingResult.getAllErrors()); } - private ServerRequest buildServerRequest(MockServerHttpRequest request, - Throwable error) { + private ServerRequest buildServerRequest(MockServerHttpRequest request, Throwable error) { ServerWebExchange exchange = MockServerWebExchange.from(request); this.errorAttributes.storeErrorInformation(error, exchange); return ServerRequest.create(exchange, this.readers); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java index d709dfdffcb..6934c0e13f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MustacheViewResolverTests { - private final String prefix = "classpath:/" - + getClass().getPackage().getName().replace(".", "/") + "/"; + private final String prefix = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + "/"; private MustacheViewResolver resolver = new MustacheViewResolver(); @@ -48,15 +47,12 @@ public class MustacheViewResolverTests { @Test public void resolveNonExistent() { - assertThat( - this.resolver.resolveViewName("bar", null).block(Duration.ofSeconds(30))) - .isNull(); + assertThat(this.resolver.resolveViewName("bar", null).block(Duration.ofSeconds(30))).isNull(); } @Test public void resolveExisting() { - assertThat(this.resolver.resolveViewName("template", null) - .block(Duration.ofSeconds(30))).isNotNull(); + assertThat(this.resolver.resolveViewName("template", null).block(Duration.ofSeconds(30))).isNotNull(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java index 1a4512c8bda..34d6c771afc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MustacheViewTests { - private final String templateUrl = "classpath:/" - + getClass().getPackage().getName().replace(".", "/") + "/template.html"; + private final String templateUrl = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + + "/template.html"; private GenericApplicationContext context = new GenericApplicationContext(); @@ -52,17 +52,16 @@ public class MustacheViewTests { @Test public void viewResolvesHandlebars() { - this.exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/test").build()); + this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); MustacheView view = new MustacheView(); view.setCompiler(Mustache.compiler()); view.setUrl(this.templateUrl); view.setCharset(StandardCharsets.UTF_8.displayName()); view.setApplicationContext(this.context); - view.render(Collections.singletonMap("World", "Spring"), MediaType.TEXT_HTML, - this.exchange).block(Duration.ofSeconds(30)); - assertThat(this.exchange.getResponse().getBodyAsString() - .block(Duration.ofSeconds(30)).trim()).isEqualTo("Hello Spring"); + view.render(Collections.singletonMap("World", "Spring"), MediaType.TEXT_HTML, this.exchange) + .block(Duration.ofSeconds(30)); + assertThat(this.exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)).trim()) + .isEqualTo("Hello Spring"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java index 7da6fb735b6..9c6e1702485 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java @@ -101,8 +101,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setPort(specificPort); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - Mono result = getWebClient().build().post().uri("/test") - .contentType(MediaType.TEXT_PLAIN) + Mono result = getWebClient().build().post().uri("/test").contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromObject("Hello World")).exchange() .flatMap((response) -> response.bodyToMono(String.class)); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); @@ -128,8 +127,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder() - .baseUrl("https://localhost:" + this.webServer.getPort()) + WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) .clientConnector(connector).build(); Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromObject("Hello World")).exchange() @@ -138,8 +136,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } protected ReactorClientHttpConnector buildTrustAllSslConnector() { - SslContextBuilder builder = SslContextBuilder.forClient() - .sslProvider(SslProvider.JDK) + SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE); HttpClient client = HttpClient.create().wiretap(true) .secure((sslContextSpec) -> sslContextSpec.sslContext(builder)); @@ -147,8 +144,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void sslWantsClientAuthenticationSucceedsWithClientCertificate() - throws Exception { + public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { Ssl ssl = new Ssl(); ssl.setClientAuth(Ssl.ClientAuth.WANT); ssl.setKeyStore("classpath:test.jks"); @@ -167,11 +163,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { testClientAuthSuccess(ssl, buildTrustAllSslConnector()); } - protected ReactorClientHttpConnector buildTrustAllSslWithClientKeyConnector() - throws Exception { + protected ReactorClientHttpConnector buildTrustAllSslWithClientKeyConnector() throws Exception { KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - clientKeyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); + clientKeyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); KeyManagerFactory clientKeyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); clientKeyManagerFactory.init(clientKeyStore, "password".toCharArray()); @@ -180,14 +174,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { X509KeyManager x509KeyManager = (X509KeyManager) keyManager; PrivateKey privateKey = x509KeyManager.getPrivateKey("spring-boot"); if (privateKey != null) { - X509Certificate[] certificateChain = x509KeyManager - .getCertificateChain("spring-boot"); - SslContextBuilder builder = SslContextBuilder.forClient() - .sslProvider(SslProvider.JDK) + X509Certificate[] certificateChain = x509KeyManager.getCertificateChain("spring-boot"); + SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE) .keyManager(privateKey, certificateChain); - HttpClient client = HttpClient.create().wiretap(true).secure( - (sslContextSpec) -> sslContextSpec.sslContext(builder)); + HttpClient client = HttpClient.create().wiretap(true) + .secure((sslContextSpec) -> sslContextSpec.sslContext(builder)); return new ReactorClientHttpConnector(client); } } @@ -195,14 +187,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { throw new IllegalStateException("Key with alias 'spring-boot' not found"); } - protected void testClientAuthSuccess(Ssl sslConfiguration, - ReactorClientHttpConnector clientConnector) { + protected void testClientAuthSuccess(Ssl sslConfiguration, ReactorClientHttpConnector clientConnector) { AbstractReactiveWebServerFactory factory = getFactory(); factory.setSsl(sslConfiguration); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - WebClient client = WebClient.builder() - .baseUrl("https://localhost:" + this.webServer.getPort()) + WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) .clientConnector(clientConnector).build(); Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromObject("Hello World")).exchange() @@ -211,8 +201,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() - throws Exception { + public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { Ssl ssl = new Ssl(); ssl.setClientAuth(Ssl.ClientAuth.NEED); ssl.setKeyStore("classpath:test.jks"); @@ -231,20 +220,17 @@ public abstract class AbstractReactiveWebServerFactoryTests { testClientAuthFailure(ssl, buildTrustAllSslConnector()); } - protected void testClientAuthFailure(Ssl sslConfiguration, - ReactorClientHttpConnector clientConnector) { + protected void testClientAuthFailure(Ssl sslConfiguration, ReactorClientHttpConnector clientConnector) { AbstractReactiveWebServerFactory factory = getFactory(); factory.setSsl(sslConfiguration); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - WebClient client = WebClient.builder() - .baseUrl("https://localhost:" + this.webServer.getPort()) + WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) .clientConnector(clientConnector).build(); Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromObject("Hello World")).exchange() .flatMap((response) -> response.bodyToMono(String.class)); - StepVerifier.create(result).expectError(SSLException.class) - .verify(Duration.ofSeconds(10)); + StepVerifier.create(result).expectError(SSLException.class).verify(Duration.ofSeconds(10)); } protected WebClient.Builder getWebClient() { @@ -254,23 +240,22 @@ public abstract class AbstractReactiveWebServerFactoryTests { protected WebClient.Builder getWebClient(HttpClient client) { InetSocketAddress address = new InetSocketAddress(this.webServer.getPort()); String baseUrl = "http://" + address.getHostString() + ":" + address.getPort(); - return WebClient.builder().clientConnector(new ReactorClientHttpConnector(client)) - .baseUrl(baseUrl); + return WebClient.builder().clientConnector(new ReactorClientHttpConnector(client)).baseUrl(baseUrl); } @Test public void compressionOfResponseToGetRequest() { WebClient client = prepareCompressionTest(); - ResponseEntity response = client.get().exchange() - .flatMap((res) -> res.toEntity(Void.class)).block(Duration.ofSeconds(30)); + ResponseEntity response = client.get().exchange().flatMap((res) -> res.toEntity(Void.class)) + .block(Duration.ofSeconds(30)); assertResponseIsCompressed(response); } @Test public void compressionOfResponseToPostRequest() { WebClient client = prepareCompressionTest(); - ResponseEntity response = client.post().exchange() - .flatMap((res) -> res.toEntity(Void.class)).block(Duration.ofSeconds(30)); + ResponseEntity response = client.post().exchange().flatMap((res) -> res.toEntity(Void.class)) + .block(Duration.ofSeconds(30)); assertResponseIsCompressed(response); } @@ -280,8 +265,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { compression.setEnabled(true); compression.setMinResponseSize(DataSize.ofBytes(3001)); WebClient client = prepareCompressionTest(compression); - ResponseEntity response = client.get().exchange() - .flatMap((res) -> res.toEntity(Void.class)).block(Duration.ofSeconds(30)); + ResponseEntity response = client.get().exchange().flatMap((res) -> res.toEntity(Void.class)) + .block(Duration.ofSeconds(30)); assertResponseIsNotCompressed(response); } @@ -290,8 +275,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { Compression compression = new Compression(); compression.setMimeTypes(new String[] { "application/json" }); WebClient client = prepareCompressionTest(compression); - ResponseEntity response = client.get().exchange() - .flatMap((res) -> res.toEntity(Void.class)).block(Duration.ofSeconds(30)); + ResponseEntity response = client.get().exchange().flatMap((res) -> res.toEntity(Void.class)) + .block(Duration.ofSeconds(30)); assertResponseIsNotCompressed(response); } @@ -301,9 +286,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { compression.setEnabled(true); compression.setExcludedUserAgents(new String[] { "testUserAgent" }); WebClient client = prepareCompressionTest(compression); - ResponseEntity response = client.get().header("User-Agent", "testUserAgent") - .exchange().flatMap((res) -> res.toEntity(Void.class)) - .block(Duration.ofSeconds(30)); + ResponseEntity response = client.get().header("User-Agent", "testUserAgent").exchange() + .flatMap((res) -> res.toEntity(Void.class)).block(Duration.ofSeconds(30)); assertResponseIsNotCompressed(response); } @@ -323,15 +307,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { protected WebClient prepareCompressionTest(Compression compression) { AbstractReactiveWebServerFactory factory = getFactory(); factory.setCompression(compression); - this.webServer = factory - .getWebServer(new CharsHandler(3000, MediaType.TEXT_PLAIN)); + this.webServer = factory.getWebServer(new CharsHandler(3000, MediaType.TEXT_PLAIN)); this.webServer.start(); HttpClient client = HttpClient.create().wiretap(true).compress(true) .tcpConfiguration((tcpClient) -> tcpClient.doOnConnected( - (connection) -> connection.channel().pipeline().addBefore( - NettyPipeline.HttpDecompressor, "CompressionTest", - new CompressionDetectionHandler()))); + (connection) -> connection.channel().pipeline().addBefore(NettyPipeline.HttpDecompressor, + "CompressionTest", new CompressionDetectionHandler()))); return getWebClient(client).build(); } @@ -346,8 +328,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { protected void assertForwardHeaderIsUsed(AbstractReactiveWebServerFactory factory) { this.webServer = factory.getWebServer(new XForwardedHandler()); this.webServer.start(); - String body = getWebClient().build().get().header("X-Forwarded-Proto", "https") - .retrieve().bodyToMono(String.class).block(Duration.ofSeconds(30)); + String body = getWebClient().build().get().header("X-Forwarded-Proto", "https").retrieve() + .bodyToMono(String.class).block(Duration.ofSeconds(30)); assertThat(body).isEqualTo("https"); } @@ -364,15 +346,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { } - protected static class CompressionDetectionHandler - extends ChannelInboundHandlerAdapter { + protected static class CompressionDetectionHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; - boolean compressed = response.headers() - .contains(HttpHeaderNames.CONTENT_ENCODING, "gzip", true); + boolean compressed = response.headers().contains(HttpHeaderNames.CONTENT_ENCODING, "gzip", true); if (compressed) { response.headers().set("X-Test-Compressed", "true"); } @@ -413,8 +393,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { public Mono handle(ServerHttpRequest request, ServerHttpResponse response) { String scheme = request.getURI().getScheme(); DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); - DataBuffer buffer = bufferFactory - .wrap(scheme.getBytes(StandardCharsets.UTF_8)); + DataBuffer buffer = bufferFactory.wrap(scheme.getBytes(StandardCharsets.UTF_8)); return response.writeWith(Mono.just(buffer)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java index fcbe910ea1d..58ce690450d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ public class CompressionTests { @Test public void defaultCompressableMimeTypesMatchesTomcatsDefault() { - assertThat(new Compression().getMimeTypes()) - .containsExactlyInAnyOrder(getTomcatDefaultCompressableMimeTypes()); + assertThat(new Compression().getMimeTypes()).containsExactlyInAnyOrder(getTomcatDefaultCompressableMimeTypes()); } private String[] getTomcatDefaultCompressableMimeTypes() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index 1bcc47ad830..a1d289d7931 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,10 +55,9 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { @Test public void setBeanFactoryWhenNotListableShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.processor.setBeanFactory(mock(BeanFactory.class))) - .withMessageContaining("WebServerCustomizerBeanPostProcessor can only " - + "be used with a ListableBeanFactory"); + assertThatIllegalArgumentException().isThrownBy(() -> this.processor.setBeanFactory(mock(BeanFactory.class))) + .withMessageContaining( + "WebServerCustomizerBeanPostProcessor can only " + "be used with a ListableBeanFactory"); } @Test @@ -155,8 +154,8 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { @SuppressWarnings({ "unchecked", "rawtypes" }) private void addMockBeans(Map beans) { - given(this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, - false)).willReturn((Map) beans); + given(this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false)) + .willReturn((Map) beans); } private void postProcessBeforeInitialization(Class type) { @@ -191,18 +190,15 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } - private static class WebServerFactoryOneCustomizer - extends MockWebServerFactoryCustomizer { + private static class WebServerFactoryOneCustomizer extends MockWebServerFactoryCustomizer { } - private static class WebServerFactoryTwoCustomizer - extends MockWebServerFactoryCustomizer { + private static class WebServerFactoryTwoCustomizer extends MockWebServerFactoryCustomizer { } - private static class WebServerFactoryAllCustomizer - extends MockWebServerFactoryCustomizer { + private static class WebServerFactoryAllCustomizer extends MockWebServerFactoryCustomizer { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java index 98b87fc1d20..262ee54dab3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java @@ -57,8 +57,7 @@ public abstract class AbstractFilterRegistrationBeanTests { @Before public void setupMocks() { MockitoAnnotations.initMocks(this); - given(this.servletContext.addFilter(anyString(), any(Filter.class))) - .willReturn(this.registration); + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); } @Test @@ -67,8 +66,7 @@ public abstract class AbstractFilterRegistrationBeanTests { bean.onStartup(this.servletContext); verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter()); verify(this.registration).setAsyncSupported(true); - verify(this.registration).addMappingForUrlPatterns( - EnumSet.of(DispatcherType.REQUEST), false, "/*"); + verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); } @Test @@ -82,8 +80,7 @@ public abstract class AbstractFilterRegistrationBeanTests { bean.addUrlPatterns("/c"); bean.setServletNames(new LinkedHashSet<>(Arrays.asList("s1", "s2"))); bean.addServletNames("s3"); - bean.setServletRegistrationBeans( - Collections.singleton(mockServletRegistration("s4"))); + bean.setServletRegistrationBeans(Collections.singleton(mockServletRegistration("s4"))); bean.addServletRegistrationBeans(mockServletRegistration("s5")); bean.setMatchAfter(true); bean.onStartup(this.servletContext); @@ -93,10 +90,9 @@ public abstract class AbstractFilterRegistrationBeanTests { expectedInitParameters.put("a", "b"); expectedInitParameters.put("c", "d"); verify(this.registration).setInitParameters(expectedInitParameters); - verify(this.registration).addMappingForUrlPatterns( - EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", "/c"); - verify(this.registration).addMappingForServletNames( - EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", "s1", "s2", "s3"); + verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", "/c"); + verify(this.registration).addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", "s1", + "s2", "s3"); } @Test @@ -119,35 +115,31 @@ public abstract class AbstractFilterRegistrationBeanTests { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setEnabled(false); bean.onStartup(this.servletContext); - verify(this.servletContext, never()).addFilter(eq("mockFilter"), - getExpectedFilter()); + verify(this.servletContext, never()).addFilter(eq("mockFilter"), getExpectedFilter()); } @Test public void setServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - assertThatIllegalArgumentException() - .isThrownBy(() -> bean.setServletRegistrationBeans(null)) + assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletRegistrationBeans(null)) .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test public void addServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - assertThatIllegalArgumentException().isThrownBy( - () -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test public void setServletRegistrationBeanReplacesValue() throws Exception { - AbstractFilterRegistrationBean bean = createFilterRegistrationBean( - mockServletRegistration("a")); - bean.setServletRegistrationBeans(new LinkedHashSet>( - Collections.singletonList(mockServletRegistration("b")))); + AbstractFilterRegistrationBean bean = createFilterRegistrationBean(mockServletRegistration("a")); + bean.setServletRegistrationBeans( + new LinkedHashSet>(Collections.singletonList(mockServletRegistration("b")))); bean.onStartup(this.servletContext); - verify(this.registration).addMappingForServletNames( - EnumSet.of(DispatcherType.REQUEST), false, "b"); + verify(this.registration).addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), false, "b"); } @Test @@ -169,8 +161,7 @@ public abstract class AbstractFilterRegistrationBeanTests { @Test public void addUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - assertThatIllegalArgumentException() - .isThrownBy(() -> bean.addUrlPatterns((String[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlPatterns((String[]) null)) .withMessageContaining("UrlPatterns must not be null"); } @@ -184,8 +175,7 @@ public abstract class AbstractFilterRegistrationBeanTests { @Test public void addServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - assertThatIllegalArgumentException() - .isThrownBy(() -> bean.addServletNames((String[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> bean.addServletNames((String[]) null)) .withMessageContaining("ServletNames must not be null"); } @@ -194,15 +184,14 @@ public abstract class AbstractFilterRegistrationBeanTests { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.onStartup(this.servletContext); - verify(this.registration).addMappingForUrlPatterns( - EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*"); + verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), + false, "/*"); } @Test public void withSpecificDispatcherTypesEnumSet() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - EnumSet types = EnumSet.of(DispatcherType.INCLUDE, - DispatcherType.FORWARD); + EnumSet types = EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.setDispatcherTypes(types); bean.onStartup(this.servletContext); verify(this.registration).addMappingForUrlPatterns(types, false, "/*"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java index b9a7db63e5a..ca0721bb00f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ import static org.mockito.ArgumentMatchers.isA; * * @author Phillip Webb */ -public class DelegatingFilterProxyRegistrationBeanTests - extends AbstractFilterRegistrationBeanTests { +public class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { private static ThreadLocal mockFilterInitialized = new ThreadLocal<>(); @@ -53,22 +52,19 @@ public class DelegatingFilterProxyRegistrationBeanTests @Test public void targetBeanNameMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean(null)) .withMessageContaining("TargetBeanName must not be null or empty"); } @Test public void targetBeanNameMustNotBeEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("")) + assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("")) .withMessageContaining("TargetBeanName must not be null or empty"); } @Test public void nameDefaultsToTargetBeanName() { - assertThat(new DelegatingFilterProxyRegistrationBean("myFilter") - .getOrDeduceName(null)).isEqualTo("myFilter"); + assertThat(new DelegatingFilterProxyRegistrationBean("myFilter").getOrDeduceName(null)).isEqualTo("myFilter"); } @Test @@ -76,38 +72,34 @@ public class DelegatingFilterProxyRegistrationBeanTests DelegatingFilterProxyRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); assertThat(filter).isInstanceOf(DelegatingFilterProxy.class); - assertThat(ReflectionTestUtils.getField(filter, "webApplicationContext")) - .isEqualTo(this.applicationContext); - assertThat(ReflectionTestUtils.getField(filter, "targetBeanName")) - .isEqualTo("mockFilter"); + assertThat(ReflectionTestUtils.getField(filter, "webApplicationContext")).isEqualTo(this.applicationContext); + assertThat(ReflectionTestUtils.getField(filter, "targetBeanName")).isEqualTo("mockFilter"); } @Test public void initShouldNotCauseEarlyInitialization() throws Exception { - this.applicationContext.registerBeanDefinition("mockFilter", - new RootBeanDefinition(MockFilter.class)); + this.applicationContext.registerBeanDefinition("mockFilter", new RootBeanDefinition(MockFilter.class)); DelegatingFilterProxyRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); filter.init(new MockFilterConfig()); assertThat(mockFilterInitialized.get()).isNull(); - filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), - new MockFilterChain()); + filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); assertThat(mockFilterInitialized.get()).isTrue(); } @Test public void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("mockFilter", - (ServletRegistrationBean[]) null)) + .isThrownBy( + () -> new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null)) .withMessageContaining("ServletRegistrationBeans must not be null"); } @Override protected DelegatingFilterProxyRegistrationBean createFilterRegistrationBean( ServletRegistrationBean... servletRegistrationBeans) { - DelegatingFilterProxyRegistrationBean bean = new DelegatingFilterProxyRegistrationBean( - "mockFilter", servletRegistrationBeans); + DelegatingFilterProxyRegistrationBean bean = new DelegatingFilterProxyRegistrationBean("mockFilter", + servletRegistrationBeans); bean.setApplicationContext(this.applicationContext); return bean; } @@ -124,8 +116,7 @@ public class DelegatingFilterProxyRegistrationBeanTests } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java index 2d10c107547..9a65bd277a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,23 +46,20 @@ public class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanT @Test public void setFilterMustNotBeNull() throws Exception { FilterRegistrationBean bean = new FilterRegistrationBean<>(); - assertThatIllegalArgumentException() - .isThrownBy(() -> bean.onStartup(this.servletContext)) + assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) .withMessageContaining("Filter must not be null"); } @Test public void constructFilterMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new FilterRegistrationBean<>(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new FilterRegistrationBean<>(null)) .withMessageContaining("Filter must not be null"); } @Test public void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, - (ServletRegistrationBean[]) null)) + .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null)) .withMessageContaining("ServletRegistrationBeans must not be null"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java index e046196c05e..2b06710156c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java @@ -58,8 +58,8 @@ public class FilterRegistrationIntegrationTests { } private void load(Class configuration) { - this.context = new AnnotationConfigServletWebServerApplicationContext( - ContainerConfiguration.class, configuration); + this.context = new AnnotationConfigServletWebServerApplicationContext(ContainerConfiguration.class, + configuration); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java index 70ccc8003e8..371b235a28e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java @@ -56,8 +56,7 @@ public class ServletComponentScanIntegrationTests { new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); String port = this.context.getEnvironment().getProperty("local.server.port"); - String response = new RestTemplate() - .getForObject("http://localhost:" + port + "/test", String.class); + String response = new RestTemplate().getForObject("http://localhost:" + port + "/test", String.class); assertThat(response).isEqualTo("alpha bravo"); } @@ -68,13 +67,10 @@ public class ServletComponentScanIntegrationTests { new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); @SuppressWarnings("rawtypes") - Map beans = this.context - .getBeansOfType(ServletRegistrationBean.class); - ServletRegistrationBean servletRegistrationBean = beans - .get(TestMultipartServlet.class.getName()); + Map beans = this.context.getBeansOfType(ServletRegistrationBean.class); + ServletRegistrationBean servletRegistrationBean = beans.get(TestMultipartServlet.class.getName()); assertThat(servletRegistrationBean).isNotNull(); - MultipartConfigElement multipartConfig = servletRegistrationBean - .getMultipartConfig(); + MultipartConfigElement multipartConfig = servletRegistrationBean.getMultipartConfig(); assertThat(multipartConfig).isNotNull(); assertThat(multipartConfig.getLocation()).isEqualTo("test"); assertThat(multipartConfig.getMaxRequestSize()).isEqualTo(2048); @@ -83,8 +79,7 @@ public class ServletComponentScanIntegrationTests { } @Configuration(proxyBeanMethods = false) - @ServletComponentScan( - basePackages = "org.springframework.boot.web.servlet.testcomponents") + @ServletComponentScan(basePackages = "org.springframework.boot.web.servlet.testcomponents") static class TestConfiguration { @Bean diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index f6b6d8ab5e1..16cb1ba0cf1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -48,20 +48,17 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(ValuePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @Test public void packagesConfiguredWithValueAsm() { this.context = new AnnotationConfigApplicationContext(); - this.context.registerBeanDefinition("valuePackages", - new RootBeanDefinition(ValuePackages.class.getName())); + this.context.registerBeanDefinition("valuePackages", new RootBeanDefinition(ValuePackages.class.getName())); this.context.refresh(); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @Test @@ -69,8 +66,7 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @Test @@ -78,28 +74,23 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(BasePackageClasses.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()) - .contains(getClass().getPackage().getName()); + assertThat(postProcessor.getPackagesToScan()).contains(getClass().getPackage().getName()); } @Test public void packagesConfiguredWithBothValueAndBasePackages() { assertThatExceptionOfType(AnnotationConfigurationException.class) - .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( - ValueAndBasePackages.class)) + .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class)) .withMessageContaining("'value'").withMessageContaining("'basePackages'") - .withMessageContaining("com.example.foo") - .withMessageContaining("com.example.bar"); + .withMessageContaining("com.example.foo").withMessageContaining("com.example.bar"); } @Test public void packagesFromMultipleAnnotationsAreMerged() { - this.context = new AnnotationConfigApplicationContext(BasePackages.class, - AdditionalPackages.class); + this.context = new AnnotationConfigApplicationContext(BasePackages.class, AdditionalPackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar", "com.example.baz"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar", "com.example.baz"); } @Test @@ -107,30 +98,25 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()) - .containsExactly("org.springframework.boot.web.servlet"); + assertThat(postProcessor.getPackagesToScan()).containsExactly("org.springframework.boot.web.servlet"); } @Test public void noBasePackageAndBasePackageAreCombinedCorrectly() { - this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, - BasePackages.class); + this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder( - "org.springframework.boot.web.servlet", "com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", + "com.example.foo", "com.example.bar"); } @Test public void basePackageAndNoBasePackageAreCombinedCorrectly() { - this.context = new AnnotationConfigApplicationContext(BasePackages.class, - NoBasePackages.class); + this.context = new AnnotationConfigApplicationContext(BasePackages.class, NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder( - "org.springframework.boot.web.servlet", "com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", + "com.example.foo", "com.example.bar"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java index 0a474dfb068..ed85afba60e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java @@ -49,8 +49,7 @@ public class ServletContextInitializerBeansTests { ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory()); assertThat(initializerBeans.size()).isEqualTo(1); - assertThat(initializerBeans.iterator()).toIterable() - .hasOnlyElementsOfType(TestServlet.class); + assertThat(initializerBeans.iterator()).toIterable().hasOnlyElementsOfType(TestServlet.class); } @Test @@ -59,8 +58,7 @@ public class ServletContextInitializerBeansTests { ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory()); assertThat(initializerBeans.size()).isEqualTo(1); - assertThat(initializerBeans.iterator()).toIterable() - .hasOnlyElementsOfType(TestFilter.class); + assertThat(initializerBeans.iterator()).toIterable().hasOnlyElementsOfType(TestFilter.class); } @Test @@ -69,8 +67,7 @@ public class ServletContextInitializerBeansTests { ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory(), TestServletContextInitializer.class); assertThat(initializerBeans.size()).isEqualTo(1); - assertThat(initializerBeans.iterator()).toIterable() - .hasOnlyElementsOfType(TestServletContextInitializer.class); + assertThat(initializerBeans.iterator()).toIterable().hasOnlyElementsOfType(TestServletContextInitializer.class); } private void load(Class... configuration) { @@ -134,8 +131,7 @@ public class ServletContextInitializerBeansTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java index 48f525fc96c..2e15609d74e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,14 +63,13 @@ public class ServletListenerRegistrationBeanTests { this.listener); bean.setEnabled(false); bean.onStartup(this.servletContext); - verify(this.servletContext, never()) - .addListener(any(ServletContextListener.class)); + verify(this.servletContext, never()).addListener(any(ServletContextListener.class)); } @Test public void cannotRegisterUnsupportedType() { - assertThatIllegalArgumentException().isThrownBy( - () -> new ServletListenerRegistrationBean<>(new EventListener() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new ServletListenerRegistrationBean<>(new EventListener() { })).withMessageContaining("Listener is not of a supported type"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java index a95686c42e0..c7f1d1fcfe6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,16 +63,13 @@ public class ServletRegistrationBeanTests { @Before public void setupMocks() { MockitoAnnotations.initMocks(this); - given(this.servletContext.addServlet(anyString(), any(Servlet.class))) - .willReturn(this.registration); - given(this.servletContext.addFilter(anyString(), any(Filter.class))) - .willReturn(this.filterRegistration); + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.filterRegistration); } @Test public void startupWithDefaults() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); bean.onStartup(this.servletContext); verify(this.servletContext).addServlet("mockServlet", this.servlet); verify(this.registration).setAsyncSupported(true); @@ -81,10 +78,8 @@ public class ServletRegistrationBeanTests { @Test public void startupWithDoubleRegistration() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet); - given(this.servletContext.addServlet(anyString(), any(Servlet.class))) - .willReturn(null); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(null); bean.onStartup(this.servletContext); verify(this.servletContext).addServlet("mockServlet", this.servlet); verify(this.registration, never()).setAsyncSupported(true); @@ -141,46 +136,40 @@ public class ServletRegistrationBeanTests { @Test public void setServletMustNotBeNull() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); - assertThatIllegalArgumentException() - .isThrownBy(() -> bean.onStartup(this.servletContext)) + assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) .withMessageContaining("Servlet must not be null"); } @Test public void createServletMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ServletRegistrationBean(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ServletRegistrationBean(null)) .withMessageContaining("Servlet must not be null"); } @Test public void setMappingMustNotBeNull() { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlMappings(null)) .withMessageContaining("UrlMappings must not be null"); } @Test public void createMappingMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) .withMessageContaining("UrlMappings must not be null"); } @Test public void addMappingMustNotBeNull() { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet); - assertThatIllegalArgumentException() - .isThrownBy(() -> bean.addUrlMappings((String[]) null)) + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); + assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlMappings((String[]) null)) .withMessageContaining("UrlMappings must not be null"); } @Test public void setMappingReplacesValue() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet, "/a", "/b"); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, "/a", "/b"); bean.setUrlMappings(new LinkedHashSet<>(Arrays.asList("/c", "/d"))); bean.onStartup(this.servletContext); verify(this.registration).addMapping("/c", "/d"); @@ -188,8 +177,7 @@ public class ServletRegistrationBeanTests { @Test public void modifyInitParameters() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet, "/a", "/b"); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, "/a", "/b"); bean.addInitParameter("a", "b"); bean.getInitParameters().put("a", "c"); bean.onStartup(this.servletContext); @@ -198,8 +186,7 @@ public class ServletRegistrationBeanTests { @Test public void withoutDefaultMappings() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet, false); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, false); bean.onStartup(this.servletContext); verify(this.registration, never()).addMapping(any(String[].class)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index 9c9adbfef94..23a6367fb60 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ public class WebFilterHandlerTests { @Test public void defaultFilterConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(DefaultConfigurationFilter.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(DefaultConfigurationFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationFilter.class.getName()); @@ -65,20 +64,17 @@ public class WebFilterHandlerTests { assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat((EnumSet) propertyValues.get("dispatcherTypes")) .containsExactly(DispatcherType.REQUEST); - assertThat(((Map) propertyValues.get("initParameters"))) - .isEmpty(); + assertThat(((Map) propertyValues.get("initParameters"))).isEmpty(); assertThat((String[]) propertyValues.get("servletNames")).isEmpty(); assertThat((String[]) propertyValues.get("urlPatterns")).isEmpty(); - assertThat(propertyValues.get("name")) - .isEqualTo(DefaultConfigurationFilter.class.getName()); + assertThat(propertyValues.get("name")).isEqualTo(DefaultConfigurationFilter.class.getName()); assertThat(propertyValues.get("filter")).isEqualTo(scanned); } @Test public void filterWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(CustomNameFilter.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(CustomNameFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry.getBeanDefinition("custom"); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); @@ -87,8 +83,7 @@ public class WebFilterHandlerTests { @Test public void asyncSupported() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - AsyncSupportedFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(AsyncSupportedFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); } @@ -96,63 +91,51 @@ public class WebFilterHandlerTests { @Test @SuppressWarnings("unchecked") public void dispatcherTypes() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - DispatcherTypesFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(DispatcherTypesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((Set) propertyValues.get("dispatcherTypes")) - .containsExactly(DispatcherType.FORWARD, DispatcherType.INCLUDE, - DispatcherType.REQUEST); + assertThat((Set) propertyValues.get("dispatcherTypes")).containsExactly(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST); } @SuppressWarnings("unchecked") @Test public void initParameters() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - InitParametersFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(InitParametersFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((Map) propertyValues.get("initParameters")) - .containsEntry("a", "alpha").containsEntry("b", "bravo"); + assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") + .containsEntry("b", "bravo"); } @Test public void servletNames() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - ServletNamesFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(ServletNamesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("servletNames")).contains("alpha", - "bravo"); + assertThat((String[]) propertyValues.get("servletNames")).contains("alpha", "bravo"); } @Test public void urlPatterns() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - UrlPatternsFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(UrlPatternsFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", - "bravo"); + assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", "bravo"); } @Test public void urlPatternsFromValue() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - UrlPatternsFromValueFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(UrlPatternsFromValueFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", - "bravo"); + assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", "bravo"); } @Test public void urlPatternsDeclaredTwice() throws IOException { - assertThatIllegalStateException() - .isThrownBy(() -> getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class)) - .withMessageContaining( - "The urlPatterns and value attributes are mutually exclusive."); + assertThatIllegalStateException().isThrownBy(() -> getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class)) + .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } BeanDefinition getBeanDefinition(Class filterClass) throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(filterClass.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(filterClass.getName())); this.handler.handle(scanned, this.registry); return this.registry.getBeanDefinition(filterClass.getName()); } @@ -167,14 +150,12 @@ public class WebFilterHandlerTests { } - @WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, - DispatcherType.INCLUDE }) + @WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE }) class DispatcherTypesFilter extends BaseFilter { } - @WebFilter(initParams = { @WebInitParam(name = "a", value = "alpha"), - @WebInitParam(name = "b", value = "bravo") }) + @WebFilter(initParams = { @WebInitParam(name = "a", value = "alpha"), @WebInitParam(name = "b", value = "bravo") }) class InitParametersFilter extends BaseFilter { } @@ -212,8 +193,7 @@ public class WebFilterHandlerTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java index e8bab2650a9..3d9497d3fd5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,7 @@ public class WebListenerHandlerTests { @Test public void listener() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(TestListener.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(TestListener.class.getName())); this.handler.handle(scanned, this.registry); this.registry.getBeanDefinition(TestListener.class.getName()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index b9e9947607d..480a4f1429c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,19 +49,15 @@ public class WebServletHandlerTests { @Test public void defaultServletConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(DefaultConfigurationServlet.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(DefaultConfigurationServlet.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition servletRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationServlet.class.getName()); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); - assertThat(((Map) propertyValues.get("initParameters"))) - .isEmpty(); + assertThat(((Map) propertyValues.get("initParameters"))).isEmpty(); assertThat((Integer) propertyValues.get("loadOnStartup")).isEqualTo(-1); - assertThat(propertyValues.get("name")) - .isEqualTo(DefaultConfigurationServlet.class.getName()); + assertThat(propertyValues.get("name")).isEqualTo(DefaultConfigurationServlet.class.getName()); assertThat((String[]) propertyValues.get("urlMappings")).isEmpty(); assertThat(propertyValues.get("servlet")).isEqualTo(scanned); } @@ -69,69 +65,52 @@ public class WebServletHandlerTests { @Test public void servletWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(CustomNameServlet.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(CustomNameServlet.class.getName())); this.handler.handle(scanned, this.registry); - BeanDefinition servletRegistrationBean = this.registry - .getBeanDefinition("custom"); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); + BeanDefinition servletRegistrationBean = this.registry.getBeanDefinition("custom"); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("name")).isEqualTo("custom"); } @Test public void asyncSupported() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - AsyncSupportedServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); + BeanDefinition servletRegistrationBean = getBeanDefinition(AsyncSupportedServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); } @SuppressWarnings("unchecked") @Test public void initParameters() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - InitParametersServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); - assertThat((Map) propertyValues.get("initParameters")) - .containsEntry("a", "alpha").containsEntry("b", "bravo"); + BeanDefinition servletRegistrationBean = getBeanDefinition(InitParametersServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); + assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") + .containsEntry("b", "bravo"); } @Test public void urlMappings() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - UrlPatternsServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); - assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", - "bravo"); + BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); + assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo"); } @Test public void urlMappingsFromValue() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - UrlPatternsFromValueServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); - assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", - "bravo"); + BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsFromValueServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); + assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo"); } @Test public void urlPatternsDeclaredTwice() throws IOException { - assertThatIllegalStateException() - .isThrownBy( - () -> getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class)) - .withMessageContaining( - "The urlPatterns and value attributes are mutually exclusive."); + assertThatIllegalStateException().isThrownBy(() -> getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class)) + .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } private BeanDefinition getBeanDefinition(Class filterClass) throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(filterClass.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(filterClass.getName())); this.handler.handle(scanned, this.registry); return this.registry.getBeanDefinition(filterClass.getName()); } @@ -146,8 +125,7 @@ public class WebServletHandlerTests { } - @WebServlet(initParams = { @WebInitParam(name = "a", value = "alpha"), - @WebInitParam(name = "b", value = "bravo") }) + @WebServlet(initParams = { @WebInitParam(name = "a", value = "alpha"), @WebInitParam(name = "b", value = "bravo") }) class InitParametersServlet extends HttpServlet { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java index 78f97216c2c..94f4b9d10c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java @@ -60,24 +60,22 @@ public class AnnotationConfigServletWebServerApplicationContextTests { @Test public void createFromScan() { this.context = new AnnotationConfigServletWebServerApplicationContext( - ExampleServletWebServerApplicationConfiguration.class.getPackage() - .getName()); + ExampleServletWebServerApplicationConfiguration.class.getPackage().getName()); verifyContext(); } @Test public void sessionScopeAvailable() { this.context = new AnnotationConfigServletWebServerApplicationContext( - ExampleServletWebServerApplicationConfiguration.class, - SessionScopedComponent.class); + ExampleServletWebServerApplicationConfiguration.class, SessionScopedComponent.class); verifyContext(); } @Test public void sessionScopeAvailableToServlet() { this.context = new AnnotationConfigServletWebServerApplicationContext( - ExampleServletWebServerApplicationConfiguration.class, - ExampleServletWithAutowired.class, SessionScopedComponent.class); + ExampleServletWebServerApplicationConfiguration.class, ExampleServletWithAutowired.class, + SessionScopedComponent.class); Servlet servlet = this.context.getBean(ExampleServletWithAutowired.class); assertThat(servlet).isNotNull(); } @@ -110,8 +108,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { @Test public void scanAndRefresh() { this.context = new AnnotationConfigServletWebServerApplicationContext(); - this.context.scan(ExampleServletWebServerApplicationConfiguration.class - .getPackage().getName()); + this.context.scan(ExampleServletWebServerApplicationConfiguration.class.getPackage().getName()); this.context.refresh(); verifyContext(); } @@ -123,8 +120,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { verifyContext(); // You can't initialize the application context and inject the servlet context // because of a cycle - we'd like this to be not null but it never will be - assertThat(this.context.getBean(ServletContextAwareEmbeddedConfiguration.class) - .getServletContext()).isNull(); + assertThat(this.context.getBean(ServletContextAwareEmbeddedConfiguration.class).getServletContext()).isNull(); } @Test @@ -132,18 +128,15 @@ public class AnnotationConfigServletWebServerApplicationContextTests { AnnotationConfigServletWebServerApplicationContext parent = new AnnotationConfigServletWebServerApplicationContext( WebServerConfiguration.class); this.context = new AnnotationConfigServletWebServerApplicationContext(); - this.context.register(WebServerConfiguration.class, - ServletContextAwareConfiguration.class); + this.context.register(WebServerConfiguration.class, ServletContextAwareConfiguration.class); this.context.setParent(parent); this.context.refresh(); verifyContext(); - assertThat(this.context.getBean(ServletContextAwareConfiguration.class) - .getServletContext()).isNotNull(); + assertThat(this.context.getBean(ServletContextAwareConfiguration.class).getServletContext()).isNotNull(); } private void verifyContext() { - MockServletWebServerFactory factory = this.context - .getBean(MockServletWebServerFactory.class); + MockServletWebServerFactory factory = this.context.getBean(MockServletWebServerFactory.class); Servlet servlet = this.context.getBean(Servlet.class); verify(factory.getServletContext()).addServlet("servlet", servlet); } @@ -170,8 +163,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { @Configuration(proxyBeanMethods = false) @EnableWebMvc - public static class ServletContextAwareEmbeddedConfiguration - implements ServletContextAware { + public static class ServletContextAwareEmbeddedConfiguration implements ServletContextAware { private ServletContext servletContext; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java index 251b07664bf..8dd891a0cda 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,18 +112,14 @@ public class ServletWebServerApplicationContextTests { this.context.refresh(); MockServletWebServerFactory factory = getWebServerFactory(); // Ensure that the context has been setup - assertThat(this.context.getServletContext()) - .isEqualTo(factory.getServletContext()); - verify(factory.getServletContext()).setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + assertThat(this.context.getServletContext()).isEqualTo(factory.getServletContext()); + verify(factory.getServletContext()).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); // Ensure WebApplicationContextUtils.registerWebApplicationScopes was called - assertThat(this.context.getBeanFactory() - .getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) - .isInstanceOf(SessionScope.class); + assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) + .isInstanceOf(SessionScope.class); // Ensure WebApplicationContextUtils.registerEnvironmentBeans was called - assertThat(this.context - .containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); + assertThat(this.context.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); } @Test @@ -139,11 +135,9 @@ public class ServletWebServerApplicationContextTests { @Test public void ServletWebServerInitializedEventPublished() { addWebServerFactoryBean(); - this.context.registerBeanDefinition("listener", - new RootBeanDefinition(MockListener.class)); + this.context.registerBeanDefinition("listener", new RootBeanDefinition(MockListener.class)); this.context.refresh(); - ServletWebServerInitializedEvent event = this.context.getBean(MockListener.class) - .getEvent(); + ServletWebServerInitializedEvent event = this.context.getBean(MockListener.class).getEvent(); assertThat(event).isNotNull(); assertThat(event.getSource().getPort() >= 0).isTrue(); assertThat(event.getApplicationContext()).isEqualTo(this.context); @@ -186,10 +180,9 @@ public class ServletWebServerApplicationContextTests { @Test public void missingServletWebServerFactory() { - assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(() -> this.context.refresh()).withMessageContaining( - "Unable to start ServletWebServerApplicationContext due to missing " - + "ServletWebServerFactory bean"); + assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) + .withMessageContaining("Unable to start ServletWebServerApplicationContext due to missing " + + "ServletWebServerFactory bean"); } @Test @@ -197,10 +190,9 @@ public class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); this.context.registerBeanDefinition("webServerFactory2", new RootBeanDefinition(MockServletWebServerFactory.class)); - assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(() -> this.context.refresh()).withMessageContaining( - "Unable to start ServletWebServerApplicationContext due to " - + "multiple ServletWebServerFactory beans"); + assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) + .withMessageContaining("Unable to start ServletWebServerApplicationContext due to " + + "multiple ServletWebServerFactory beans"); } @@ -223,8 +215,7 @@ public class ServletWebServerApplicationContextTests { FilterRegistrationBean registration = new FilterRegistrationBean<>(); registration.setFilter(mock(Filter.class)); registration.setOrder(100); - this.context.registerBeanDefinition("filterRegistrationBean", - beanDefinition(registration)); + this.context.registerBeanDefinition("filterRegistrationBean", beanDefinition(registration)); this.context.refresh(); MockServletWebServerFactory factory = getWebServerFactory(); verify(factory.getServletContext()).addFilter("filterBean", filter); @@ -235,11 +226,9 @@ public class ServletWebServerApplicationContextTests { @Test public void multipleServletBeans() { addWebServerFactoryBean(); - Servlet servlet1 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet1).getOrder()).willReturn(1); - Servlet servlet2 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet2 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet2).getOrder()).willReturn(2); this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2)); this.context.registerBeanDefinition("servletBean1", beanDefinition(servlet1)); @@ -249,24 +238,19 @@ public class ServletWebServerApplicationContextTests { InOrder ordered = inOrder(servletContext); ordered.verify(servletContext).addServlet("servletBean1", servlet1); ordered.verify(servletContext).addServlet("servletBean2", servlet2); - verify(factory.getRegisteredServlet(0).getRegistration()) - .addMapping("/servletBean1/"); - verify(factory.getRegisteredServlet(1).getRegistration()) - .addMapping("/servletBean2/"); + verify(factory.getRegisteredServlet(0).getRegistration()).addMapping("/servletBean1/"); + verify(factory.getRegisteredServlet(1).getRegistration()).addMapping("/servletBean2/"); } @Test public void multipleServletBeansWithMainDispatcher() { addWebServerFactoryBean(); - Servlet servlet1 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet1).getOrder()).willReturn(1); - Servlet servlet2 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet2 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet2).getOrder()).willReturn(2); this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2)); - this.context.registerBeanDefinition("dispatcherServlet", - beanDefinition(servlet1)); + this.context.registerBeanDefinition("dispatcherServlet", beanDefinition(servlet1)); this.context.refresh(); MockServletWebServerFactory factory = getWebServerFactory(); ServletContext servletContext = factory.getServletContext(); @@ -274,19 +258,16 @@ public class ServletWebServerApplicationContextTests { ordered.verify(servletContext).addServlet("dispatcherServlet", servlet1); ordered.verify(servletContext).addServlet("servletBean2", servlet2); verify(factory.getRegisteredServlet(0).getRegistration()).addMapping("/"); - verify(factory.getRegisteredServlet(1).getRegistration()) - .addMapping("/servletBean2/"); + verify(factory.getRegisteredServlet(1).getRegistration()).addMapping("/servletBean2/"); } @Test public void servletAndFilterBeans() { addWebServerFactoryBean(); Servlet servlet = mock(Servlet.class); - Filter filter1 = mock(Filter.class, - withSettings().extraInterfaces(Ordered.class)); + Filter filter1 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) filter1).getOrder()).willReturn(1); - Filter filter2 = mock(Filter.class, - withSettings().extraInterfaces(Ordered.class)); + Filter filter2 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) filter2).getOrder()).willReturn(2); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean2", beanDefinition(filter2)); @@ -299,10 +280,10 @@ public class ServletWebServerApplicationContextTests { verify(factory.getRegisteredServlet(0).getRegistration()).addMapping("/"); ordered.verify(factory.getServletContext()).addFilter("filterBean1", filter1); ordered.verify(factory.getServletContext()).addFilter("filterBean2", filter2); - verify(factory.getRegisteredFilter(0).getRegistration()).addMappingForUrlPatterns( - EnumSet.of(DispatcherType.REQUEST), false, "/*"); - verify(factory.getRegisteredFilter(1).getRegistration()).addMappingForUrlPatterns( - EnumSet.of(DispatcherType.REQUEST), false, "/*"); + verify(factory.getRegisteredFilter(0).getRegistration()) + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); + verify(factory.getRegisteredFilter(1).getRegistration()) + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); } @Test @@ -314,10 +295,8 @@ public class ServletWebServerApplicationContextTests { ServletContextInitializer initializer2 = mock(ServletContextInitializer.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) initializer2).getOrder()).willReturn(2); - this.context.registerBeanDefinition("initializerBean2", - beanDefinition(initializer2)); - this.context.registerBeanDefinition("initializerBean1", - beanDefinition(initializer1)); + this.context.registerBeanDefinition("initializerBean2", beanDefinition(initializer2)); + this.context.registerBeanDefinition("initializerBean1", beanDefinition(initializer1)); this.context.refresh(); ServletContext servletContext = getWebServerFactory().getServletContext(); InOrder ordered = inOrder(initializer1, initializer2); @@ -329,8 +308,7 @@ public class ServletWebServerApplicationContextTests { public void servletContextListenerBeans() { addWebServerFactoryBean(); ServletContextListener initializer = mock(ServletContextListener.class); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.refresh(); ServletContext servletContext = getWebServerFactory().getServletContext(); verify(servletContext).addListener(initializer); @@ -341,10 +319,8 @@ public class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); ServletContextInitializer initializer1 = mock(ServletContextInitializer.class); ServletContextInitializer initializer2 = mock(ServletContextInitializer.class); - this.context.registerBeanDefinition("initializerBean2", - beanDefinition(initializer2)); - this.context.registerBeanDefinition("initializerBean1", - beanDefinition(initializer1)); + this.context.registerBeanDefinition("initializerBean2", beanDefinition(initializer2)); + this.context.registerBeanDefinition("initializerBean1", beanDefinition(initializer1)); this.context.refresh(); ServletContext servletContext = getWebServerFactory().getServletContext(); verify(initializer1).onStartup(servletContext); @@ -352,14 +328,12 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletContextInitializerBeansDoesNotSkipServletsAndFilters() - throws Exception { + public void servletContextInitializerBeansDoesNotSkipServletsAndFilters() throws Exception { addWebServerFactoryBean(); ServletContextInitializer initializer = mock(ServletContextInitializer.class); Servlet servlet = mock(Servlet.class); Filter filter = mock(Filter.class); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); @@ -374,10 +348,8 @@ public class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); Servlet servlet = mock(Servlet.class); Filter filter = mock(Filter.class); - ServletRegistrationBean initializer = new ServletRegistrationBean<>( - servlet, "/foo"); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + ServletRegistrationBean initializer = new ServletRegistrationBean<>(servlet, "/foo"); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); @@ -391,8 +363,7 @@ public class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); Filter filter = mock(Filter.class); FilterRegistrationBean initializer = new FilterRegistrationBean<>(filter); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); ServletContext servletContext = getWebServerFactory().getServletContext(); @@ -400,34 +371,28 @@ public class ServletWebServerApplicationContextTests { } @Test - public void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() - throws Exception { + public void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() throws Exception { addWebServerFactoryBean(); - DelegatingFilterProxyRegistrationBean initializer = new DelegatingFilterProxyRegistrationBean( - "filterBean"); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); - BeanDefinition filterBeanDefinition = beanDefinition( - new IllegalStateException("Create FilterBean Failure")); + DelegatingFilterProxyRegistrationBean initializer = new DelegatingFilterProxyRegistrationBean("filterBean"); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); + BeanDefinition filterBeanDefinition = beanDefinition(new IllegalStateException("Create FilterBean Failure")); filterBeanDefinition.setLazyInit(true); this.context.registerBeanDefinition("filterBean", filterBeanDefinition); this.context.refresh(); ServletContext servletContext = getWebServerFactory().getServletContext(); - verify(servletContext, atMost(1)).addFilter(anyString(), - this.filterCaptor.capture()); + verify(servletContext, atMost(1)).addFilter(anyString(), this.filterCaptor.capture()); // Up to this point the filterBean should not have been created, calling // the delegate proxy will trigger creation and an exception assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> { this.filterCaptor.getValue().init(new MockFilterConfig()); - this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), - new MockHttpServletResponse(), new MockFilterChain()); + this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), + new MockFilterChain()); }).withMessageContaining("Create FilterBean Failure"); } @Test public void postProcessWebServerFactory() { - RootBeanDefinition beanDefinition = new RootBeanDefinition( - MockServletWebServerFactory.class); + RootBeanDefinition beanDefinition = new RootBeanDefinition(MockServletWebServerFactory.class); MutablePropertyValues pv = new MutablePropertyValues(); pv.add("port", "${port}"); beanDefinition.setPropertyValues(pv); @@ -436,8 +401,7 @@ public class ServletWebServerApplicationContextTests { Properties properties = new Properties(); properties.put("port", 8080); propertySupport.setProperties(properties); - this.context.registerBeanDefinition("propertySupport", - beanDefinition(propertySupport)); + this.context.registerBeanDefinition("propertySupport", beanDefinition(propertySupport)); this.context.refresh(); assertThat(getWebServerFactory().getWebServer().getPort()).isEqualTo(8080); } @@ -451,10 +415,8 @@ public class ServletWebServerApplicationContextTests { factory.registerScope(WebApplicationContext.SCOPE_SESSION, scope); addWebServerFactoryBean(); this.context.refresh(); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_REQUEST)) - .isSameAs(scope); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) - .isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_REQUEST)).isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_SESSION)).isSameAs(scope); } @Test @@ -462,14 +424,11 @@ public class ServletWebServerApplicationContextTests { // gh-14990 int initialOutputLength = this.output.toString().length(); addWebServerFactoryBean(); - RootBeanDefinition beanDefinition = new RootBeanDefinition( - WithAutowiredServletRequest.class); + RootBeanDefinition beanDefinition = new RootBeanDefinition(WithAutowiredServletRequest.class); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); - this.context.registerBeanDefinition("withAutowiredServletRequest", - beanDefinition); + this.context.registerBeanDefinition("withAutowiredServletRequest", beanDefinition); this.context.addBeanFactoryPostProcessor((beanFactory) -> { - WithAutowiredServletRequest bean = beanFactory - .getBean(WithAutowiredServletRequest.class); + WithAutowiredServletRequest bean = beanFactory.getBean(WithAutowiredServletRequest.class); assertThat(bean.getRequest()).isNotNull(); }); this.context.refresh(); @@ -481,8 +440,8 @@ public class ServletWebServerApplicationContextTests { public void webApplicationScopeIsRegistered() throws Exception { addWebServerFactoryBean(); this.context.refresh(); - assertThat(this.context.getBeanFactory() - .getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)).isNotNull(); + assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)) + .isNotNull(); } private void addWebServerFactoryBean() { @@ -511,8 +470,7 @@ public class ServletWebServerApplicationContextTests { return object; } - public static class MockListener - implements ApplicationListener { + public static class MockListener implements ApplicationListener { private ServletWebServerInitializedEvent event; @@ -531,8 +489,7 @@ public class ServletWebServerApplicationContextTests { protected static class OrderedFilter extends GenericFilterBean { @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java index 661972ac63f..2ae26d0bc15 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java @@ -69,41 +69,35 @@ public class ServletWebServerMvcIntegrationTests { @Test public void tomcat() throws Exception { - this.context = new AnnotationConfigServletWebServerApplicationContext( - TomcatConfig.class); + this.context = new AnnotationConfigServletWebServerApplicationContext(TomcatConfig.class); doTest(this.context, "/hello"); } @Test public void jetty() throws Exception { - this.context = new AnnotationConfigServletWebServerApplicationContext( - JettyConfig.class); + this.context = new AnnotationConfigServletWebServerApplicationContext(JettyConfig.class); doTest(this.context, "/hello"); } @Test public void undertow() throws Exception { - this.context = new AnnotationConfigServletWebServerApplicationContext( - UndertowConfig.class); + this.context = new AnnotationConfigServletWebServerApplicationContext(UndertowConfig.class); doTest(this.context, "/hello"); } @Test public void advancedConfig() throws Exception { - this.context = new AnnotationConfigServletWebServerApplicationContext( - AdvancedConfig.class); + this.context = new AnnotationConfigServletWebServerApplicationContext(AdvancedConfig.class); doTest(this.context, "/example/spring/hello"); } - private void doTest(AnnotationConfigServletWebServerApplicationContext context, - String resourcePath) throws Exception { + private void doTest(AnnotationConfigServletWebServerApplicationContext context, String resourcePath) + throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); - ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI( - "http://localhost:" + context.getWebServer().getPort() + resourcePath), - HttpMethod.GET); + ClientHttpRequest request = clientHttpRequestFactory.createRequest( + new URI("http://localhost:" + context.getWebServer().getPort() + resourcePath), HttpMethod.GET); try (ClientHttpResponse response = request.execute()) { - String actual = StreamUtils.copyToString(response.getBody(), - StandardCharsets.UTF_8); + String actual = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8); assertThat(actual).isEqualTo("Hello World"); } } @@ -111,8 +105,7 @@ public class ServletWebServerMvcIntegrationTests { // Simple main method for testing in a browser @SuppressWarnings("resource") public static void main(String[] args) { - new AnnotationConfigServletWebServerApplicationContext( - JettyServletWebServerFactory.class, Config.class); + new AnnotationConfigServletWebServerApplicationContext(JettyServletWebServerFactory.class, Config.class); } @Configuration(proxyBeanMethods = false) @@ -186,10 +179,8 @@ public class ServletWebServerMvcIntegrationTests { } @Bean - public ServletRegistrationBean dispatcherRegistration( - DispatcherServlet dispatcherServlet) { - ServletRegistrationBean registration = new ServletRegistrationBean<>( - dispatcherServlet); + public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) { + ServletRegistrationBean registration = new ServletRegistrationBean<>(dispatcherServlet); registration.addUrlMappings("/spring/*"); return registration; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java index c66b819c8fc..1bb2b1ff4f6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,8 @@ import static org.mockito.Mockito.verify; */ public class XmlServletWebServerApplicationContextTests { - private static final String PATH = XmlServletWebServerApplicationContextTests.class - .getPackage().getName().replace('.', '/') + "/"; + private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage().getName() + .replace('.', '/') + "/"; private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml"; @@ -41,8 +41,7 @@ public class XmlServletWebServerApplicationContextTests { @Test public void createFromResource() { - this.context = new XmlServletWebServerApplicationContext( - new ClassPathResource(FILE, getClass())); + this.context = new XmlServletWebServerApplicationContext(new ClassPathResource(FILE, getClass())); verifyContext(); } @@ -83,8 +82,7 @@ public class XmlServletWebServerApplicationContextTests { } private void verifyContext() { - MockServletWebServerFactory factory = this.context - .getBean(MockServletWebServerFactory.class); + MockServletWebServerFactory factory = this.context.getBean(MockServletWebServerFactory.class); Servlet servlet = this.context.getBean(Servlet.class); verify(factory.getServletContext()).addServlet("servlet", servlet); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java index 141bf9f59a2..9442b0ef7a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,25 +53,21 @@ public class DefaultErrorAttributesTests { @Test public void includeTimeStamp() { - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("timestamp")).isInstanceOf(Date.class); } @Test public void specificStatusCode() { this.request.setAttribute("javax.servlet.error.status_code", 404); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); - assertThat(attributes.get("error")) - .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); + assertThat(attributes.get("error")).isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); assertThat(attributes.get("status")).isEqualTo(404); } @Test public void missingStatusCode() { - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("error")).isEqualTo("None"); assertThat(attributes.get("status")).isEqualTo(999); } @@ -79,12 +75,9 @@ public class DefaultErrorAttributesTests { @Test public void mvcError() { RuntimeException ex = new RuntimeException("Test"); - ModelAndView modelAndView = this.errorAttributes.resolveException(this.request, - null, null, ex); - this.request.setAttribute("javax.servlet.error.exception", - new RuntimeException("Ignored")); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + ModelAndView modelAndView = this.errorAttributes.resolveException(this.request, null, null, ex); + this.request.setAttribute("javax.servlet.error.exception", new RuntimeException("Ignored")); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(modelAndView).isNull(); assertThat(attributes.get("exception")).isNull(); @@ -95,8 +88,7 @@ public class DefaultErrorAttributesTests { public void servletError() { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test"); @@ -105,19 +97,16 @@ public class DefaultErrorAttributesTests { @Test public void servletMessage() { this.request.setAttribute("javax.servlet.error.message", "Test"); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test"); } @Test public void nullMessage() { - this.request.setAttribute("javax.servlet.error.exception", - new RuntimeException()); + this.request.setAttribute("javax.servlet.error.exception", new RuntimeException()); this.request.setAttribute("javax.servlet.error.message", "Test"); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -127,8 +116,7 @@ public class DefaultErrorAttributesTests { RuntimeException ex = new RuntimeException("Test"); ServletException wrapped = new ServletException(new ServletException(ex)); this.request.setAttribute("javax.servlet.error.exception", wrapped); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(wrapped); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test"); @@ -138,8 +126,7 @@ public class DefaultErrorAttributesTests { public void getError() { Error error = new OutOfMemoryError("Test error"); this.request.setAttribute("javax.servlet.error.exception", error); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(error); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test error"); @@ -147,8 +134,7 @@ public class DefaultErrorAttributesTests { @Test public void extractBindingResultErrors() { - BindingResult bindingResult = new MapBindingResult( - Collections.singletonMap("a", "b"), "objectName"); + BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new BindException(bindingResult); testBindingResult(bindingResult, ex); @@ -156,8 +142,7 @@ public class DefaultErrorAttributesTests { @Test public void extractMethodArgumentNotValidExceptionBindingResultErrors() { - BindingResult bindingResult = new MapBindingResult( - Collections.singletonMap("a", "b"), "objectName"); + BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new MethodArgumentNotValidException(null, bindingResult); testBindingResult(bindingResult, ex); @@ -165,10 +150,8 @@ public class DefaultErrorAttributesTests { private void testBindingResult(BindingResult bindingResult, Exception ex) { this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); - assertThat(attributes.get("message")) - .isEqualTo("Validation failed for object='objectName'. Error count: 1"); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); + assertThat(attributes.get("message")).isEqualTo("Validation failed for object='objectName'. Error count: 1"); assertThat(attributes.get("errors")).isEqualTo(bindingResult.getAllErrors()); } @@ -177,10 +160,8 @@ public class DefaultErrorAttributesTests { DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes(true); RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = errorAttributes - .getErrorAttributes(this.webRequest, false); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + Map attributes = errorAttributes.getErrorAttributes(this.webRequest, false); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -188,8 +169,7 @@ public class DefaultErrorAttributesTests { public void trace() { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, true); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, true); assertThat(attributes.get("trace").toString()).startsWith("java.lang"); } @@ -197,16 +177,14 @@ public class DefaultErrorAttributesTests { public void noTrace() { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("trace")).isNull(); } @Test public void path() { this.request.setAttribute("javax.servlet.error.request_uri", "path"); - Map attributes = this.errorAttributes - .getErrorAttributes(this.webRequest, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("path")).isEqualTo("path"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockFilter.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockFilter.java index 7bad6ad1b85..00442d036d9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockFilter.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,8 @@ public class MockFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockServlet.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockServlet.java index 60b4369d906..d457a79b369 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockServlet.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/mock/MockServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,7 @@ import javax.servlet.ServletResponse; public class MockServlet extends GenericServlet { @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java index b09b3b7fcbf..40c81855664 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java @@ -205,8 +205,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); int port = this.webServer.getPort(); this.webServer.stop(); - assertThatIOException() - .isThrownBy(() -> getResponse(getLocalUrl(port, "/hello"))); + assertThatIOException().isThrownBy(() -> getResponse(getLocalUrl(port, "/hello"))); } @Test @@ -239,8 +238,8 @@ public abstract class AbstractServletWebServerFactoryTests { public void loadOnStartAfterContextIsInitialized() { AbstractServletWebServerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); - this.webServer = factory.getWebServer((servletContext) -> servletContext - .addServlet("test", servlet).setLoadOnStartup(1)); + this.webServer = factory + .getWebServer((servletContext) -> servletContext.addServlet("test", servlet).setLoadOnStartup(1)); assertThat(servlet.getInitCount()).isEqualTo(0); this.webServer.start(); assertThat(servlet.getInitCount()).isEqualTo(1); @@ -253,8 +252,7 @@ public abstract class AbstractServletWebServerFactoryTests { factory.setPort(specificPort); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); - assertThat(getResponse("http://localhost:" + specificPort + "/hello")) - .isEqualTo("Hello World"); + assertThat(getResponse("http://localhost:" + specificPort + "/hello")).isEqualTo("Hello World"); assertThat(this.webServer.getPort()).isEqualTo(specificPort); } @@ -273,31 +271,25 @@ public abstract class AbstractServletWebServerFactoryTests { factory.setContextPath("/custom"); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); - assertThat(this.output.toString()) - .containsOnlyOnce("with context path '/custom'"); + assertThat(this.output.toString()).containsOnlyOnce("with context path '/custom'"); } @Test public void contextPathMustStartWithSlash() { - assertThatIllegalArgumentException() - .isThrownBy(() -> getFactory().setContextPath("missingslash")) - .withMessageContaining( - "ContextPath must start with '/' and not end with '/'"); + assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("missingslash")) + .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test public void contextPathMustNotEndWithSlash() { - assertThatIllegalArgumentException() - .isThrownBy(() -> getFactory().setContextPath("extraslash/")) - .withMessageContaining( - "ContextPath must start with '/' and not end with '/'"); + assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("extraslash/")) + .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test public void contextRootPathMustNotBeSlash() { - assertThatIllegalArgumentException() - .isThrownBy(() -> getFactory().setContextPath("/")).withMessageContaining( - "Root ContextPath must be specified using an empty string"); + assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("/")) + .withMessageContaining("Root ContextPath must be specified using an empty string"); } @Test @@ -326,8 +318,7 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void mimeType() throws Exception { - FileCopyUtils.copy("test", - new FileWriter(this.temporaryFolder.newFile("test.xxcss"))); + FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.xxcss"))); AbstractServletWebServerFactory factory = getFactory(); factory.setDocumentRoot(this.temporaryFolder.getRoot()); MimeMappings mimeMappings = new MimeMappings(); @@ -336,8 +327,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); this.webServer.start(); ClientHttpResponse response = getClientResponse(getLocalUrl("/test.xxcss")); - assertThat(response.getHeaders().getContentType().toString()) - .isEqualTo("text/css"); + assertThat(response.getHeaders().getContentType().toString()).isEqualTo("text/css"); response.close(); } @@ -345,8 +335,7 @@ public abstract class AbstractServletWebServerFactoryTests { public void errorPage() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello")); - this.webServer = factory.getWebServer(exampleServletRegistration(), - errorServletRegistration()); + this.webServer = factory.getWebServer(exampleServletRegistration(), errorServletRegistration()); this.webServer.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); assertThat(getResponse(getLocalUrl("/bang"))).isEqualTo("Hello World"); @@ -356,13 +345,10 @@ public abstract class AbstractServletWebServerFactoryTests { public void errorPageFromPutRequest() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello")); - this.webServer = factory.getWebServer(exampleServletRegistration(), - errorServletRegistration()); + this.webServer = factory.getWebServer(exampleServletRegistration(), errorServletRegistration()); this.webServer.start(); - assertThat(getResponse(getLocalUrl("/hello"), HttpMethod.PUT)) - .isEqualTo("Hello World"); - assertThat(getResponse(getLocalUrl("/bang"), HttpMethod.PUT)) - .isEqualTo("Hello World"); + assertThat(getResponse(getLocalUrl("/hello"), HttpMethod.PUT)).isEqualTo("Hello World"); + assertThat(getResponse(getLocalUrl("/bang"), HttpMethod.PUT)).isEqualTo("Hello World"); } @Test @@ -381,36 +367,27 @@ public abstract class AbstractServletWebServerFactoryTests { Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false); factory.setSsl(ssl); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThatExceptionOfType(SSLException.class).isThrownBy( - () -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThatExceptionOfType(SSLException.class) + .isThrownBy(() -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); } @Test public void sslGetScheme() throws Exception { // gh-2232 AbstractServletWebServerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) - .contains("scheme=https"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https"); } @Test @@ -422,12 +399,10 @@ public abstract class AbstractServletWebServerFactoryTests { new ExampleServlet(true, false), "/hello"); this.webServer = factory.getWebServer(registration); this.webServer.start(); - TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy( - "5c7ae101"); - SSLContext sslContext = new SSLContextBuilder() - .loadTrustMaterial(null, trustStrategy).build(); - HttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)).build(); + TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy("5c7ae101"); + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) + .build(); String response = getResponse(getLocalUrl("https", "/hello"), new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response).contains("scheme=https"); @@ -437,16 +412,13 @@ public abstract class AbstractServletWebServerFactoryTests { public void serverHeaderIsDisabledByDefaultWhenUsingSsl() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), - HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, + new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response.getHeaders().get("Server")).isNullOrEmpty(); } @@ -455,16 +427,13 @@ public abstract class AbstractServletWebServerFactoryTests { AbstractServletWebServerFactory factory = getFactory(); factory.setServerHeader("MyServer"); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), - HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, + new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response.getHeaders().get("Server")).containsExactly("MyServer"); } @@ -475,127 +444,91 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test public void pkcs12KeyStoreAndTrustStore() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", - "classpath:test.p12", null, null)); + factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", "classpath:test.p12", null, null)); this.webServer = factory.getWebServer(); this.webServer.start(); KeyStore keyStore = KeyStore.getInstance("pkcs12"); - keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), - "secret".toCharArray()); + keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "secret".toCharArray(), - (aliases, socket) -> "spring-boot") - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "secret".toCharArray(), (aliases, socket) -> "spring-boot").build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test - public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() - throws Exception { + public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", - "classpath:test.jks", null, null)); + factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null)); this.webServer = factory.getWebServer(); this.webServer.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray(), - (aliases, socket) -> "spring-boot") - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); + SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "password".toCharArray(), (aliases, socket) -> "spring-boot").build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test - public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() - throws Exception { + public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks")); this.webServer = factory.getWebServer(); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); String localUrl = getLocalUrl("https", "/test.txt"); assertThatIOException().isThrownBy(() -> getResponse(localUrl, requestFactory)); } @Test - public void sslWantsClientAuthenticationSucceedsWithClientCertificate() - throws Exception { + public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks", null, - new String[] { "TLSv1.2" }, null)); + factory.setSsl( + getSsl(ClientAuth.WANT, "password", "classpath:test.jks", null, new String[] { "TLSv1.2" }, null)); this.webServer = factory.getWebServer(); this.webServer.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); + keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test - public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() - throws Exception { + public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.webServer = factory.getWebServer(); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test @@ -613,20 +546,13 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); this.webServer.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray(), - (aliases, socket) -> "spring-boot") - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); + SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "password".toCharArray(), (aliases, socket) -> "spring-boot").build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); verify(sslStoreProvider, atLeastOnce()).getKeyStore(); verify(sslStoreProvider, atLeastOnce()).getTrustStore(); } @@ -653,20 +579,17 @@ public abstract class AbstractServletWebServerFactoryTests { return getSsl(clientAuth, keyPassword, keyStore, null, null, null); } - private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, - String keyStore) { + private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, String keyStore) { return getSsl(clientAuth, keyPassword, keyAlias, keyStore, null, null, null); } - private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyStore, - String trustStore, String[] supportedProtocols, String[] ciphers) { - return getSsl(clientAuth, keyPassword, null, keyStore, trustStore, - supportedProtocols, ciphers); + private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyStore, String trustStore, + String[] supportedProtocols, String[] ciphers) { + return getSsl(clientAuth, keyPassword, null, keyStore, trustStore, supportedProtocols, ciphers); } - private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, - String keyStore, String trustStore, String[] supportedProtocols, - String[] ciphers) { + private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, String keyStore, String trustStore, + String[] supportedProtocols, String[] ciphers) { Ssl ssl = new Ssl(); ssl.setClientAuth(clientAuth); if (keyPassword != null) { @@ -694,23 +617,16 @@ public abstract class AbstractServletWebServerFactoryTests { return ssl; } - protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, - String[] ciphers) throws Exception { + protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers) throws Exception { AbstractServletWebServerFactory factory = getFactory(); - factory.setSsl(getSsl(null, "password", "src/test/resources/restricted.jks", null, - protocols, ciphers)); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + factory.setSsl(getSsl(null, "password", "src/test/resources/restricted.jks", null, protocols, ciphers)); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) - .contains("scheme=https"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https"); } private String getStoreType(String keyStore) { @@ -719,8 +635,7 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void defaultSessionTimeout() { - assertThat(getFactory().getSession().getTimeout()) - .isEqualTo(Duration.ofMinutes(30)); + assertThat(getFactory().getSession().getTimeout()).isEqualTo(Duration.ofMinutes(30)); } @Test @@ -750,8 +665,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); getResponse(getLocalUrl("/session")); this.webServer.stop(); - File[] dirContents = sessionStoreDir - .listFiles((dir, name) -> !(".".equals(name) || "..".equals(name))); + File[] dirContents = sessionStoreDir.listFiles((dir, name) -> !(".".equals(name) || "..".equals(name))); assertThat(dirContents.length).isGreaterThan(0); } @@ -776,8 +690,7 @@ public abstract class AbstractServletWebServerFactoryTests { public void getValidSessionStoreWhenSessionStoreReferencesFile() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().setStoreDir(this.temporaryFolder.newFile()); - assertThatIllegalStateException() - .isThrownBy(() -> factory.getValidSessionStoreDir(false)) + assertThatIllegalStateException().isThrownBy(() -> factory.getValidSessionStoreDir(false)) .withMessageContaining("points to a file"); } @@ -792,8 +705,7 @@ public abstract class AbstractServletWebServerFactoryTests { factory.getSession().getCookie().setSecure(true); factory.getSession().getCookie().setMaxAge(Duration.ofSeconds(60)); final AtomicReference configReference = new AtomicReference<>(); - this.webServer = factory.getWebServer( - (context) -> configReference.set(context.getSessionCookieConfig())); + this.webServer = factory.getWebServer((context) -> configReference.set(context.getSessionCookieConfig())); SessionCookieConfig sessionCookieConfig = configReference.get(); assertThat(sessionCookieConfig.getName()).isEqualTo("testname"); assertThat(sessionCookieConfig.getDomain()).isEqualTo("testdomain"); @@ -842,8 +754,7 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void noCompressionForUserAgent() throws Exception { - assertThat(doTestCompression(10000, null, new String[] { "testUserAgent" })) - .isFalse(); + assertThat(doTestCompression(10000, null, new String[] { "testUserAgent" })).isFalse(); } @Test @@ -852,15 +763,13 @@ public abstract class AbstractServletWebServerFactoryTests { Compression compression = new Compression(); compression.setEnabled(true); factory.setCompression(compression); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(false, true), "/hello")); + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(false, true), "/hello")); this.webServer.start(); TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); - Map contentDecoderMap = Collections - .singletonMap("gzip", (InputStreamFactory) inputStreamFactory); - getResponse(getLocalUrl("/hello"), - new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() - .setContentDecoderRegistry(contentDecoderMap).build())); + Map contentDecoderMap = Collections.singletonMap("gzip", + (InputStreamFactory) inputStreamFactory); + getResponse(getLocalUrl("/hello"), new HttpComponentsClientHttpRequestFactory( + HttpClientBuilder.create().setContentDecoderRegistry(contentDecoderMap).build())); assertThat(inputStreamFactory.wasCompressionUsed()).isTrue(); } @@ -870,11 +779,10 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); Map configuredMimeMappings = getActualMimeMappings(); Collection expectedMimeMappings = getExpectedMimeMappings(); - configuredMimeMappings.forEach((key, value) -> assertThat(expectedMimeMappings) - .contains(new MimeMappings.Mapping(key, value))); + configuredMimeMappings.forEach( + (key, value) -> assertThat(expectedMimeMappings).contains(new MimeMappings.Mapping(key, value))); for (MimeMappings.Mapping mapping : expectedMimeMappings) { - assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), - mapping.getMimeType()); + assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), mapping.getMimeType()); } assertThat(configuredMimeMappings.size()).isEqualTo(expectedMimeMappings.size()); } @@ -915,28 +823,24 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void portClashOfPrimaryConnectorResultsInPortInUseException() - throws IOException { + public void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { AbstractServletWebServerFactory factory = getFactory(); factory.setPort(port); - AbstractServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); + AbstractServletWebServerFactoryTests.this.webServer = factory.getWebServer(); AbstractServletWebServerFactoryTests.this.webServer.start(); }).satisfies((ex) -> handleExceptionCausedByBlockedPort(ex, port)); }); } @Test - public void portClashOfSecondaryConnectorResultsInPortInUseException() - throws IOException { + public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { AbstractServletWebServerFactory factory = getFactory(); addConnector(port, factory); - AbstractServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); + AbstractServletWebServerFactoryTests.this.webServer = factory.getWebServer(); AbstractServletWebServerFactoryTests.this.webServer.start(); }).satisfies((ex) -> handleExceptionCausedByBlockedPort(ex, port)); }); @@ -971,43 +875,39 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); Assume.assumeThat(getJspServlet(), notNullValue()); JspServlet jspServlet = getJspServlet(); - EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils - .getField(jspServlet, "options"); + EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils.getField(jspServlet, "options"); assertThat(options.getDevelopment()).isFalse(); } @Test public void faultyFilterCausesStartFailure() { AbstractServletWebServerFactory factory = getFactory(); - factory.addInitializers( - (servletContext) -> servletContext.addFilter("faulty", new Filter() { + factory.addInitializers((servletContext) -> servletContext.addFilter("faulty", new Filter() { - @Override - public void init(FilterConfig filterConfig) throws ServletException { - throw new ServletException("Faulty filter"); - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + throw new ServletException("Faulty filter"); + } - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - chain.doFilter(request, response); - } + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + chain.doFilter(request, response); + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } - })); - assertThatExceptionOfType(WebServerException.class) - .isThrownBy(() -> factory.getWebServer().start()); + })); + assertThatExceptionOfType(WebServerException.class).isThrownBy(() -> factory.getWebServer().start()); } @Test public void sessionConfiguration() { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(Duration.ofSeconds(123)); - factory.getSession().setTrackingModes( - EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)); + factory.getSession().setTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)); factory.getSession().getCookie().setName("testname"); factory.getSession().getCookie().setDomain("testdomain"); factory.getSession().getCookie().setPath("/testpath"); @@ -1019,27 +919,20 @@ public abstract class AbstractServletWebServerFactoryTests { factory.getWebServer(contextReference::set).start(); ServletContext servletContext = contextReference.get(); assertThat(servletContext.getEffectiveSessionTrackingModes()) - .isEqualTo(EnumSet.of(javax.servlet.SessionTrackingMode.COOKIE, - javax.servlet.SessionTrackingMode.URL)); - assertThat(servletContext.getSessionCookieConfig().getName()) - .isEqualTo("testname"); - assertThat(servletContext.getSessionCookieConfig().getDomain()) - .isEqualTo("testdomain"); - assertThat(servletContext.getSessionCookieConfig().getPath()) - .isEqualTo("/testpath"); - assertThat(servletContext.getSessionCookieConfig().getComment()) - .isEqualTo("testcomment"); + .isEqualTo(EnumSet.of(javax.servlet.SessionTrackingMode.COOKIE, javax.servlet.SessionTrackingMode.URL)); + assertThat(servletContext.getSessionCookieConfig().getName()).isEqualTo("testname"); + assertThat(servletContext.getSessionCookieConfig().getDomain()).isEqualTo("testdomain"); + assertThat(servletContext.getSessionCookieConfig().getPath()).isEqualTo("/testpath"); + assertThat(servletContext.getSessionCookieConfig().getComment()).isEqualTo("testcomment"); assertThat(servletContext.getSessionCookieConfig().isHttpOnly()).isTrue(); assertThat(servletContext.getSessionCookieConfig().isSecure()).isTrue(); assertThat(servletContext.getSessionCookieConfig().getMaxAge()).isEqualTo(60); } @Test - public void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() - throws Exception { + public void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() throws Exception { ServletContextListener listener = mock(ServletContextListener.class); - this.webServer = getFactory() - .getWebServer((servletContext) -> servletContext.addListener(listener)); + this.webServer = getFactory().getWebServer((servletContext) -> servletContext.addListener(listener)); this.webServer.start(); this.webServer.stop(); verify(listener).contextDestroyed(any(ServletContextEvent.class)); @@ -1048,10 +941,9 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void exceptionThrownOnLoadFailureIsRethrown() { AbstractServletWebServerFactory factory = getFactory(); - this.webServer = factory.getWebServer((context) -> context - .addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); - assertThatExceptionOfType(WebServerException.class) - .isThrownBy(this.webServer::start) + this.webServer = factory + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + assertThatExceptionOfType(WebServerException.class).isThrownBy(this.webServer::start) .satisfies(this::wrapsFailingServletException); } @@ -1066,35 +958,29 @@ public abstract class AbstractServletWebServerFactoryTests { fail("Exception did not wrap FailingServletException"); } - protected abstract void addConnector(int port, - AbstractServletWebServerFactory factory); + protected abstract void addConnector(int port, AbstractServletWebServerFactory factory); - protected abstract void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort); + protected abstract void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort); - private boolean doTestCompression(int contentSize, String[] mimeTypes, - String[] excludedUserAgents) throws Exception { - return doTestCompression(contentSize, mimeTypes, excludedUserAgents, - HttpMethod.GET); + private boolean doTestCompression(int contentSize, String[] mimeTypes, String[] excludedUserAgents) + throws Exception { + return doTestCompression(contentSize, mimeTypes, excludedUserAgents, HttpMethod.GET); } - private boolean doTestCompression(int contentSize, String[] mimeTypes, - String[] excludedUserAgents, HttpMethod method) throws Exception { - String testContent = setUpFactoryForCompression(contentSize, mimeTypes, - excludedUserAgents); + private boolean doTestCompression(int contentSize, String[] mimeTypes, String[] excludedUserAgents, + HttpMethod method) throws Exception { + String testContent = setUpFactoryForCompression(contentSize, mimeTypes, excludedUserAgents); TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); - Map contentDecoderMap = Collections - .singletonMap("gzip", (InputStreamFactory) inputStreamFactory); + Map contentDecoderMap = Collections.singletonMap("gzip", + (InputStreamFactory) inputStreamFactory); String response = getResponse(getLocalUrl("/test.txt"), method, - new HttpComponentsClientHttpRequestFactory( - HttpClientBuilder.create().setUserAgent("testUserAgent") - .setContentDecoderRegistry(contentDecoderMap).build())); + new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().setUserAgent("testUserAgent") + .setContentDecoderRegistry(contentDecoderMap).build())); assertThat(response).isEqualTo(testContent); return inputStreamFactory.wasCompressionUsed(); } - private String setUpFactoryForCompression(int contentSize, String[] mimeTypes, - String[] excludedUserAgents) { + private String setUpFactoryForCompression(int contentSize, String[] mimeTypes, String[] excludedUserAgents) { char[] chars = new char[contentSize]; Arrays.fill(chars, 'F'); String testContent = new String(chars); @@ -1108,19 +994,17 @@ public abstract class AbstractServletWebServerFactoryTests { compression.setExcludedUserAgents(excludedUserAgents); } factory.setCompression(compression); - factory.addInitializers( - new ServletRegistrationBean(new HttpServlet() { + factory.addInitializers(new ServletRegistrationBean(new HttpServlet() { - @Override - protected void service(HttpServletRequest req, - HttpServletResponse resp) throws IOException { - resp.setContentType("text/plain"); - resp.setContentLength(testContent.length()); - resp.getWriter().write(testContent); - resp.getWriter().flush(); - } + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("text/plain"); + resp.setContentLength(testContent.length()); + resp.getWriter().write(testContent); + resp.getWriter().flush(); + } - }, "/test.txt")); + }, "/test.txt")); this.webServer = factory.getWebServer(); this.webServer.start(); return testContent; @@ -1134,10 +1018,8 @@ public abstract class AbstractServletWebServerFactoryTests { protected abstract Charset getCharset(Locale locale); - private void addTestTxtFile(AbstractServletWebServerFactory factory) - throws IOException { - FileCopyUtils.copy("test", - new FileWriter(this.temporaryFolder.newFile("test.txt"))); + private void addTestTxtFile(AbstractServletWebServerFactory factory) throws IOException { + FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.txt"))); factory.setDocumentRoot(this.temporaryFolder.getRoot()); } @@ -1153,8 +1035,7 @@ public abstract class AbstractServletWebServerFactoryTests { return "http://localhost:" + port + resourcePath; } - protected String getResponse(String url, String... headers) - throws IOException, URISyntaxException { + protected String getResponse(String url, String... headers) throws IOException, URISyntaxException { return getResponse(url, HttpMethod.GET, headers); } @@ -1165,17 +1046,14 @@ public abstract class AbstractServletWebServerFactoryTests { } } - protected String getResponse(String url, - HttpComponentsClientHttpRequestFactory requestFactory, String... headers) + protected String getResponse(String url, HttpComponentsClientHttpRequestFactory requestFactory, String... headers) throws IOException, URISyntaxException { return getResponse(url, HttpMethod.GET, requestFactory, headers); } - protected String getResponse(String url, HttpMethod method, - HttpComponentsClientHttpRequestFactory requestFactory, String... headers) - throws IOException, URISyntaxException { - try (ClientHttpResponse response = getClientResponse(url, method, requestFactory, - headers)) { + protected String getResponse(String url, HttpMethod method, HttpComponentsClientHttpRequestFactory requestFactory, + String... headers) throws IOException, URISyntaxException { + try (ClientHttpResponse response = getClientResponse(url, method, requestFactory, headers)) { return StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8); } } @@ -1185,18 +1063,16 @@ public abstract class AbstractServletWebServerFactoryTests { return getClientResponse(url, HttpMethod.GET, headers); } - protected ClientHttpResponse getClientResponse(String url, HttpMethod method, - String... headers) throws IOException, URISyntaxException { - return getClientResponse(url, method, - new HttpComponentsClientHttpRequestFactory() { + protected ClientHttpResponse getClientResponse(String url, HttpMethod method, String... headers) + throws IOException, URISyntaxException { + return getClientResponse(url, method, new HttpComponentsClientHttpRequestFactory() { - @Override - protected HttpContext createHttpContext(HttpMethod httpMethod, - URI uri) { - return AbstractServletWebServerFactoryTests.this.httpClientContext; - } + @Override + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return AbstractServletWebServerFactoryTests.this.httpClientContext; + } - }, headers); + }, headers); } protected ClientHttpResponse getClientResponse(String url, HttpMethod method, @@ -1212,10 +1088,8 @@ public abstract class AbstractServletWebServerFactoryTests { return response; } - protected void assertForwardHeaderIsUsed(ServletWebServerFactory factory) - throws IOException, URISyntaxException { - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + protected void assertForwardHeaderIsUsed(ServletWebServerFactory factory) throws IOException, URISyntaxException { + this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); assertThat(getResponse(getLocalUrl("/hello"), "X-Forwarded-For:140.211.11.130")) .contains("remoteaddr=140.211.11.130"); @@ -1223,8 +1097,7 @@ public abstract class AbstractServletWebServerFactoryTests { protected abstract AbstractServletWebServerFactory getFactory(); - protected abstract org.apache.jasper.servlet.JspServlet getJspServlet() - throws Exception; + protected abstract org.apache.jasper.servlet.JspServlet getJspServlet() throws Exception; protected ServletContextInitializer exampleServletRegistration() { return new ServletRegistrationBean<>(new ExampleServlet(), "/hello"); @@ -1232,38 +1105,32 @@ public abstract class AbstractServletWebServerFactoryTests { @SuppressWarnings("serial") private ServletContextInitializer errorServletRegistration() { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - new ExampleServlet() { + ServletRegistrationBean bean = new ServletRegistrationBean<>(new ExampleServlet() { - @Override - public void service(ServletRequest request, - ServletResponse response) { - throw new RuntimeException("Planned"); - } + @Override + public void service(ServletRequest request, ServletResponse response) { + throw new RuntimeException("Planned"); + } - }, "/bang"); + }, "/bang"); bean.setName("error"); return bean; } protected final ServletContextInitializer sessionServletRegistration() { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - new ExampleServlet() { + ServletRegistrationBean bean = new ServletRegistrationBean<>(new ExampleServlet() { - @Override - public void service(ServletRequest request, ServletResponse response) - throws IOException { - HttpSession session = ((HttpServletRequest) request) - .getSession(true); - long value = System.currentTimeMillis(); - Object existing = session.getAttribute("boot"); - session.setAttribute("boot", value); - PrintWriter writer = response.getWriter(); - writer.append(String.valueOf(existing)).append(":") - .append(String.valueOf(value)); - } + @Override + public void service(ServletRequest request, ServletResponse response) throws IOException { + HttpSession session = ((HttpServletRequest) request).getSession(true); + long value = System.currentTimeMillis(); + Object existing = session.getAttribute("boot"); + session.setAttribute("boot", value); + PrintWriter writer = response.getWriter(); + writer.append(String.valueOf(existing)).append(":").append(String.valueOf(value)); + } - }, "/session"); + }, "/session"); bean.setName("session"); return bean; } @@ -1287,8 +1154,7 @@ public abstract class AbstractServletWebServerFactoryTests { } } - private KeyStore loadStore() throws KeyStoreException, IOException, - NoSuchAlgorithmException, CertificateException { + private KeyStore loadStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); Resource resource = new ClassPathResource("test.jks"); try (InputStream inputStream = resource.getInputStream()) { @@ -1304,8 +1170,7 @@ public abstract class AbstractServletWebServerFactoryTests { @Override public InputStream create(InputStream in) throws IOException { if (this.requested.get()) { - throw new IllegalStateException( - "On deflated InputStream already requested"); + throw new IllegalStateException("On deflated InputStream already requested"); } this.requested.set(true); return new GZIPInputStream(in); @@ -1346,8 +1211,7 @@ public abstract class AbstractServletWebServerFactoryTests { /** * {@link TrustSelfSignedStrategy} that also validates certificate serial number. */ - private static final class SerialNumberValidatingTrustSelfSignedStrategy - extends TrustSelfSignedStrategy { + private static final class SerialNumberValidatingTrustSelfSignedStrategy extends TrustSelfSignedStrategy { private final String serialNumber; @@ -1356,8 +1220,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Override - public boolean isTrusted(X509Certificate[] chain, String authType) - throws CertificateException { + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { String hexSerialNumber = chain[0].getSerialNumber().toString(16); boolean isMatch = hexSerialNumber.equals(this.serialNumber); return super.isTrusted(chain, authType) && isMatch; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java index 7d0f726acd6..4de37f5536e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,11 +42,9 @@ public class DocumentRootTests { @Test public void explodedWarFileDocumentRootWhenRunningFromExplodedWar() throws Exception { - File webInfClasses = this.temporaryFolder.newFolder("test.war", "WEB-INF", "lib", - "spring-boot.jar"); + File webInfClasses = this.temporaryFolder.newFolder("test.war", "WEB-INF", "lib", "spring-boot.jar"); File directory = this.documentRoot.getExplodedWarFileDocumentRoot(webInfClasses); - assertThat(directory) - .isEqualTo(webInfClasses.getParentFile().getParentFile().getParentFile()); + assertThat(directory).isEqualTo(webInfClasses.getParentFile().getParentFile().getParentFile()); } @Test @@ -58,16 +56,14 @@ public class DocumentRootTests { @Test public void codeSourceArchivePath() throws Exception { - CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), - (Certificate[]) null); + CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), (Certificate[]) null); File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/some/test/path/")); } @Test public void codeSourceArchivePathContainingSpaces() throws Exception { - CodeSource codeSource = new CodeSource( - new URL("file", "", "/test/path/with%20space/"), (Certificate[]) null); + CodeSource codeSource = new CodeSource(new URL("file", "", "/test/path/with%20space/"), (Certificate[]) null); File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/test/path/with space/")); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java index 5c17796fe06..91aed35c62a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory @Override public WebServer getWebServer(ServletContextInitializer... initializers) { - this.webServer = spy( - new MockServletWebServer(mergeInitializers(initializers), getPort())); + this.webServer = spy(new MockServletWebServer(mergeInitializers(initializers), getPort())); return this.webServer; } @@ -54,22 +53,18 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory } public RegisteredServlet getRegisteredServlet(int index) { - return (getWebServer() != null) ? getWebServer().getRegisteredServlet(index) - : null; + return (getWebServer() != null) ? getWebServer().getRegisteredServlet(index) : null; } public RegisteredFilter getRegisteredFilter(int index) { - return (getWebServer() != null) ? getWebServer().getRegisteredFilters(index) - : null; + return (getWebServer() != null) ? getWebServer().getRegisteredFilters(index) : null; } public static class MockServletWebServer - extends org.springframework.boot.testsupport.web.servlet.MockServletWebServer - implements WebServer { + extends org.springframework.boot.testsupport.web.servlet.MockServletWebServer implements WebServer { public MockServletWebServer(ServletContextInitializer[] initializers, int port) { - super(Arrays.stream(initializers) - .map((initializer) -> (Initializer) initializer::onStartup) + super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup) .toArray(Initializer[]::new), port); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java index ac9fe25091d..f63ba3e1185 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,40 +45,36 @@ public class StaticResourceJarsTests { @Test public void includeJarWithStaticResources() throws Exception { File jarFile = createResourcesJar("test-resources.jar"); - List staticResourceJarUrls = new StaticResourceJars() - .getUrlsFrom(jarFile.toURI().toURL()); + List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(1); } @Test public void includeJarWithStaticResourcesWithUrlEncodedSpaces() throws Exception { File jarFile = createResourcesJar("test resources.jar"); - List staticResourceJarUrls = new StaticResourceJars() - .getUrlsFrom(jarFile.toURI().toURL()); + List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(1); } @Test public void includeJarWithStaticResourcesWithPlusInItsPath() throws Exception { File jarFile = createResourcesJar("test + resources.jar"); - List staticResourceJarUrls = new StaticResourceJars() - .getUrlsFrom(jarFile.toURI().toURL()); + List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(1); } @Test public void excludeJarWithoutStaticResources() throws Exception { File jarFile = createJar("dependency.jar"); - List staticResourceJarUrls = new StaticResourceJars() - .getUrlsFrom(jarFile.toURI().toURL()); + List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(0); } @Test public void uncPathsAreTolerated() throws Exception { File jarFile = createResourcesJar("test-resources.jar"); - List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom( - jarFile.toURI().toURL(), new URL("file://unc.example.com/test.jar")); + List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL(), + new URL("file://unc.example.com/test.jar")); assertThat(staticResourceJarUrls).hasSize(1); } @@ -99,11 +95,9 @@ public class StaticResourceJarsTests { return createJar(name, null); } - private File createJar(String name, Consumer customizer) - throws IOException { + private File createJar(String name, Consumer customizer) throws IOException { File jarFile = this.temporaryFolder.newFile(name); - JarOutputStream jarOutputStream = new JarOutputStream( - new FileOutputStream(jarFile)); + JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(jarFile)); if (customizer != null) { customizer.accept(jarOutputStream); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java index 7cb3a938ba3..b876f0b3ebc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java @@ -92,12 +92,12 @@ public class ErrorPageFilterIntegrationTests { assertThat(this.controller.getStatus()).isEqualTo(200); } - private void doTest(AnnotationConfigServletWebServerApplicationContext context, - String resourcePath, HttpStatus status) throws Exception { + private void doTest(AnnotationConfigServletWebServerApplicationContext context, String resourcePath, + HttpStatus status) throws Exception { int port = context.getWebServer().getPort(); RestTemplate template = new RestTemplate(); - ResponseEntity entity = template.getForEntity( - new URI("http://localhost:" + port + resourcePath), String.class); + ResponseEntity entity = template.getForEntity(new URI("http://localhost:" + port + resourcePath), + String.class); assertThat(entity.getBody()).isEqualTo("Hello World"); assertThat(entity.getStatusCode()).isEqualTo(status); } @@ -136,8 +136,7 @@ public class ErrorPageFilterIntegrationTests { private CountDownLatch latch = new CountDownLatch(1); public int getStatus() throws InterruptedException { - assertThat(this.latch.await(1, TimeUnit.SECONDS)) - .as("Timed out waiting for latch").isTrue(); + assertThat(this.latch.await(1, TimeUnit.SECONDS)).as("Timed out waiting for latch").isTrue(); return this.status; } @@ -154,8 +153,7 @@ public class ErrorPageFilterIntegrationTests { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptorAdapter() { @Override - public void postHandle(HttpServletRequest request, - HttpServletResponse response, Object handler, + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { HelloWorldController.this.setStatus(response.getStatus()); HelloWorldController.this.latch.countDown(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java index 9226f38727c..2b1418c33ff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,8 +78,7 @@ public class ErrorPageFilterTests { public void notAnError() throws Exception { this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isNull(); } @@ -92,22 +91,19 @@ public class ErrorPageFilterTests { response.flushBuffer(); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()) - .isEqualTo(201); - assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain - .getResponse()).getResponse()).getStatus()).isEqualTo(201); + assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()).isEqualTo(201); + assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .getStatus()).isEqualTo(201); assertThat(this.response.isCommitted()).isTrue(); } @Test public void unauthorizedWithErrorPath() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); - this.chain = new TestFilterChain( - (request, response, chain) -> response.sendError(401, "UNAUTHORIZED")); + this.chain = new TestFilterChain((request, response, chain) -> response.sendError(401, "UNAUTHORIZED")); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain - .getResponse(); + HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain.getResponse(); assertThat(wrapper.getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); assertThat(wrapper.getStatus()).isEqualTo(401); @@ -120,14 +116,11 @@ public class ErrorPageFilterTests { public void responseCommitted() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.response.setCommitted(true); - this.chain = new TestFilterChain( - (request, response, chain) -> response.sendError(400, "BAD")); + this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); assertThat(this.response.getForwardedUrl()).isNull(); assertThat(this.response.isCommitted()).isTrue(); } @@ -147,14 +140,11 @@ public class ErrorPageFilterTests { @Test public void responseUncommittedWithoutErrorPage() throws Exception { - this.chain = new TestFilterChain( - (request, response, chain) -> response.sendError(400, "BAD")); + this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); assertThat(this.response.getForwardedUrl()).isNull(); assertThat(this.response.isCommitted()).isTrue(); } @@ -172,17 +162,12 @@ public class ErrorPageFilterTests { @Test public void globalError() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); - this.chain = new TestFilterChain( - (request, response, chain) -> response.sendError(400, "BAD")); + this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/error"); } @@ -190,17 +175,12 @@ public class ErrorPageFilterTests { @Test public void statusError() throws Exception { this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - this.chain = new TestFilterChain( - (request, response, chain) -> response.sendError(400, "BAD")); + this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/400"); } @@ -213,8 +193,7 @@ public class ErrorPageFilterTests { response.flushBuffer(); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isNull(); } @@ -227,22 +206,15 @@ public class ErrorPageFilterTests { throw new RuntimeException("BAD"); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map requestAttributes = getAttributesForDispatch("/500"); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isEqualTo(RuntimeException.class); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(RuntimeException.class); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isNull(); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isEqualTo(RuntimeException.class); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(RuntimeException.class); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); } @@ -261,11 +233,9 @@ public class ErrorPageFilterTests { @Test public void statusCode() throws Exception { - this.chain = new TestFilterChain((request, response, - chain) -> assertThat(response.getStatus()).isEqualTo(200)); + this.chain = new TestFilterChain((request, response, chain) -> assertThat(response.getStatus()).isEqualTo(200)); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(200); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(200); } @Test @@ -276,22 +246,16 @@ public class ErrorPageFilterTests { throw new IllegalStateException("BAD"); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map requestAttributes = getAttributesForDispatch("/500"); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) .isEqualTo(IllegalStateException.class); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(IllegalStateException.class); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isNull(); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(IllegalStateException.class); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); } @@ -300,14 +264,12 @@ public class ErrorPageFilterTests { this.request.setAsyncStarted(true); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isFalse(); } @Test - public void responseIsCommittedWhenRequestIsAsyncAndExceptionIsThrown() - throws Exception { + public void responseIsCommittedWhenRequestIsAsyncAndExceptionIsThrown() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.request.setAsyncStarted(true); this.chain = new TestFilterChain((request, response, chain) -> { @@ -316,14 +278,12 @@ public class ErrorPageFilterTests { }); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @Test - public void responseIsCommittedWhenRequestIsAsyncAndStatusIs400Plus() - throws Exception { + public void responseIsCommittedWhenRequestIsAsyncAndStatusIs400Plus() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.request.setAsyncStarted(true); this.chain = new TestFilterChain((request, response, chain) -> { @@ -332,8 +292,7 @@ public class ErrorPageFilterTests { }); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @@ -342,14 +301,12 @@ public class ErrorPageFilterTests { setUpAsyncDispatch(); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isFalse(); } @Test - public void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() - throws Exception { + public void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new TestFilterChain((request, response, chain) -> { @@ -358,14 +315,12 @@ public class ErrorPageFilterTests { }); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @Test - public void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() - throws Exception { + public void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new TestFilterChain((request, response, chain) -> { @@ -374,14 +329,12 @@ public class ErrorPageFilterTests { }); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @Test - public void responseIsNotFlushedIfStatusIsLessThan400AndItHasAlreadyBeenCommitted() - throws Exception { + public void responseIsNotFlushedIfStatusIsLessThan400AndItHasAlreadyBeenCommitted() throws Exception { HttpServletResponse committedResponse = mock(HttpServletResponse.class); given(committedResponse.isCommitted()).willReturn(true); given(committedResponse.getStatus()).willReturn(200); @@ -390,8 +343,7 @@ public class ErrorPageFilterTests { } @Test - public void errorMessageForRequestWithoutPathInfo() - throws IOException, ServletException { + public void errorMessageForRequestWithoutPathInfo() throws IOException, ServletException { this.request.setServletPath("/test"); this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new TestFilterChain((request, response, chain) -> { @@ -403,8 +355,7 @@ public class ErrorPageFilterTests { } @Test - public void errorMessageForRequestWithPathInfo() - throws IOException, ServletException { + public void errorMessageForRequestWithPathInfo() throws IOException, ServletException { this.request.setServletPath("/test"); this.request.setPathInfo("/alpha"); this.filter.addErrorPages(new ErrorPage("/error")); @@ -424,29 +375,21 @@ public class ErrorPageFilterTests { throw new NestedServletException("Wrapper", new RuntimeException("BAD")); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map requestAttributes = getAttributesForDispatch("/500"); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isEqualTo(RuntimeException.class); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(RuntimeException.class); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isNull(); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isEqualTo(RuntimeException.class); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(RuntimeException.class); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); } @Test - public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() - throws Exception { + public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() throws Exception { this.chain = new TestFilterChain((request, response, chain) -> { response.sendError(400); response.getWriter().flush(); @@ -460,8 +403,7 @@ public class ErrorPageFilterTests { this.request.setAsyncStarted(true); DeferredResult result = new DeferredResult<>(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); - asyncManager.setAsyncWebRequest( - new StandardServletAsyncWebRequest(this.request, this.response)); + asyncManager.setAsyncWebRequest(new StandardServletAsyncWebRequest(this.request, this.response)); asyncManager.startDeferredResultProcessing(result); } @@ -478,16 +420,14 @@ public class ErrorPageFilterTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { AtomicBoolean called = new AtomicBoolean(); Chain chain = () -> { if (called.compareAndSet(false, true)) { super.doFilter(request, response); } }; - this.handler.handle((HttpServletRequest) request, - (HttpServletResponse) response, chain); + this.handler.handle((HttpServletRequest) request, (HttpServletResponse) response, chain); chain.call(); } @@ -508,8 +448,7 @@ public class ErrorPageFilterTests { } - private static final class DispatchRecordingMockHttpServletRequest - extends MockHttpServletRequest { + private static final class DispatchRecordingMockHttpServletRequest extends MockHttpServletRequest { private final Map dispatchers = new HashMap<>(); @@ -519,8 +458,7 @@ public class ErrorPageFilterTests { @Override public RequestDispatcher getRequestDispatcher(String path) { - AttributeCapturingRequestDispatcher dispatcher = new AttributeCapturingRequestDispatcher( - path); + AttributeCapturingRequestDispatcher dispatcher = new AttributeCapturingRequestDispatcher(path); this.dispatchers.put(path, dispatcher); return dispatcher; } @@ -529,8 +467,7 @@ public class ErrorPageFilterTests { return this.dispatchers.get(path); } - private static final class AttributeCapturingRequestDispatcher - extends MockRequestDispatcher { + private static final class AttributeCapturingRequestDispatcher extends MockRequestDispatcher { private final Map requestAttributes = new HashMap<>(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java index c1c3ad87df2..ea00be7c98c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,31 +36,25 @@ public class ServletContextApplicationContextInitializerTests { private final ServletContext servletContext = mock(ServletContext.class); - private final ConfigurableWebApplicationContext applicationContext = mock( - ConfigurableWebApplicationContext.class); + private final ConfigurableWebApplicationContext applicationContext = mock(ConfigurableWebApplicationContext.class); @Test public void servletContextIsSetOnTheApplicationContext() { - new ServletContextApplicationContextInitializer(this.servletContext) - .initialize(this.applicationContext); + new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); verify(this.applicationContext).setServletContext(this.servletContext); } @Test public void applicationContextIsNotStoredInServletContextByDefault() { - new ServletContextApplicationContextInitializer(this.servletContext) - .initialize(this.applicationContext); - verify(this.servletContext, never()).setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); + verify(this.servletContext, never()).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } @Test public void applicationContextCanBeStoredInServletContext() { - new ServletContextApplicationContextInitializer(this.servletContext, true) - .initialize(this.applicationContext); - verify(this.servletContext).setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + new ServletContextApplicationContextInitializer(this.servletContext, true).initialize(this.applicationContext); + verify(this.servletContext).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java index ce4cc2410f1..bb7d8a85102 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java @@ -63,31 +63,28 @@ public class SpringBootServletInitializerTests { @After public void verifyLoggingOutput() { - assertThat(this.output.toString()) - .doesNotContain(StandardServletEnvironment.class.getSimpleName()); + assertThat(this.output.toString()).doesNotContain(StandardServletEnvironment.class.getSimpleName()); } @Test public void failsWithoutConfigure() { assertThatIllegalStateException() - .isThrownBy(() -> new MockSpringBootServletInitializer() - .createRootApplicationContext(this.servletContext)) + .isThrownBy( + () -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext)) .withMessageContaining("No SpringApplication sources have been defined"); } @Test public void withConfigurationAnnotation() { - new WithConfigurationAnnotation() - .createRootApplicationContext(this.servletContext); - assertThat(this.application.getAllSources()).containsOnly( - WithConfigurationAnnotation.class, ErrorPageFilterConfiguration.class); + new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); + assertThat(this.application.getAllSources()).containsOnly(WithConfigurationAnnotation.class, + ErrorPageFilterConfiguration.class); } @Test public void withConfiguredSource() { new WithConfiguredSource().createRootApplicationContext(this.servletContext); - assertThat(this.application.getAllSources()).containsOnly(Config.class, - ErrorPageFilterConfiguration.class); + assertThat(this.application.getAllSources()).containsOnly(Config.class, ErrorPageFilterConfiguration.class); } @Test @@ -99,22 +96,19 @@ public class SpringBootServletInitializerTests { @Test public void mainClassHasSensibleDefault() { - new WithConfigurationAnnotation() - .createRootApplicationContext(this.servletContext); + new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); assertThat(this.application).hasFieldOrPropertyWithValue("mainApplicationClass", WithConfigurationAnnotation.class); } @Test public void errorPageFilterRegistrationCanBeDisabled() { - WebServer webServer = new UndertowServletWebServerFactory(0) - .getWebServer((servletContext) -> { - try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() - .createRootApplicationContext(servletContext)) { - assertThat(context.getBeansOfType(ErrorPageFilter.class)) - .hasSize(0); - } - }); + WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { + try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() + .createRootApplicationContext(servletContext)) { + assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); + } + }); try { webServer.start(); } @@ -125,8 +119,7 @@ public class SpringBootServletInitializerTests { @Test public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() { - try (ConfigurableApplicationContext context = new SpringApplication( - ExecutableWar.class).run()) { + try (ConfigurableApplicationContext context = new SpringApplication(ExecutableWar.class).run()) { assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); } } @@ -134,26 +127,21 @@ public class SpringBootServletInitializerTests { @Test public void servletContextPropertySourceIsAvailablePriorToRefresh() { ServletContext servletContext = mock(ServletContext.class); - given(servletContext.getInitParameterNames()).willReturn(Collections - .enumeration(Collections.singletonList("spring.profiles.active"))); - given(servletContext.getInitParameter("spring.profiles.active")) - .willReturn("from-servlet-context"); - given(servletContext.getAttributeNames()) - .willReturn(Collections.enumeration(Collections.emptyList())); + given(servletContext.getInitParameterNames()) + .willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active"))); + given(servletContext.getInitParameter("spring.profiles.active")).willReturn("from-servlet-context"); + given(servletContext.getAttributeNames()).willReturn(Collections.enumeration(Collections.emptyList())); try (ConfigurableApplicationContext context = (ConfigurableApplicationContext) new PropertySourceVerifyingSpringBootServletInitializer() .createRootApplicationContext(servletContext)) { - assertThat(context.getEnvironment().getActiveProfiles()) - .containsExactly("from-servlet-context"); + assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("from-servlet-context"); } } - private static class PropertySourceVerifyingSpringBootServletInitializer - extends SpringBootServletInitializer { + private static class PropertySourceVerifyingSpringBootServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return builder.sources(TestApp.class) - .listeners(new PropertySourceVerifyingApplicationListener()); + return builder.sources(TestApp.class).listeners(new PropertySourceVerifyingApplicationListener()); } } @@ -173,8 +161,7 @@ public class SpringBootServletInitializerTests { } - private class CustomSpringBootServletInitializer - extends MockSpringBootServletInitializer { + private class CustomSpringBootServletInitializer extends MockSpringBootServletInitializer { private final CustomSpringApplicationBuilder applicationBuilder = new CustomSpringApplicationBuilder(); @@ -184,8 +171,7 @@ public class SpringBootServletInitializerTests { } @Override - protected SpringApplicationBuilder configure( - SpringApplicationBuilder application) { + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Config.class); } @@ -199,16 +185,14 @@ public class SpringBootServletInitializerTests { public class WithConfiguredSource extends MockSpringBootServletInitializer { @Override - protected SpringApplicationBuilder configure( - SpringApplicationBuilder application) { + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Config.class); } } @Configuration(proxyBeanMethods = false) - public static class WithErrorPageFilterNotRegistered - extends SpringBootServletInitializer { + public static class WithErrorPageFilterNotRegistered extends SpringBootServletInitializer { public WithErrorPageFilterNotRegistered() { setRegisterErrorPageFilter(false); @@ -250,8 +234,7 @@ public class SpringBootServletInitializerTests { public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { PropertySource propertySource = event.getEnvironment().getPropertySources() .get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); - assertThat(propertySource.getProperty("spring.profiles.active")) - .isEqualTo("from-servlet-context"); + assertThat(propertySource.getProperty("spring.profiles.active")).isEqualTo("from-servlet-context"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java index a2839b58880..d4f226c04dd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ class TestFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { request.setAttribute("filterAttribute", "bravo"); chain.doFilter(request, response); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java index 45618fb30f7..ec18453df65 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java @@ -21,8 +21,7 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @WebServlet("/test-multipart") -@MultipartConfig(location = "test", maxFileSize = 1024, maxRequestSize = 2048, - fileSizeThreshold = 512) +@MultipartConfig(location = "test", maxFileSize = 1024, maxRequestSize = 2048, fileSizeThreshold = 512) public class TestMultipartServlet extends HttpServlet { } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java index 1be55fe4005..a7cc03cabe4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,11 +28,9 @@ import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - resp.getWriter().print( - ((String) req.getServletContext().getAttribute("listenerAttribute")) + " " - + req.getAttribute("filterAttribute")); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.getWriter().print(((String) req.getServletContext().getAttribute("listenerAttribute")) + " " + + req.getAttribute("filterAttribute")); resp.getWriter().flush(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java index eaa44fdb0a4..0fdedf45434 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MustacheViewResolverTests { - private final String prefix = "classpath:/" - + getClass().getPackage().getName().replace(".", "/") + "/"; + private final String prefix = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + "/"; private MustacheViewResolver resolver = new MustacheViewResolver(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java index d68db223bc4..98566d8a0a2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java @@ -37,8 +37,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MustacheViewTests { - private final String templateUrl = "classpath:/" - + getClass().getPackage().getName().replace(".", "/") + "/template.html"; + private final String templateUrl = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + + "/template.html"; private MockHttpServletRequest request = new MockHttpServletRequest(); @@ -51,9 +51,7 @@ public class MustacheViewTests { this.context.refresh(); MockServletContext servletContext = new MockServletContext(); this.context.setServletContext(servletContext); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); } @Test @@ -62,8 +60,7 @@ public class MustacheViewTests { view.setCompiler(Mustache.compiler()); view.setUrl(this.templateUrl); view.setApplicationContext(this.context); - view.render(Collections.singletonMap("World", "Spring"), this.request, - this.response); + view.render(Collections.singletonMap("World", "Spring"), this.request, this.response); assertThat(this.response.getContentAsString().trim()).isEqualTo("Hello Spring"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java index 0d493beb8d7..5d799cbab59 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,20 +52,16 @@ public class HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests { @Test public void buildWithCustomTimeouts() { - WebServiceMessageSender messageSender = this.builder - .setConnectTimeout(Duration.ofSeconds(5)) + WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(2)).build(); - OkHttp3ClientHttpRequestFactory factory = assertOkHttp3RequestFactory( - messageSender); - OkHttpClient client = (OkHttpClient) ReflectionTestUtils.getField(factory, - "client"); + OkHttp3ClientHttpRequestFactory factory = assertOkHttp3RequestFactory(messageSender); + OkHttpClient client = (OkHttpClient) ReflectionTestUtils.getField(factory, "client"); assertThat(client).isNotNull(); assertThat(client.connectTimeoutMillis()).isEqualTo(5000); assertThat(client.readTimeoutMillis()).isEqualTo(2000); } - private OkHttp3ClientHttpRequestFactory assertOkHttp3RequestFactory( - WebServiceMessageSender messageSender) { + private OkHttp3ClientHttpRequestFactory assertOkHttp3RequestFactory(WebServiceMessageSender messageSender) { assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class); ClientHttpRequestMessageSender sender = (ClientHttpRequestMessageSender) messageSender; ClientHttpRequestFactory requestFactory = sender.getRequestFactory(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java index 6c36456a089..0e61a0d200e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,17 +50,14 @@ public class HttpWebServiceMessageSenderBuilderSimpleIntegrationTests { @Test public void buildWithCustomTimeouts() { - WebServiceMessageSender messageSender = this.builder - .setConnectTimeout(Duration.ofSeconds(5)) + WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(2)).build(); - SimpleClientHttpRequestFactory requestFactory = assertSimpleClientRequestFactory( - messageSender); + SimpleClientHttpRequestFactory requestFactory = assertSimpleClientRequestFactory(messageSender); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 5000); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 2000); } - private SimpleClientHttpRequestFactory assertSimpleClientRequestFactory( - WebServiceMessageSender messageSender) { + private SimpleClientHttpRequestFactory assertSimpleClientRequestFactory(WebServiceMessageSender messageSender) { assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class); ClientHttpRequestMessageSender sender = (ClientHttpRequestMessageSender) messageSender; ClientHttpRequestFactory requestFactory = sender.getRequestFactory(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java index cbdb4eab829..c4492838a20 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,18 +42,15 @@ public class HttpWebServiceMessageSenderBuilderTests { public void buildWithRequestFactorySupplier() { ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class); ClientHttpRequestMessageSender messageSender = build( - new HttpWebServiceMessageSenderBuilder() - .requestFactory(() -> requestFactory)); + new HttpWebServiceMessageSenderBuilder().requestFactory(() -> requestFactory)); assertThat(messageSender.getRequestFactory()).isSameAs(requestFactory); } @Test public void buildWithReadAndConnectTimeout() { ClientHttpRequestMessageSender messageSender = build( - new HttpWebServiceMessageSenderBuilder() - .requestFactory(SimpleClientHttpRequestFactory::new) - .setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2))); + new HttpWebServiceMessageSenderBuilder().requestFactory(SimpleClientHttpRequestFactory::new) + .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); SimpleClientHttpRequestFactory requestFactory = (SimpleClientHttpRequestFactory) messageSender .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 5000); @@ -62,22 +59,17 @@ public class HttpWebServiceMessageSenderBuilderTests { @Test public void buildUsesHttpComponentsByDefault() { - ClientHttpRequestMessageSender messageSender = build( - new HttpWebServiceMessageSenderBuilder() - .setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2))); + ClientHttpRequestMessageSender messageSender = build(new HttpWebServiceMessageSenderBuilder() + .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); ClientHttpRequestFactory requestFactory = messageSender.getRequestFactory(); - assertThat(requestFactory) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); - RequestConfig requestConfig = (RequestConfig) ReflectionTestUtils - .getField(requestFactory, "requestConfig"); + assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + RequestConfig requestConfig = (RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig"); assertThat(requestConfig).isNotNull(); assertThat(requestConfig.getConnectTimeout()).isEqualTo(5000); assertThat(requestConfig.getSocketTimeout()).isEqualTo(2000); } - private ClientHttpRequestMessageSender build( - HttpWebServiceMessageSenderBuilder builder) { + private ClientHttpRequestMessageSender build(HttpWebServiceMessageSenderBuilder builder) { WebServiceMessageSender messageSender = builder.build(); assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class); return ((ClientHttpRequestMessageSender) messageSender); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java index 488232db757..bce8787e7cf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,7 @@ public class WebServiceTemplateBuilderTests { @Test public void createWithCustomizersShouldApplyCustomizers() { - WebServiceTemplateCustomizer customizer = mock( - WebServiceTemplateCustomizer.class); + WebServiceTemplateCustomizer customizer = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = new WebServiceTemplateBuilder(customizer).build(); verify(customizer).customize(template); } @@ -89,39 +88,34 @@ public class WebServiceTemplateBuilderTests { @Test public void detectHttpMessageSenderWhenFalseShouldDisableDetection() { - WebServiceTemplate webServiceTemplate = this.builder - .detectHttpMessageSender(false).build(); + WebServiceTemplate webServiceTemplate = this.builder.detectHttpMessageSender(false).build(); assertThat(webServiceTemplate.getMessageSenders()).hasSize(1); - assertThat(webServiceTemplate.getMessageSenders()[0]) - .isInstanceOf(HttpUrlConnectionMessageSender.class); + assertThat(webServiceTemplate.getMessageSenders()[0]).isInstanceOf(HttpUrlConnectionMessageSender.class); } @Test public void messageSendersWhenSendersAreAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.messageSenders((WebServiceMessageSender[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.messageSenders((WebServiceMessageSender[]) null)) .withMessageContaining("MessageSenders must not be null"); } @Test public void messageSendersCollectionWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageSenders( - (Collection) null)) + .isThrownBy(() -> this.builder.messageSenders((Collection) null)) .withMessageContaining("MessageSenders must not be null"); } @Test public void messageSendersShouldApply() { - WebServiceTemplate template = this.builder.messageSenders(this.messageSender) - .build(); + WebServiceTemplate template = this.builder.messageSenders(this.messageSender).build(); assertThat(template.getMessageSenders()).containsOnly(this.messageSender); } @Test public void messageSendersShouldReplaceExisting() { - WebServiceTemplate template = this.builder - .messageSenders(new ClientHttpRequestMessageSender()) + WebServiceTemplate template = this.builder.messageSenders(new ClientHttpRequestMessageSender()) .messageSenders(this.messageSender).build(); assertThat(template.getMessageSenders()).containsOnly(this.messageSender); } @@ -129,16 +123,14 @@ public class WebServiceTemplateBuilderTests { @Test public void additionalMessageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalMessageSenders((WebServiceMessageSender[]) null)) + .isThrownBy(() -> this.builder.additionalMessageSenders((WebServiceMessageSender[]) null)) .withMessageContaining("MessageSenders must not be null"); } @Test public void additionalMessageSendersCollectionWhenSendersAreAreNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageSenders( - (Collection) null)) + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.additionalMessageSenders((Collection) null)) .withMessageContaining("MessageSenders must not be null"); } @@ -147,30 +139,26 @@ public class WebServiceTemplateBuilderTests { ClientHttpRequestMessageSender httpMessageSender = new ClientHttpRequestMessageSender(); WebServiceTemplate template = this.builder.messageSenders(httpMessageSender) .additionalMessageSenders(this.messageSender).build(); - assertThat(template.getMessageSenders()).containsOnly(httpMessageSender, - this.messageSender); + assertThat(template.getMessageSenders()).containsOnly(httpMessageSender, this.messageSender); } @Test public void additionalMessageSendersShouldKeepDetectedHttpMessageSender() { - WebServiceTemplate template = this.builder - .additionalMessageSenders(this.messageSender).build(); + WebServiceTemplate template = this.builder.additionalMessageSenders(this.messageSender).build(); assertThat(template.getMessageSenders()).contains(this.messageSender); assertThat(template.getMessageSenders()).hasSize(2); } @Test public void interceptorsWhenInterceptorsAreNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((ClientInterceptor[]) null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.builder.interceptors((ClientInterceptor[]) null)) .withMessageContaining("Interceptors must not be null"); } @Test public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .interceptors((Collection) null)) + .isThrownBy(() -> this.builder.interceptors((Collection) null)) .withMessageContaining("Interceptors must not be null"); } @@ -182,33 +170,31 @@ public class WebServiceTemplateBuilderTests { @Test public void interceptorsShouldReplaceExisting() { - WebServiceTemplate template = this.builder - .interceptors(mock(ClientInterceptor.class)) + WebServiceTemplate template = this.builder.interceptors(mock(ClientInterceptor.class)) .interceptors(Collections.singleton(this.interceptor)).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) .withMessageContaining("Interceptors must not be null"); } @Test public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalInterceptors((Set) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) .withMessageContaining("Interceptors must not be null"); } @Test public void additionalInterceptorsShouldAddToExisting() { ClientInterceptor interceptor = mock(ClientInterceptor.class); - WebServiceTemplate template = this.builder.interceptors(interceptor) - .additionalInterceptors(this.interceptor).build(); - assertThat(template.getInterceptors()).containsOnly(interceptor, - this.interceptor); + WebServiceTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor) + .build(); + assertThat(template.getInterceptors()).containsOnly(interceptor, this.interceptor); } @Test @@ -218,29 +204,26 @@ public class WebServiceTemplateBuilderTests { WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setInterceptors(new ClientInterceptor[] { f1 }); this.builder.additionalInterceptors(f2).configure(webServiceTemplate); - assertThat(webServiceTemplate.getInterceptors()).containsExactlyInAnyOrder(f2, - f1); + assertThat(webServiceTemplate.getInterceptors()).containsExactlyInAnyOrder(f2, f1); } @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers( - (Collection) null)) + .isThrownBy(() -> this.builder.customizers((Collection) null)) .withMessageContaining("Customizers must not be null"); } @Test public void customizersShouldApply() { - WebServiceTemplateCustomizer customizer = mock( - WebServiceTemplateCustomizer.class); + WebServiceTemplateCustomizer customizer = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer).build(); verify(customizer).customize(template); } @@ -249,17 +232,14 @@ public class WebServiceTemplateBuilderTests { public void customizersShouldBeAppliedLast() { WebServiceTemplate template = spy(new WebServiceTemplate()); this.builder - .additionalCustomizers(((webServiceTemplate) -> verify(webServiceTemplate) - .setMessageSenders(any()))); + .additionalCustomizers(((webServiceTemplate) -> verify(webServiceTemplate).setMessageSenders(any()))); this.builder.configure(template); } @Test public void customizersShouldReplaceExisting() { - WebServiceTemplateCustomizer customizer1 = mock( - WebServiceTemplateCustomizer.class); - WebServiceTemplateCustomizer customizer2 = mock( - WebServiceTemplateCustomizer.class); + WebServiceTemplateCustomizer customizer1 = mock(WebServiceTemplateCustomizer.class); + WebServiceTemplateCustomizer customizer2 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer1) .customizers(Collections.singleton(customizer2)).build(); verifyZeroInteractions(customizer1); @@ -269,27 +249,22 @@ public class WebServiceTemplateBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .additionalCustomizers((WebServiceTemplateCustomizer[]) null)) + .isThrownBy(() -> this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers( - (Collection) null)) + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.additionalCustomizers((Collection) null)) .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersShouldAddToExisting() { - WebServiceTemplateCustomizer customizer1 = mock( - WebServiceTemplateCustomizer.class); - WebServiceTemplateCustomizer customizer2 = mock( - WebServiceTemplateCustomizer.class); - WebServiceTemplate template = this.builder.customizers(customizer1) - .additionalCustomizers(customizer2).build(); + WebServiceTemplateCustomizer customizer1 = mock(WebServiceTemplateCustomizer.class); + WebServiceTemplateCustomizer customizer2 = mock(WebServiceTemplateCustomizer.class); + WebServiceTemplate template = this.builder.customizers(customizer1).additionalCustomizers(customizer2).build(); verify(customizer1).customize(template); verify(customizer2).customize(template); } @@ -312,16 +287,14 @@ public class WebServiceTemplateBuilderTests { @Test public void setTransformerFactoryClass() { WebServiceTemplate template = mock(WebServiceTemplate.class); - this.builder.setTransformerFactoryClass(SAXTransformerFactory.class) - .configure(template); + this.builder.setTransformerFactoryClass(SAXTransformerFactory.class).configure(template); verify(template).setTransformerFactoryClass(SAXTransformerFactory.class); } @Test public void setWebServiceMessageFactory() { WebServiceMessageFactory messageFactory = mock(WebServiceMessageFactory.class); - WebServiceTemplate template = this.builder - .setWebServiceMessageFactory(messageFactory).build(); + WebServiceTemplate template = this.builder.setWebServiceMessageFactory(messageFactory).build(); assertThat(template.getMessageFactory()).isEqualTo(messageFactory); } @@ -335,46 +308,36 @@ public class WebServiceTemplateBuilderTests { @Test public void setUnmarshaller() { Unmarshaller unmarshaller = mock(Unmarshaller.class); - WebServiceTemplate webServiceTemplate = this.builder.setUnmarshaller(unmarshaller) - .build(); + WebServiceTemplate webServiceTemplate = this.builder.setUnmarshaller(unmarshaller).build(); assertThat(webServiceTemplate.getUnmarshaller()).isEqualTo(unmarshaller); } @Test public void setFaultMessageResolver() { FaultMessageResolver faultMessageResolver = mock(FaultMessageResolver.class); - WebServiceTemplate webServiceTemplate = this.builder - .setFaultMessageResolver(faultMessageResolver).build(); - assertThat(webServiceTemplate.getFaultMessageResolver()) - .isEqualTo(faultMessageResolver); + WebServiceTemplate webServiceTemplate = this.builder.setFaultMessageResolver(faultMessageResolver).build(); + assertThat(webServiceTemplate.getFaultMessageResolver()).isEqualTo(faultMessageResolver); } @Test public void setDefaultUri() { URI uri = URI.create("http://localhost:8080"); - WebServiceTemplate webServiceTemplate = this.builder.setDefaultUri(uri.toString()) - .build(); - assertThat(webServiceTemplate.getDestinationProvider().getDestination()) - .isEqualTo(uri); + WebServiceTemplate webServiceTemplate = this.builder.setDefaultUri(uri.toString()).build(); + assertThat(webServiceTemplate.getDestinationProvider().getDestination()).isEqualTo(uri); } @Test public void setDestinationProvider() { - DestinationProvider destinationProvider = () -> URI - .create("http://localhost:8080"); - WebServiceTemplate webServiceTemplate = this.builder - .setDestinationProvider(destinationProvider).build(); - assertThat(webServiceTemplate.getDestinationProvider()) - .isEqualTo(destinationProvider); + DestinationProvider destinationProvider = () -> URI.create("http://localhost:8080"); + WebServiceTemplate webServiceTemplate = this.builder.setDestinationProvider(destinationProvider).build(); + assertThat(webServiceTemplate.getDestinationProvider()).isEqualTo(destinationProvider); } - private void assertHttpComponentsRequestFactory( - WebServiceMessageSender messageSender) { + private void assertHttpComponentsRequestFactory(WebServiceMessageSender messageSender) { assertThat(messageSender).isInstanceOf(ClientHttpRequestMessageSender.class); ClientHttpRequestMessageSender sender = (ClientHttpRequestMessageSender) messageSender; ClientHttpRequestFactory requestFactory = sender.getRequestFactory(); - assertThat(requestFactory) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/main/java/sample/actuator/customsecurity/SecurityConfiguration.java b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/main/java/sample/actuator/customsecurity/SecurityConfiguration.java index 1342389146c..0f45475c4e2 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/main/java/sample/actuator/customsecurity/SecurityConfiguration.java +++ b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/main/java/sample/actuator/customsecurity/SecurityConfiguration.java @@ -33,10 +33,9 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { return new InMemoryUserDetailsManager( - User.withDefaultPasswordEncoder().username("user").password("password") - .authorities("ROLE_USER").build(), - User.withDefaultPasswordEncoder().username("beans").password("beans") - .authorities("ROLE_BEANS").build(), + User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER") + .build(), + User.withDefaultPasswordEncoder().username("beans").password("beans").authorities("ROLE_BEANS").build(), User.withDefaultPasswordEncoder().username("admin").password("admin") .authorities("ROLE_ACTUATOR", "ROLE_USER").build()); } diff --git a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/CorsSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/CorsSampleActuatorApplicationTests.java index 0740bd6c84c..032b82fdde4 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/CorsSampleActuatorApplicationTests.java @@ -52,36 +52,31 @@ class CorsSampleActuatorApplicationTests { @BeforeEach public void setUp() { RestTemplateBuilder builder = new RestTemplateBuilder(); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - this.applicationContext.getEnvironment(), "http"); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(this.applicationContext.getEnvironment(), + "http"); builder = builder.uriTemplateHandler(handler); this.testRestTemplate = new TestRestTemplate(builder); } @Test void endpointShouldReturnUnauthorized() { - ResponseEntity entity = this.testRestTemplate.getForEntity("/actuator/env", - Map.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("/actuator/env", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void preflightRequestToEndpointShouldReturnOk() throws Exception { RequestEntity healthRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080") - .header("Access-Control-Request-Method", "GET").build(); - ResponseEntity exchange = this.testRestTemplate.exchange(healthRequest, - Map.class); + .header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build(); + ResponseEntity exchange = this.testRestTemplate.exchange(healthRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { RequestEntity entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095") - .header("Access-Control-Request-Method", "GET").build(); - ResponseEntity exchange = this.testRestTemplate.exchange(entity, - byte[].class); + .header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build(); + ResponseEntity exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java index 39f92c3aca4..5c04d4ca69c 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java @@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.server.port=0", - "management.server.servlet.context-path=/management" }) + properties = { "management.server.port=0", "management.server.servlet.context-path=/management" }) class ManagementPortAndPathSampleActuatorApplicationTests { @LocalServerPort @@ -55,24 +54,22 @@ class ManagementPortAndPathSampleActuatorApplicationTests { @Test void actuatorPathOnMainPortShouldNotMatch() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/actuator/health", String.class); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testSecureActuator() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/management/actuator/env", - String.class); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/env", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testInsecureActuator() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/management/actuator/health", - String.class); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @@ -80,8 +77,7 @@ class ManagementPortAndPathSampleActuatorApplicationTests { @Test void testMissing() { ResponseEntity entity = new TestRestTemplate("admin", "admin") - .getForEntity("http://localhost:" + this.managementPort - + "/management/actuator/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } diff --git a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java index 34eb444af2f..59e38091004 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-custom-security/src/test/java/sample/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java @@ -58,30 +58,26 @@ class SampleActuatorCustomSecurityApplicationTests { assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map body = entity.getBody(); - assertThat((String) body.get("message")) - .contains("Expected exception in controller"); + assertThat((String) body.get("message")).contains("Expected exception in controller"); } @Test void testInsecureStaticResources() { - ResponseEntity entity = restTemplate() - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity entity = restTemplate().getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } @Test void actuatorInsecureEndpoint() { - ResponseEntity entity = restTemplate().getForEntity("/actuator/health", - String.class); + ResponseEntity entity = restTemplate().getForEntity("/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test void actuatorLinksIsSecure() { - ResponseEntity entity = restTemplate().getForEntity("/actuator", - Object.class); + ResponseEntity entity = restTemplate().getForEntity("/actuator", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = adminRestTemplate().getForEntity("/actuator", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @@ -89,43 +85,40 @@ class SampleActuatorCustomSecurityApplicationTests { @Test void actuatorSecureEndpointWithAnonymous() { - ResponseEntity entity = restTemplate().getForEntity("/actuator/env", - Object.class); + ResponseEntity entity = restTemplate().getForEntity("/actuator/env", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorSecureEndpointWithUnauthorizedUser() { - ResponseEntity entity = userRestTemplate().getForEntity("/actuator/env", - Object.class); + ResponseEntity entity = userRestTemplate().getForEntity("/actuator/env", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void actuatorSecureEndpointWithAuthorizedUser() { - ResponseEntity entity = adminRestTemplate().getForEntity("/actuator/env", - Object.class); + ResponseEntity entity = adminRestTemplate().getForEntity("/actuator/env", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void actuatorCustomMvcSecureEndpointWithAnonymous() { - ResponseEntity entity = restTemplate() - .getForEntity("/actuator/example/echo?text={t}", String.class, "test"); + ResponseEntity entity = restTemplate().getForEntity("/actuator/example/echo?text={t}", String.class, + "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorCustomMvcSecureEndpointWithUnauthorizedUser() { - ResponseEntity entity = userRestTemplate() - .getForEntity("/actuator/example/echo?text={t}", String.class, "test"); + ResponseEntity entity = userRestTemplate().getForEntity("/actuator/example/echo?text={t}", String.class, + "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void actuatorCustomMvcSecureEndpointWithAuthorizedUser() { - ResponseEntity entity = adminRestTemplate() - .getForEntity("/actuator/example/echo?text={t}", String.class, "test"); + ResponseEntity entity = adminRestTemplate().getForEntity("/actuator/example/echo?text={t}", + String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("test"); assertThat(entity.getHeaders().getFirst("echo")).isEqualTo("test"); @@ -133,15 +126,13 @@ class SampleActuatorCustomSecurityApplicationTests { @Test void actuatorExcludedFromEndpointRequestMatcher() { - ResponseEntity entity = userRestTemplate() - .getForEntity("/actuator/mappings", Object.class); + ResponseEntity entity = userRestTemplate().getForEntity("/actuator/mappings", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void mvcMatchersCanBeUsedToSecureActuators() { - ResponseEntity entity = beansRestTemplate() - .getForEntity("/actuator/beans", Object.class); + ResponseEntity entity = beansRestTemplate().getForEntity("/actuator/beans", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); entity = beansRestTemplate().getForEntity("/actuator/beans/", Object.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @@ -164,8 +155,7 @@ class SampleActuatorCustomSecurityApplicationTests { } private TestRestTemplate configure(TestRestTemplate restTemplate) { - restTemplate - .setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment)); + restTemplate.setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment)); return restTemplate; } diff --git a/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java index 8da9e43e68c..91437ee87df 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java @@ -47,8 +47,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ExtendWith(OutputCaptureExtension.class) class SampleActuatorLog4J2ApplicationTests { - private static final Logger logger = LogManager - .getLogger(SampleActuatorLog4J2ApplicationTests.class); + private static final Logger logger = LogManager.getLogger(SampleActuatorLog4J2ApplicationTests.class); @Autowired private MockMvc mvc; @@ -61,12 +60,9 @@ class SampleActuatorLog4J2ApplicationTests { @Test void validateLoggersEndpoint() throws Exception { - this.mvc.perform( - get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol") - .header("Authorization", "Basic " + getBasicAuth())) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("{\"configuredLevel\":\"WARN\"," - + "\"effectiveLevel\":\"WARN\"}"))); + this.mvc.perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization", + "Basic " + getBasicAuth())).andExpect(status().isOk()).andExpect( + content().string(equalTo("{\"configuredLevel\":\"WARN\"," + "\"effectiveLevel\":\"WARN\"}"))); } private String getBasicAuth() { diff --git a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java index d2765f938ae..f4f1187a1a5 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java @@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.server.port:0" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port:0" }) class SampleActuatorUiApplicationPortTests { @LocalServerPort @@ -47,26 +46,23 @@ class SampleActuatorUiApplicationPortTests { @Test void testHome() { - ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port, String.class); + ResponseEntity entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void testMetrics() { @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/actuator/metrics", - Map.class); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { - ResponseEntity entity = new TestRestTemplate() - .withBasicAuth("user", getPassword()).getForEntity( - "http://localhost:" + this.managementPort + "/actuator/health", - String.class); + ResponseEntity entity = new TestRestTemplate().withBasicAuth("user", getPassword()) + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java index b0bb8f2768b..13e585d4b7f 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java @@ -49,17 +49,15 @@ class SampleActuatorUiApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate - .withBasicAuth("user", getPassword()).exchange("/", HttpMethod.GET, - new HttpEntity(headers), String.class); + ResponseEntity entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/", + HttpMethod.GET, new HttpEntity(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello"); } @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } @@ -67,8 +65,7 @@ class SampleActuatorUiApplicationTests { @Test void testMetrics() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @@ -76,9 +73,8 @@ class SampleActuatorUiApplicationTests { void testError() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()).exchange("/error", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/error", + HttpMethod.GET, new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody()).contains("<html>").contains("<body>") .contains("Please contact the operator with the above information"); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java b/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java index 69a5d49c8dd..6c136ee68fa 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java @@ -45,8 +45,7 @@ public class SampleController { @GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, String> hello() { - return Collections.singletonMap("message", - this.helloWorldService.getHelloMessage()); + return Collections.singletonMap("message", this.helloWorldService.getHelloMessage()); } @PostMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java index 5d8d5d4790d..f53be03c1cb 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java @@ -45,8 +45,8 @@ class EndpointsPropertiesSampleActuatorApplicationTests { @Test void testCustomErrorPath() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/oops", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/oops", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -56,8 +56,7 @@ class EndpointsPropertiesSampleActuatorApplicationTests { @Test void testCustomContextPath() { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java index 209ef48d059..98f86bc4c56 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java @@ -35,9 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.server.port=0", "management.server.address=127.0.0.1", - "management.server.servlet.context-path:/admin" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0", + "management.server.address=127.0.0.1", "management.server.servlet.context-path:/admin" }) class ManagementAddressActuatorApplicationTests { @LocalServerPort @@ -49,16 +48,14 @@ class ManagementAddressActuatorApplicationTests { @Test void testHome() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port, Map.class); + ResponseEntity<Map> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate() - .withBasicAuth("user", getPassword()).getForEntity("http://localhost:" - + this.managementPort + "/admin/actuator/health", String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword()) + .getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java index b09451e8692..075013f7eaa 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java @@ -43,8 +43,7 @@ class ManagementPathSampleActuatorApplicationTests { @Test void testHealth() { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java index dade6a8938d..9788a6e2e1d 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java @@ -37,10 +37,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.server.port=0", - "management.endpoints.web.base-path=/admin", - "management.endpoint.health.show-details=never" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0", + "management.endpoints.web.base-path=/admin", "management.endpoint.health.show-details=never" }) class ManagementPortAndPathSampleActuatorApplicationTests { @LocalServerPort @@ -67,17 +65,15 @@ class ManagementPortAndPathSampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/metrics", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate() - .withBasicAuth("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/admin/health", - String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword()) + .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}"); } @@ -86,19 +82,15 @@ class ManagementPortAndPathSampleActuatorApplicationTests { void testEnvNotFound() { String unknownProperty = "test-does-not-exist"; assertThat(this.environment.containsProperty(unknownProperty)).isFalse(); - ResponseEntity<String> entity = new TestRestTemplate() - .withBasicAuth("user", getPassword()).getForEntity("http://localhost:" - + this.managementPort + "/admin/env/" + unknownProperty, - String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword()).getForEntity( + "http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test void testMissing() { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity( - "http://localhost:" + this.managementPort + "/admin/missing", - String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } @@ -118,8 +110,7 @@ class ManagementPortAndPathSampleActuatorApplicationTests { void testManagementErrorPage() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/error", - Map.class); + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java index 70b501d78fc..9e768efb58c 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { - "management.server.port=0", "management.endpoint.health.show-details=always" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, + properties = { "management.server.port=0", "management.endpoint.health.show-details=always" }) class ManagementPortSampleActuatorApplicationTests { @LocalServerPort @@ -60,18 +60,15 @@ class ManagementPortSampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/actuator/metrics", - Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate() - .withBasicAuth("user", getPassword()).getForEntity( - "http://localhost:" + this.managementPort + "/actuator/health", - String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword()) + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).contains("\"example\""); @@ -82,8 +79,7 @@ class ManagementPortSampleActuatorApplicationTests { void testErrorPage() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/error", - Map.class); + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortWithLazyInitializationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortWithLazyInitializationTests.java index 1d28594379b..5bbf340e3bd 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortWithLazyInitializationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortWithLazyInitializationTests.java @@ -32,8 +32,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "management.server.port=0", "spring.main.lazy-initialization=true" }) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "management.server.port=0", "spring.main.lazy-initialization=true" }) class ManagementPortWithLazyInitializationTests { @LocalManagementPort @@ -41,10 +41,8 @@ class ManagementPortWithLazyInitializationTests { @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate() - .withBasicAuth("user", "password").getForEntity( - "http://localhost:" + this.managementPort + "/actuator/health", - String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java index a96b475f69d..2a62dfc6943 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java @@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.server.port=-1" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=-1" }) class NoManagementSampleActuatorApplicationTests { @Autowired @@ -44,8 +43,8 @@ class NoManagementSampleActuatorApplicationTests { @Test void testHome() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -56,8 +55,8 @@ class NoManagementSampleActuatorApplicationTests { void testMetricsNotAvailable() { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/metrics", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/metrics", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java index 427913be8f0..835b7d31f20 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java @@ -66,8 +66,7 @@ class SampleActuatorApplicationTests { @Test void testMetricsIsSecure() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = this.restTemplate.getForEntity("/actuator/metrics/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @@ -80,8 +79,8 @@ class SampleActuatorApplicationTests { @Test void testHome() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -93,8 +92,7 @@ class SampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); Map<String, Object> body = entity.getBody(); @@ -106,8 +104,7 @@ class SampleActuatorApplicationTests { @Test void testEnv() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/actuator/env", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") @@ -117,8 +114,7 @@ class SampleActuatorApplicationTests { @Test void healthInsecureByDefault() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\""); @@ -126,22 +122,18 @@ class SampleActuatorApplicationTests { @Test void infoInsecureByDefault() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/info", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/info", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()) - .contains("\"artifact\":\"spring-boot-sample-actuator\""); + assertThat(entity.getBody()).contains("\"artifact\":\"spring-boot-sample-actuator\""); assertThat(entity.getBody()).contains("\"someKey\":\"someValue\""); - assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", - "\"target\":\"1.8\""); - assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", - "\"reporting\":\"UTF-8\""); + assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", "\"target\":\"1.8\""); + assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", "\"reporting\":\"UTF-8\""); } @Test void testErrorPage() { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/foo", String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/foo", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).contains("\"error\":"); @@ -152,9 +144,8 @@ class SampleActuatorApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) - .exchange("/foo", HttpMethod.GET, request, String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/foo", + HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).as("Body was null").isNotNull(); @@ -164,8 +155,8 @@ class SampleActuatorApplicationTests { @Test void testErrorPageDirectAccess() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/error", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/error", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -177,8 +168,7 @@ class SampleActuatorApplicationTests { @SuppressWarnings("unchecked") public void testBeans() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/actuator/beans", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).containsOnlyKeys("contexts"); @@ -188,17 +178,14 @@ class SampleActuatorApplicationTests { @Test void testConfigProps() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/actuator/configprops", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); Map<String, Object> body = entity.getBody(); Map<String, Object> contexts = (Map<String, Object>) body.get("contexts"); - Map<String, Object> context = (Map<String, Object>) contexts - .get(this.applicationContext.getId()); + Map<String, Object> context = (Map<String, Object>) contexts.get(this.applicationContext.getId()); Map<String, Object> beans = (Map<String, Object>) context.get("beans"); - assertThat(beans) - .containsKey("spring.datasource-" + DataSourceProperties.class.getName()); + assertThat(beans).containsKey("spring.datasource-" + DataSourceProperties.class.getName()); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java index b71d0414d71..5b56c96168e 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java @@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "spring.mvc.servlet.path=/spring" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.mvc.servlet.path=/spring" }) class ServletPathSampleActuatorApplicationTests { @Autowired @@ -44,8 +43,7 @@ class ServletPathSampleActuatorApplicationTests { @Test void testErrorPath() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/spring/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") @@ -56,8 +54,7 @@ class ServletPathSampleActuatorApplicationTests { @Test void testHealth() { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/spring/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); @@ -66,8 +63,7 @@ class ServletPathSampleActuatorApplicationTests { @Test void testHomeIsSecure() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java index 98fca790662..05a3607faf8 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java @@ -38,10 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -@SpringBootTest( - classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class, - SampleActuatorApplication.class }, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class, + SampleActuatorApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) class ShutdownSampleActuatorApplicationTests { @Autowired @@ -50,8 +48,8 @@ class ShutdownSampleActuatorApplicationTests { @Test void testHome() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -62,8 +60,7 @@ class ShutdownSampleActuatorApplicationTests { @DirtiesContext public void testShutdown() { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()) .postForEntity("/actuator/shutdown", null, Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") diff --git a/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java b/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java index e813c8e273e..75c0f35a38f 100644 --- a/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java +++ b/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java @@ -48,12 +48,10 @@ public class SampleAntApplicationIT { }); assertThat(jarFiles).hasSize(1); - Process process = new JavaExecutable() - .processBuilder("-jar", jarFiles[0].getName()).directory(target).start(); + Process process = new JavaExecutable().processBuilder("-jar", jarFiles[0].getName()).directory(target).start(); process.waitFor(5, TimeUnit.MINUTES); assertThat(process.exitValue()).isEqualTo(0); - String output = FileCopyUtils - .copyToString(new InputStreamReader(process.getInputStream())); + String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream())); assertThat(output).contains("Spring Boot Ant Example"); } diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java index f6f98bfd10f..1dd151dbfa3 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java @@ -48,13 +48,11 @@ public class ChatService { @org.atmosphere.config.service.Message(encoders = JacksonEncoderDecoder.class, decoders = JacksonEncoderDecoder.class) public Message onMessage(Message message) throws IOException { - this.logger.info("Author " + message.getAuthor() + " sent message " - + message.getMessage()); + this.logger.info("Author " + message.getAuthor() + " sent message " + message.getMessage()); return message; } - public static class JacksonEncoderDecoder - implements Encoder<Message, String>, Decoder<String, Message> { + public static class JacksonEncoderDecoder implements Encoder<Message, String>, Decoder<String, Message> { private final ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java index 4f0e6d0cb34..0c075b2e4c0 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java @@ -50,11 +50,11 @@ public class SampleAtmosphereApplication { // to be mapped to '/chat' AtmosphereServlet atmosphereServlet = new AtmosphereServlet(); atmosphereServlet.framework().setHandlersPath("/"); - ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>( - atmosphereServlet, "/chat/*"); + ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>(atmosphereServlet, + "/chat/*"); registration.addInitParameter("org.atmosphere.cpr.packages", "sample"); - registration.addInitParameter("org.atmosphere.interceptor.HeartbeatInterceptor" - + ".clientHeartbeatFrequencyInSeconds", "10"); + registration.addInitParameter( + "org.atmosphere.interceptor.HeartbeatInterceptor" + ".clientHeartbeatFrequencyInSeconds", "10"); registration.setLoadOnStartup(0); // Need to occur before the EmbeddedAtmosphereInitializer registration.setOrder(Ordered.HIGHEST_PRECEDENCE); diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java index 227b314edf4..a500372d650 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java @@ -42,8 +42,7 @@ import org.springframework.web.socket.handler.TextWebSocketHandler; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest(classes = SampleAtmosphereApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleAtmosphereApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) class SampleAtmosphereApplicationTests { private static Log logger = LogFactory.getLog(SampleAtmosphereApplicationTests.class); @@ -53,18 +52,15 @@ class SampleAtmosphereApplicationTests { @Test void chatEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/chat/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0L); - assertThat(messagePayloadReference.get()) - .contains("{\"message\":\"test\",\"author\":\"test\",\"time\":"); + assertThat(messagePayloadReference.get()).contains("{\"message\":\"test\",\"author\":\"test\",\"time\":"); } @Configuration(proxyBeanMethods = false) @@ -90,8 +86,7 @@ class SampleAtmosphereApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; } @@ -106,17 +101,13 @@ class SampleAtmosphereApplicationTests { return new TextWebSocketHandler() { @Override - public void afterConnectionEstablished(WebSocketSession session) - throws Exception { - session.sendMessage(new TextMessage( - "{\"author\":\"test\",\"message\":\"test\"}")); + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + session.sendMessage(new TextMessage("{\"author\":\"test\",\"message\":\"test\"}")); } @Override - protected void handleTextMessage(WebSocketSession session, - TextMessage message) throws Exception { - logger.info("Received: " + message + " (" - + ClientConfiguration.this.latch.getCount() + ")"); + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { + logger.info("Received: " + message + " (" + ClientConfiguration.this.latch.getCount() + ")"); session.close(); ClientConfiguration.this.messagePayload.set(message.getPayload()); ClientConfiguration.this.latch.countDown(); diff --git a/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java b/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java index ea496ead332..0c737c4a554 100644 --- a/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java +++ b/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java @@ -45,8 +45,7 @@ public class SampleBatchApplication { return new Tasklet() { @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext context) { + public RepeatStatus execute(StepContribution contribution, ChunkContext context) { return RepeatStatus.FINISHED; } }; @@ -66,8 +65,7 @@ public class SampleBatchApplication { public static void main(String[] args) { // System.exit is common for Batch applications since the exit code can be used to // drive a workflow - System.exit(SpringApplication - .exit(SpringApplication.run(SampleBatchApplication.class, args))); + System.exit(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class, args))); } } diff --git a/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java b/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java index 3e165a8e8ca..e120a3f8882 100644 --- a/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java @@ -30,8 +30,7 @@ class SampleBatchApplicationTests { @Test void testDefaultSettings(CapturedOutput capturedOutput) { - assertThat(SpringApplication - .exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); + assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); assertThat(capturedOutput).contains("completed with the following parameters"); } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java index 5010db25ce3..e6c28f9f38e 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java @@ -36,8 +36,8 @@ public class CacheManagerCheck implements CommandLineRunner { @Override public void run(String... strings) throws Exception { - logger.info("\n\n" + "=========================================================\n" - + "Using cache manager: " + this.cacheManager.getClass().getName() + "\n" + logger.info("\n\n" + "=========================================================\n" + "Using cache manager: " + + this.cacheManager.getClass().getName() + "\n" + "=========================================================\n\n"); } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java index e689f2d56af..2d4d5fb657c 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java @@ -27,8 +27,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; public class SampleCacheApplication { public static void main(String[] args) { - new SpringApplicationBuilder().sources(SampleCacheApplication.class) - .profiles("app").run(args); + new SpringApplicationBuilder().sources(SampleCacheApplication.class).profiles("app").run(args); } } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java index abae2044edc..27823e8f4b1 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java @@ -28,26 +28,21 @@ import org.springframework.stereotype.Component; @Profile("app") class SampleClient { - private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX", - "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", - "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ", - "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", - "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", - "CI", "HR", "CU", "CW", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", - "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "GA", - "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", - "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", - "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR", - "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", - "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", - "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "NC", - "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA", - "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", - "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", - "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "SS", "ES", "LK", - "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", - "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", - "UM", "UY", "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW"); + private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX", "AL", "DZ", "AS", "AD", "AO", + "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", + "BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", + "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CW", "CY", "CZ", "DK", + "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", + "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", + "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", + "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", + "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", + "MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", + "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN", + "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", + "ZA", "GS", "SS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", + "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VE", + "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW"); private final CountryRepository countryService; @@ -60,8 +55,7 @@ class SampleClient { @Scheduled(fixedDelay = 500) public void retrieveCountry() { - String randomCode = SAMPLE_COUNTRY_CODES - .get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size())); + String randomCode = SAMPLE_COUNTRY_CODES.get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size())); System.out.println("Looking for country with code '" + randomCode + "'"); this.countryService.findByCode(randomCode); } diff --git a/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java b/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java index 10c121c64a8..f6544d802e1 100644 --- a/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java @@ -42,8 +42,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java b/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java index 597fa3ed383..1ab82e29ae7 100644 --- a/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java +++ b/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java @@ -22,11 +22,9 @@ import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionLis import org.springframework.core.Ordered; -public class OrderedCassandraTestExecutionListener - extends CassandraUnitDependencyInjectionTestExecutionListener { +public class OrderedCassandraTestExecutionListener extends CassandraUnitDependencyInjectionTestExecutionListener { - private static final Log logger = LogFactory - .getLog(OrderedCassandraTestExecutionListener.class); + private static final Log logger = LogFactory.getLog(OrderedCassandraTestExecutionListener.class); @Override public int getOrder() { diff --git a/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java b/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java index dac594d578b..c8253536fed 100644 --- a/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java +++ b/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ public class User { @Override public String toString() { - return "User{" + "id='" + this.id + '\'' + ", firstName='" + this.firstName + '\'' - + ", lastName='" + this.lastName + '\'' + '}'; + return "User{" + "id='" + this.id + '\'' + ", firstName='" + this.firstName + '\'' + ", lastName='" + + this.lastName + '\'' + '}'; } } diff --git a/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java index 4dfd27acbb6..2d6c220ac25 100644 --- a/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java @@ -33,8 +33,7 @@ class SampleCouchbaseApplicationTests { @Test void testDefaultSettings(CapturedOutput capturedOutput) { try { - new SpringApplicationBuilder(SampleCouchbaseApplication.class) - .run("--server.port=0"); + new SpringApplicationBuilder(SampleCouchbaseApplication.class).run("--server.port=0"); } catch (RuntimeException ex) { if (serverNotRunning(ex)) { diff --git a/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java b/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java index c214eac59f7..8002e9ddd33 100644 --- a/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java @@ -19,8 +19,7 @@ package sample.data.elasticsearch; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; -@Document(indexName = "customer", type = "customer", shards = 1, replicas = 0, - refreshInterval = "-1") +@Document(indexName = "customer", type = "customer", shards = 1, replicas = 0, refreshInterval = "-1") public class Customer { @Id @@ -64,8 +63,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/City.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/City.java index dd62c7a6d10..69b2a722477 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/City.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/City.java @@ -30,8 +30,7 @@ public class City implements Serializable { private static final long serialVersionUID = 1L; @Id - @SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", - initialValue = 23) + @SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23) @GeneratedValue(generator = "city_generator") private Long id; diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Hotel.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Hotel.java index 3743a3a0b74..a2d78047102 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Hotel.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Hotel.java @@ -36,8 +36,7 @@ public class Hotel implements Serializable { private static final long serialVersionUID = 1L; @Id - @SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence", - initialValue = 28) + @SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence", initialValue = 28) @GeneratedValue(generator = "hotel_generator") private Long id; diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Review.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Review.java index 36ad46e16be..608943423b7 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Review.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/domain/Review.java @@ -38,8 +38,7 @@ public class Review implements Serializable { private static final long serialVersionUID = 1L; @Id - @SequenceGenerator(name = "review_generator", sequenceName = "review_sequence", - initialValue = 64) + @SequenceGenerator(name = "review_generator", sequenceName = "review_sequence", initialValue = 64) @GeneratedValue(generator = "review_generator") private Long id; diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java index dd0bb191ea6..c16ec30dfbf 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java @@ -26,8 +26,7 @@ interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); - Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, - String country, Pageable pageable); + Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java index 4b007a76675..6ba53659c30 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java @@ -57,9 +57,8 @@ class CityServiceImpl implements CityService { name = name.substring(0, splitPos); } - return this.cityRepository - .findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), - country.trim(), pageable); + return this.cityRepository.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), country.trim(), + pageable); } @Override diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java index a1c96cb1056..819870b2545 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java @@ -60,15 +60,13 @@ class SampleDataJpaApplicationTests { @Test void testHome() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Bath")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Bath")); } @Test void testJmx() throws Exception { assertThat(ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)) - .hasSize(1); + .queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)).hasSize(1); } } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java index 5a94e00a678..4001b8bba2a 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java @@ -48,13 +48,10 @@ class HotelRepositoryIntegrationTests { @Test void executesQueryMethodsCorrectly() { - City city = this.cityRepository - .findAll(PageRequest.of(0, 1, Direction.ASC, "name")).getContent().get(0); + City city = this.cityRepository.findAll(PageRequest.of(0, 1, Direction.ASC, "name")).getContent().get(0); assertThat(city.getName()).isEqualTo("Atlanta"); - Page<HotelSummary> hotels = this.repository.findByCity(city, - PageRequest.of(0, 10, Direction.ASC, "name")); - Hotel hotel = this.repository.findByCityAndName(city, - hotels.getContent().get(0).getName()); + Page<HotelSummary> hotels = this.repository.findByCity(city, PageRequest.of(0, 10, Direction.ASC, "name")); + Hotel hotel = this.repository.findByCityAndName(city, hotels.getContent().get(0).getName()); assertThat(hotel.getName()).isEqualTo("Doubletree"); List<RatingCount> counts = this.repository.findRatingCounts(hotel); assertThat(counts).hasSize(1); diff --git a/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java b/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java index bfee455993a..80860e0bf98 100644 --- a/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java @@ -37,8 +37,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/SampleMongoApplication.java b/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/SampleMongoApplication.java index 7521a87a89f..afc261cb06a 100644 --- a/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/SampleMongoApplication.java +++ b/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/SampleMongoApplication.java @@ -61,9 +61,8 @@ public class SampleMongoApplication implements CommandLineRunner { @Bean public MongoClientSettingsBuilderCustomizer customizer() { - return (builder) -> builder - .applyToConnectionPoolSettings((connectionPool) -> connectionPool - .maxConnectionIdleTime(5, TimeUnit.MINUTES)); + return (builder) -> builder.applyToConnectionPoolSettings( + (connectionPool) -> connectionPool.maxConnectionIdleTime(5, TimeUnit.MINUTES)); } public static void main(String[] args) { diff --git a/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java b/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java index eb04ad97657..1568eca45dc 100644 --- a/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/City.java b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/City.java index 71776d03ecd..2359abc991b 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/City.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/City.java @@ -30,8 +30,7 @@ public class City implements Serializable { private static final long serialVersionUID = 1L; @Id - @SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", - initialValue = 23) + @SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23) @GeneratedValue(generator = "city_generator") private Long id; diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/Hotel.java b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/Hotel.java index 3f135c59c02..91e249e93bd 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/Hotel.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/domain/Hotel.java @@ -33,8 +33,7 @@ public class Hotel implements Serializable { private static final long serialVersionUID = 1L; @Id - @SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence", - initialValue = 28) + @SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence", initialValue = 28) @GeneratedValue(generator = "hotel_generator") private Long id; diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java index 330148676bf..566d54db8a2 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java @@ -27,11 +27,9 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "cities", path = "cities") interface CityRepository extends PagingAndSortingRepository<City, Long> { - Page<City> findByNameContainingAndCountryContainingAllIgnoringCase( - @Param("name") String name, @Param("country") String country, - Pageable pageable); + Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(@Param("name") String name, + @Param("country") String country, Pageable pageable); - City findByNameAndCountryAllIgnoringCase(@Param("name") String name, - @Param("country") String country); + City findByNameAndCountryAllIgnoringCase(@Param("name") String name, @Param("country") String country); } diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java index aa5ed17529b..eddb8643ade 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java @@ -55,25 +55,21 @@ class SampleDataRestApplicationTests { @Test void testHome() throws Exception { - this.mvc.perform(get("/api")).andExpect(status().isOk()) - .andExpect(content().string(containsString("hotels"))); + this.mvc.perform(get("/api")).andExpect(status().isOk()).andExpect(content().string(containsString("hotels"))); } @Test void findByNameAndCountry() throws Exception { - this.mvc.perform(get( - "/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia")) - .andExpect(status().isOk()) - .andExpect(jsonPath("state", equalTo("Victoria"))) + this.mvc.perform(get("/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia")) + .andExpect(status().isOk()).andExpect(jsonPath("state", equalTo("Victoria"))) .andExpect(jsonPath("name", equalTo("Melbourne"))); } @Test void findByContaining() throws Exception { - this.mvc.perform(get( - "/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) - .andExpect(status().isOk()) - .andExpect(jsonPath("_embedded.cities", hasSize(3))); + this.mvc.perform( + get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) + .andExpect(status().isOk()).andExpect(jsonPath("_embedded.cities", hasSize(3))); } } diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java index f2b30405611..7e33f64dca9 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java @@ -46,17 +46,15 @@ class CityRepositoryIntegrationTests { @Test void findByNameAndCountry() { - City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne", - "Australia"); + City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne", "Australia"); assertThat(city).isNotNull(); assertThat(city.getName()).isEqualTo("Melbourne"); } @Test void findContaining() { - Page<City> cities = this.repository - .findByNameContainingAndCountryContainingAllIgnoringCase("", "UK", - PageRequest.of(0, 10)); + Page<City> cities = this.repository.findByNameContainingAndCountryContainingAllIgnoringCase("", "UK", + PageRequest.of(0, 10)); assertThat(cities.getTotalElements()).isEqualTo(3L); } diff --git a/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java b/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java index 3d44260f8f6..f569740eb47 100644 --- a/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java +++ b/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java @@ -93,8 +93,8 @@ public class Product { @Override public String toString() { - return "Product [id=" + this.id + ", name=" + this.name + ", price=" + this.price - + ", category=" + this.category + ", location=" + this.location + "]"; + return "Product [id=" + this.id + ", name=" + this.name + ", price=" + this.price + ", category=" + + this.category + ", location=" + this.location + "]"; } } diff --git a/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java b/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java index 8a0dcb8fb60..d0778e9dd03 100644 --- a/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java +++ b/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java @@ -41,8 +41,7 @@ public class MyController { sessionVar = new Date(); session.setAttribute("var", sessionVar); } - ModelMap model = new ModelMap("message", Message.MESSAGE) - .addAttribute("sessionVar", sessionVar); + ModelMap model = new ModelMap("message", Message.MESSAGE).addAttribute("sessionVar", sessionVar); return new ModelAndView("hello", model); } diff --git a/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java b/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java index 2dbd14b4026..5ae76704a76 100644 --- a/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java @@ -41,24 +41,21 @@ class SampleDevToolsApplicationIntegrationTests { @Test void testStaticResource() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/application.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/application.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("color: green;"); } @Test void testPublicResource() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("public file"); } @Test void testClassResource() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/application.properties", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/application.properties", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java b/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java index 0371889556f..fdf9cc55d44 100644 --- a/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java +++ b/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java @@ -25,8 +25,7 @@ import javax.persistence.SequenceGenerator; public class Person { @Id - @SequenceGenerator(name = "person_generator", sequenceName = "person_sequence", - allocationSize = 1) + @SequenceGenerator(name = "person_generator", sequenceName = "person_sequence", allocationSize = 1) @GeneratedValue(generator = "person_generator") private Long id; @@ -52,8 +51,7 @@ public class Person { @Override public String toString() { - return "Person [firstName=" + this.firstName + ", lastName=" + this.lastName - + "]"; + return "Person [firstName=" + this.firstName + ", lastName=" + this.lastName + "]"; } } diff --git a/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java b/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java index 1e3f127d99f..1eb458869c8 100644 --- a/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java @@ -32,8 +32,7 @@ class SampleFlywayApplicationTests { @Test void testDefaultSettings() { - assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON", - Integer.class)).isEqualTo(1); + assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON", Integer.class)).isEqualTo(1); } } diff --git a/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java b/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java index a10a9dd5e75..336f3db774b 100644 --- a/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java +++ b/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java @@ -48,8 +48,7 @@ public class CustomerController { @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) HttpEntity<CollectionModel<Customer>> showCustomers() { - CollectionModel<Customer> resources = new CollectionModel<>( - this.repository.findAll()); + CollectionModel<Customer> resources = new CollectionModel<>(this.repository.findAll()); resources.add(this.entityLinks.linkToCollectionResource(Customer.class)); return new ResponseEntity<>(resources, HttpStatus.OK); } diff --git a/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java b/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java index 0d429928931..dc6ee3fe5df 100644 --- a/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java @@ -39,11 +39,9 @@ class SampleHateoasApplicationTests { @Test void hasHalLinks() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/customers/1", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/customers/1", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).startsWith( - "{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\""); + assertThat(entity.getBody()).startsWith("{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\""); assertThat(entity.getBody()).contains("_links\":{\"self\":{\"href\""); } @@ -52,11 +50,10 @@ class SampleHateoasApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.ACCEPT, "application/xml;q=0.9,application/json;q=0.8"); HttpEntity<?> request = new HttpEntity<>(headers); - ResponseEntity<String> response = this.restTemplate.exchange("/customers/1", - HttpMethod.GET, request, String.class); + ResponseEntity<String> response = this.restTemplate.exchange("/customers/1", HttpMethod.GET, request, + String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getHeaders().getContentType()) - .isEqualTo(MediaType.parseMediaType("application/json")); + assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.parseMediaType("application/json")); } } diff --git a/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java b/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java index 66aa22c5143..8e5ded4b680 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java @@ -57,25 +57,22 @@ public class SampleIntegrationApplication { @Bean public FileWritingMessageHandler fileWriter() { - FileWritingMessageHandler writer = new FileWritingMessageHandler( - this.serviceProperties.getOutputDir()); + FileWritingMessageHandler writer = new FileWritingMessageHandler(this.serviceProperties.getOutputDir()); writer.setExpectReply(false); return writer; } @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlows.from(fileReader(), new FixedRatePoller()) - .channel(inputChannel()).handle(endpoint).channel(outputChannel()) - .handle(fileWriter()).get(); + return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) + .channel(outputChannel()).handle(fileWriter()).get(); } public static void main(String[] args) { SpringApplication.run(SampleIntegrationApplication.class, args); } - private static class FixedRatePoller - implements Consumer<SourcePollingChannelAdapterSpec> { + private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> { @Override public void accept(SourcePollingChannelAdapterSpec spec) { diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java index dd3a410b01d..db318ca9fe6 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java @@ -62,10 +62,10 @@ class SampleIntegrationApplicationTests { void testVanillaExchange(@TempDir Path temp) throws Exception { File inputDir = new File(temp.toFile(), "input"); File outputDir = new File(temp.toFile(), "output"); - this.context = SpringApplication.run(SampleIntegrationApplication.class, - "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir); - SpringApplication.run(ProducerApplication.class, "World", - "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir); + this.context = SpringApplication.run(SampleIntegrationApplication.class, "--service.input-dir=" + inputDir, + "--service.output-dir=" + outputDir); + SpringApplication.run(ProducerApplication.class, "World", "--service.input-dir=" + inputDir, + "--service.output-dir=" + outputDir); String output = getOutput(outputDir); assertThat(output).contains("Hello World"); } @@ -74,44 +74,38 @@ class SampleIntegrationApplicationTests { void testMessageGateway(@TempDir Path temp) throws Exception { File inputDir = new File(temp.toFile(), "input"); File outputDir = new File(temp.toFile(), "output"); - this.context = SpringApplication.run(SampleIntegrationApplication.class, - "testviamg", "--service.input-dir=" + inputDir, - "--service.output-dir=" + outputDir); - String output = getOutput( - this.context.getBean(ServiceProperties.class).getOutputDir()); + this.context = SpringApplication.run(SampleIntegrationApplication.class, "testviamg", + "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir); + String output = getOutput(this.context.getBean(ServiceProperties.class).getOutputDir()); assertThat(output).contains("testviamg"); } private String getOutput(File outputDir) throws Exception { - Future<String> future = Executors.newSingleThreadExecutor() - .submit(new Callable<String>() { - @Override - public String call() throws Exception { - Resource[] resources = getResourcesWithContent(outputDir); - while (resources.length == 0) { - Thread.sleep(200); - resources = getResourcesWithContent(outputDir); - } - StringBuilder builder = new StringBuilder(); - for (Resource resource : resources) { - try (InputStream inputStream = resource.getInputStream()) { - builder.append(new String( - StreamUtils.copyToByteArray(inputStream))); - } - } - return builder.toString(); + Future<String> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() { + @Override + public String call() throws Exception { + Resource[] resources = getResourcesWithContent(outputDir); + while (resources.length == 0) { + Thread.sleep(200); + resources = getResourcesWithContent(outputDir); + } + StringBuilder builder = new StringBuilder(); + for (Resource resource : resources) { + try (InputStream inputStream = resource.getInputStream()) { + builder.append(new String(StreamUtils.copyToByteArray(inputStream))); } - }); + } + return builder.toString(); + } + }); return future.get(30, TimeUnit.SECONDS); } private Resource[] getResourcesWithContent(File outputDir) throws IOException { - Resource[] candidates = ResourcePatternUtils - .getResourcePatternResolver(new DefaultResourceLoader()) + Resource[] candidates = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) .getResources("file:" + outputDir.getAbsolutePath() + "/**"); for (Resource candidate : candidates) { - if ((candidate.getFilename() != null - && candidate.getFilename().endsWith(".writing")) + if ((candidate.getFilename() != null && candidate.getFilename().endsWith(".writing")) || candidate.contentLength() == 0) { return new Resource[0]; } diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java index 3f825c7d246..1ba46554d52 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java @@ -42,8 +42,7 @@ public class ProducerApplication implements ApplicationRunner { this.serviceProperties.getInputDir().mkdirs(); if (args.getNonOptionArgs().size() > 0) { FileOutputStream stream = new FileOutputStream( - new File(this.serviceProperties.getInputDir(), - "data" + System.currentTimeMillis() + ".txt")); + new File(this.serviceProperties.getInputDir(), "data" + System.currentTimeMillis() + ".txt")); for (String arg : args.getNonOptionArgs()) { stream.write(arg.getBytes()); } diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java b/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java index b4e38d5e7ca..20362e4a599 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java @@ -24,9 +24,7 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer public class SampleJerseyApplication extends SpringBootServletInitializer { public static void main(String[] args) { - new SampleJerseyApplication() - .configure(new SpringApplicationBuilder(SampleJerseyApplication.class)) - .run(args); + new SampleJerseyApplication().configure(new SpringApplicationBuilder(SampleJerseyApplication.class)).run(args); } } diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/JerseyApplicationPathAndManagementPortTests.java b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/JerseyApplicationPathAndManagementPortTests.java index 48550664996..3cfbc090e8b 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/JerseyApplicationPathAndManagementPortTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/JerseyApplicationPathAndManagementPortTests.java @@ -33,8 +33,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "management.server.port=0", "spring.jersey.application-path=/app" }) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "management.server.port=0", "spring.jersey.application-path=/app" }) class JerseyApplicationPathAndManagementPortTests { @LocalServerPort @@ -48,9 +48,8 @@ class JerseyApplicationPathAndManagementPortTests { @Test void applicationPathShouldNotAffectActuators() { - ResponseEntity<String> entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.managementPort + "/actuator/health", - String.class); + ResponseEntity<String> entity = this.testRestTemplate + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java index 55ca2171238..3c12e5c4271 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java @@ -35,30 +35,26 @@ class SampleJerseyApplicationTests { @Test void contextLoads() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void reverse() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/reverse?input=olleh", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse?input=olleh", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); } @Test void validation() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test void actuatorStatus() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}"); } diff --git a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java index 7c7f34a33af..b237a978d73 100644 --- a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java @@ -59,13 +59,10 @@ class SampleJettyApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - try (GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody()))) { - assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)) - .isEqualTo("Hello World"); + try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()))) { + assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java b/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java index b38cb7bf2eb..68f58198207 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java +++ b/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java @@ -62,18 +62,15 @@ public class JooqExamples implements CommandLineRunner { } private void jooqSql() { - Query query = this.dsl.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME) - .from(BOOK).join(AUTHOR).on(BOOK.AUTHOR_ID.equal(AUTHOR.ID)) - .where(BOOK.PUBLISHED_IN.equal(2015)); + Query query = this.dsl.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME).from(BOOK).join(AUTHOR) + .on(BOOK.AUTHOR_ID.equal(AUTHOR.ID)).where(BOOK.PUBLISHED_IN.equal(2015)); Object[] bind = query.getBindValues().toArray(new Object[0]); - List<String> list = this.jdbc.query(query.getSQL(), bind, - new RowMapper<String>() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getString(1) + " : " + rs.getString(2) + " " - + rs.getString(3); - } - }); + List<String> list = this.jdbc.query(query.getSQL(), bind, new RowMapper<String>() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString(1) + " : " + rs.getString(2) + " " + rs.getString(3); + } + }); System.out.println("jOOQ SQL " + list); } diff --git a/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java b/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java index 86a9a548e55..a01e65d1562 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java @@ -35,8 +35,7 @@ class SampleJooqApplicationTests { @Test void outputResults(CapturedOutput capturedOutput) { SampleJooqApplication.main(NO_ARGS); - assertThat(capturedOutput).contains("jOOQ Fetch 1 Greg Turnquest") - .contains("jOOQ Fetch 2 Craig Walls") + assertThat(capturedOutput).contains("jOOQ Fetch 1 Greg Turnquest").contains("jOOQ Fetch 2 Craig Walls") .contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " + "Spring Boot in Action : Craig Walls]"); } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Note.java b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Note.java index 5079ba175f3..f9c1a8e147f 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Note.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Note.java @@ -28,8 +28,7 @@ import javax.persistence.SequenceGenerator; public class Note { @Id - @SequenceGenerator(name = "note_generator", sequenceName = "note_sequence", - initialValue = 5) + @SequenceGenerator(name = "note_generator", sequenceName = "note_sequence", initialValue = 5) @GeneratedValue(generator = "note_generator") private long id; diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Tag.java b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Tag.java index d5255f240d7..09c5673408e 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Tag.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/domain/Tag.java @@ -28,8 +28,7 @@ import javax.persistence.SequenceGenerator; public class Tag { @Id - @SequenceGenerator(name = "tag_generator", sequenceName = "tag_sequence", - initialValue = 4) + @SequenceGenerator(name = "tag_generator", sequenceName = "tag_sequence", initialValue = 4) @GeneratedValue(generator = "tag_generator") private long id; diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java index 1f18fd3f3f4..f530dd09971 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java @@ -33,8 +33,7 @@ class JpaNoteRepository implements NoteRepository { @Override public List<Note> findAll() { - return this.entityManager.createQuery("SELECT n FROM Note n", Note.class) - .getResultList(); + return this.entityManager.createQuery("SELECT n FROM Note n", Note.class).getResultList(); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java index 28cf6095dd9..4fbcd3d43cf 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java @@ -33,8 +33,7 @@ class JpaTagRepository implements TagRepository { @Override public List<Tag> findAll() { - return this.entityManager.createQuery("SELECT t FROM Tag t", Tag.class) - .getResultList(); + return this.entityManager.createQuery("SELECT t FROM Tag t", Tag.class).getResultList(); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java index 4bfa649b178..75ee122cf2b 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java @@ -52,8 +52,7 @@ class SampleJpaApplicationTests { @Test void testHome() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(xpath("//tbody/tr").nodeCount(4)); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(xpath("//tbody/tr").nodeCount(4)); } } diff --git a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java index beb4372d161..29518952d8b 100644 --- a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java +++ b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java @@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext; public class SampleAtomikosApplication { public static void main(String[] args) throws Exception { - ApplicationContext context = SpringApplication - .run(SampleAtomikosApplication.class, args); + ApplicationContext context = SpringApplication.run(SampleAtomikosApplication.class, args); AccountService service = context.getBean(AccountService.class); AccountRepository repository = context.getBean(AccountRepository.class); service.createAccountAndNotify("josh"); diff --git a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java index eb4759fcfb3..5cf3d2517b2 100644 --- a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java @@ -36,14 +36,12 @@ class SampleAtomikosApplicationTests { @Test void testTransactionRollback(CapturedOutput capturedOutput) throws Exception { SampleAtomikosApplication.main(new String[] {}); - assertThat(capturedOutput.toString()).has(substring(1, "---->")) - .has(substring(1, "----> josh")).has(substring(2, "Count is 1")) - .has(substring(1, "Simulated error")); + assertThat(capturedOutput.toString()).has(substring(1, "---->")).has(substring(1, "----> josh")) + .has(substring(2, "Count is 1")).has(substring(1, "Simulated error")); } private Condition<String> substring(int times, String substring) { - return new Condition<String>( - "containing '" + substring + "' " + times + " times") { + return new Condition<String>("containing '" + substring + "' " + times + " times") { @Override public boolean matches(String value) { diff --git a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java index 594e291b898..dfa42e8064f 100644 --- a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java +++ b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java @@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext; public class SampleBitronixApplication { public static void main(String[] args) throws Exception { - ApplicationContext context = SpringApplication - .run(SampleBitronixApplication.class, args); + ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class, args); AccountService service = context.getBean(AccountService.class); AccountRepository repository = context.getBean(AccountRepository.class); service.createAccountAndNotify("josh"); diff --git a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java index 2b2167f4f8d..fd77e2a2780 100644 --- a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java @@ -39,27 +39,23 @@ class SampleBitronixApplicationTests { @Test void testTransactionRollback(CapturedOutput capturedOutput) throws Exception { SampleBitronixApplication.main(new String[] {}); - assertThat(capturedOutput.toString()).has(substring(1, "---->")) - .has(substring(1, "----> josh")).has(substring(2, "Count is 1")) - .has(substring(1, "Simulated error")); + assertThat(capturedOutput.toString()).has(substring(1, "---->")).has(substring(1, "----> josh")) + .has(substring(2, "Count is 1")).has(substring(1, "Simulated error")); } @Test void testExposesXaAndNonXa() { - ApplicationContext context = SpringApplication - .run(SampleBitronixApplication.class); + ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class); Object jmsConnectionFactory = context.getBean("jmsConnectionFactory"); Object xaJmsConnectionFactory = context.getBean("xaJmsConnectionFactory"); Object nonXaJmsConnectionFactory = context.getBean("nonXaJmsConnectionFactory"); assertThat(jmsConnectionFactory).isSameAs(xaJmsConnectionFactory); assertThat(jmsConnectionFactory).isInstanceOf(PoolingConnectionFactory.class); - assertThat(nonXaJmsConnectionFactory) - .isNotInstanceOf(PoolingConnectionFactory.class); + assertThat(nonXaJmsConnectionFactory).isNotInstanceOf(PoolingConnectionFactory.class); } private Condition<String> substring(int times, String substring) { - return new Condition<String>( - "containing '" + substring + "' " + times + " times") { + return new Condition<String>("containing '" + substring + "' " + times + " times") { @Override public boolean matches(String value) { diff --git a/spring-boot-samples/spring-boot-sample-kafka/src/main/java/sample/kafka/SampleMessage.java b/spring-boot-samples/spring-boot-sample-kafka/src/main/java/sample/kafka/SampleMessage.java index 875fd9b027d..bd6cf687e8d 100644 --- a/spring-boot-samples/spring-boot-sample-kafka/src/main/java/sample/kafka/SampleMessage.java +++ b/spring-boot-samples/spring-boot-sample-kafka/src/main/java/sample/kafka/SampleMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ public class SampleMessage { private final String message; @JsonCreator - public SampleMessage(@JsonProperty("id") Integer id, - @JsonProperty("message") String message) { + public SampleMessage(@JsonProperty("id") Integer id, @JsonProperty("message") String message) { this.id = id; this.message = message; } diff --git a/spring-boot-samples/spring-boot-sample-kafka/src/test/java/sample/kafka/SampleKafkaApplicationTests.java b/spring-boot-samples/spring-boot-sample-kafka/src/test/java/sample/kafka/SampleKafkaApplicationTests.java index 06bb0eed8eb..a55d8aedf45 100644 --- a/spring-boot-samples/spring-boot-sample-kafka/src/test/java/sample/kafka/SampleKafkaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-kafka/src/test/java/sample/kafka/SampleKafkaApplicationTests.java @@ -30,8 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Gary Russell * @author Stephane Nicoll */ -@SpringBootTest( - properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}") +@SpringBootTest(properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}") @EmbeddedKafka(topics = "testTopic") class SampleKafkaApplicationTests { @@ -41,12 +40,10 @@ class SampleKafkaApplicationTests { @Test void testVanillaExchange() throws Exception { long end = System.currentTimeMillis() + 10000; - while (this.consumer.getMessages().isEmpty() - && System.currentTimeMillis() < end) { + while (this.consumer.getMessages().isEmpty() && System.currentTimeMillis() < end) { Thread.sleep(250); } - assertThat(this.consumer.getMessages()).extracting("message") - .containsOnly("A simple test message"); + assertThat(this.consumer.getMessages()).extracting("message").containsOnly("A simple test message"); } } diff --git a/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java b/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java index b0db276f31d..1198fe10fc3 100644 --- a/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java @@ -41,16 +41,12 @@ class SampleLiquibaseApplicationTests { } } assertThat(capturedOutput).contains("Successfully acquired change log lock") - .contains("Creating database history " - + "table with name: PUBLIC.DATABASECHANGELOG") + .contains("Creating database history " + "table with name: PUBLIC.DATABASECHANGELOG") .contains("Table person created") - .contains("ChangeSet classpath:/db/" - + "changelog/db.changelog-master.yaml::1::" - + "marceloverdijk ran successfully") - .contains("New row inserted into person") - .contains("ChangeSet classpath:/db/changelog/" - + "db.changelog-master.yaml::2::" + .contains("ChangeSet classpath:/db/" + "changelog/db.changelog-master.yaml::1::" + "marceloverdijk ran successfully") + .contains("New row inserted into person").contains("ChangeSet classpath:/db/changelog/" + + "db.changelog-master.yaml::2::" + "marceloverdijk ran successfully") .contains("Successfully released change log lock"); } diff --git a/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java b/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java index b6b7c51b898..bc24bc3ca12 100644 --- a/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java +++ b/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java @@ -27,8 +27,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SampleLogbackApplication { - private static final Logger logger = LoggerFactory - .getLogger(SampleLogbackApplication.class); + private static final Logger logger = LoggerFactory.getLogger(SampleLogbackApplication.class); @PostConstruct public void logSomething() { diff --git a/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java b/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java index 1401a460877..1682d2d4ff9 100644 --- a/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java @@ -30,16 +30,13 @@ class SampleLogbackApplicationTests { @Test void testLoadedCustomLogbackConfig(CapturedOutput capturedOutput) throws Exception { SampleLogbackApplication.main(new String[0]); - assertThat(capturedOutput).contains("Sample Debug Message") - .doesNotContain("Sample Trace Message"); + assertThat(capturedOutput).contains("Sample Debug Message").doesNotContain("Sample Trace Message"); } @Test void testProfile(CapturedOutput capturedOutput) throws Exception { - SampleLogbackApplication - .main(new String[] { "--spring.profiles.active=staging" }); - assertThat(capturedOutput).contains("Sample Debug Message") - .contains("Sample Trace Message"); + SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" }); + assertThat(capturedOutput).contains("Sample Debug Message").contains("Sample Trace Message"); } } diff --git a/spring-boot-samples/spring-boot-sample-oauth2-client/src/test/java/sample/oauth2/client/SampleOAuth2ClientApplicationTests.java b/spring-boot-samples/spring-boot-sample-oauth2-client/src/test/java/sample/oauth2/client/SampleOAuth2ClientApplicationTests.java index 72aad1be21d..ff0bc019890 100644 --- a/spring-boot-samples/spring-boot-sample-oauth2-client/src/test/java/sample/oauth2/client/SampleOAuth2ClientApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-oauth2-client/src/test/java/sample/oauth2/client/SampleOAuth2ClientApplicationTests.java @@ -31,8 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret", - "YAHOO-CLIENT-ID=my-yahoo-client-id", - "YAHOO-CLIENT-SECRET=my-yahoo-client-secret" }) + "YAHOO-CLIENT-ID=my-yahoo-client-id", "YAHOO-CLIENT-SECRET=my-yahoo-client-secret" }) class SampleOAuth2ClientApplicationTests { @LocalServerPort @@ -45,14 +44,12 @@ class SampleOAuth2ClientApplicationTests { void everythingShouldRedirectToLogin() { ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()) - .isEqualTo(URI.create("http://localhost:" + this.port + "/login")); + assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login")); } @Test void loginShouldHaveAllOAuth2ClientsToChooseFrom() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/login", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("/oauth2/authorization/yahoo"); assertThat(entity.getBody()).contains("/oauth2/authorization/github-client-1"); diff --git a/spring-boot-samples/spring-boot-sample-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java b/spring-boot-samples/spring-boot-sample-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java index 896675cf5c4..68a22a463cd 100644 --- a/spring-boot-samples/spring-boot-sample-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java @@ -68,8 +68,7 @@ class SampleOauth2ResourceServerApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(VALID_TOKEN); HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - request, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -77,8 +76,7 @@ class SampleOauth2ResourceServerApplicationTests { void withNoBearerTokenShouldNotAllowAccess() { HttpHeaders headers = new HttpHeaders(); HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - request, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @@ -100,8 +98,7 @@ class SampleOauth2ResourceServerApplicationTests { + "V9gWuOzSJ0iEuWvtQ6eGBP5M6m7pccLNZfwUse8Cb4Ngx3XiTlyuqM7pv0LPyppZusfEHVEdeelou7Dy9k0OQ_nJTI3b2E1WBoHC5" + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; - return new MockResponse() - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(200).setBody(body); } diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java b/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java index 85865ea3f37..0036b584d50 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java @@ -35,8 +35,7 @@ import org.springframework.integration.file.FileWritingMessageHandler; public class SampleParentContextApplication { public static void main(String[] args) throws Exception { - new SpringApplicationBuilder(Parent.class) - .child(SampleParentContextApplication.class).run(args); + new SpringApplicationBuilder(Parent.class).child(SampleParentContextApplication.class).run(args); } @Configuration(proxyBeanMethods = false) @@ -68,21 +67,18 @@ public class SampleParentContextApplication { @Bean public FileWritingMessageHandler fileWriter() { - FileWritingMessageHandler writer = new FileWritingMessageHandler( - this.serviceProperties.getOutputDir()); + FileWritingMessageHandler writer = new FileWritingMessageHandler(this.serviceProperties.getOutputDir()); writer.setExpectReply(false); return writer; } @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlows.from(fileReader(), new FixedRatePoller()) - .channel(inputChannel()).handle(endpoint).channel(outputChannel()) - .handle(fileWriter()).get(); + return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) + .channel(outputChannel()).handle(fileWriter()).get(); } - private static class FixedRatePoller - implements Consumer<SourcePollingChannelAdapterSpec> { + private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> { @Override public void accept(SourcePollingChannelAdapterSpec spec) { diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java index 7e3b8d2763b..db06fc9738a 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java @@ -46,13 +46,11 @@ class SampleIntegrationParentApplicationTests { void testVanillaExchange(@TempDir Path temp) throws Exception { File inputDir = new File(temp.toFile(), "input"); File outputDir = new File(temp.toFile(), "output"); - ConfigurableApplicationContext app = SpringApplication.run( - SampleParentContextApplication.class, "--service.input-dir=" + inputDir, - "--service.output-dir=" + outputDir); + ConfigurableApplicationContext app = SpringApplication.run(SampleParentContextApplication.class, + "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir); try { - ConfigurableApplicationContext producer = SpringApplication.run( - ProducerApplication.class, "--service.input-dir=" + inputDir, - "--service.output-dir=" + outputDir, "World"); + ConfigurableApplicationContext producer = SpringApplication.run(ProducerApplication.class, + "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir, "World"); try { awaitOutputContaining(outputDir, "Hello World"); } @@ -65,8 +63,7 @@ class SampleIntegrationParentApplicationTests { } } - private void awaitOutputContaining(File outputDir, String requiredContents) - throws Exception { + private void awaitOutputContaining(File outputDir, String requiredContents) throws Exception { long endTime = System.currentTimeMillis() + 30000; String output = null; while (System.currentTimeMillis() < endTime) { @@ -86,21 +83,18 @@ class SampleIntegrationParentApplicationTests { } } } - fail("Timed out awaiting output containing '" + requiredContents - + "'. Output was '" + output + "'"); + fail("Timed out awaiting output containing '" + requiredContents + "'. Output was '" + output + "'"); } private Resource[] findResources(File outputDir) throws IOException { - return ResourcePatternUtils - .getResourcePatternResolver(new DefaultResourceLoader()) + return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); } private String readResources(Resource[] resources) throws IOException { StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { - builder.append( - new String(StreamUtils.copyToByteArray(resource.getInputStream()))); + builder.append(new String(StreamUtils.copyToByteArray(resource.getInputStream()))); } return builder.toString(); } diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java index 7cdd6d8f6f6..245e9b03b80 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java @@ -42,8 +42,7 @@ public class ProducerApplication implements ApplicationRunner { this.serviceProperties.getInputDir().mkdirs(); if (args.getNonOptionArgs().size() > 0) { FileOutputStream stream = new FileOutputStream( - new File(this.serviceProperties.getInputDir(), - "data" + System.currentTimeMillis() + ".txt")); + new File(this.serviceProperties.getInputDir(), "data" + System.currentTimeMillis() + ".txt")); for (String arg : args.getNonOptionArgs()) { stream.write(arg.getBytes()); } diff --git a/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java b/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java index 89e70ccf2f6..d841e3ab8f5 100644 --- a/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java @@ -74,8 +74,7 @@ class SampleProfileApplicationTests { @Test void testGoodbyeProfileFromCommandline(CapturedOutput capturedOutput) { - SampleProfileApplication - .main(new String[] { "--spring.profiles.active=goodbye" }); + SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" }); assertThat(capturedOutput).contains("Goodbye Everyone"); } diff --git a/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java b/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java index c4472f4a908..277b1a9f13d 100644 --- a/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java +++ b/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java @@ -36,8 +36,7 @@ public class SamplePropertiesValidator implements Validator { ValidationUtils.rejectIfEmpty(errors, "host", "host.empty"); ValidationUtils.rejectIfEmpty(errors, "port", "port.empty"); SampleProperties properties = (SampleProperties) o; - if (properties.getHost() != null - && !this.pattern.matcher(properties.getHost()).matches()) { + if (properties.getHost() != null && !this.pattern.matcher(properties.getHost()).matches()) { errors.rejectValue("host", "Invalid host"); } } diff --git a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java index ae8bda6cb7c..abe3ab92a03 100644 --- a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java @@ -45,8 +45,7 @@ class SamplePropertyValidationApplicationTests { @Test void bindValidProperties() { this.context.register(SamplePropertyValidationApplication.class); - TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090") - .applyTo(this.context); + TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090").applyTo(this.context); this.context.refresh(); SampleProperties properties = this.context.getBean(SampleProperties.class); assertThat(properties.getHost()).isEqualTo("192.168.0.1"); @@ -56,18 +55,15 @@ class SamplePropertyValidationApplicationTests { @Test void bindInvalidHost() { this.context.register(SamplePropertyValidationApplication.class); - TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090") - .applyTo(this.context); - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> this.context.refresh()) + TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090").applyTo(this.context); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh()) .withMessageContaining("Failed to bind properties under 'sample'"); } @Test void bindNullHost() { this.context.register(SamplePropertyValidationApplication.class); - assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> this.context.refresh()) + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh()) .withMessageContaining("Failed to bind properties under 'sample'"); } @@ -75,8 +71,7 @@ class SamplePropertyValidationApplicationTests { void validatorOnlyCalledOnSupportedClass() { this.context.register(SamplePropertyValidationApplication.class); this.context.register(ServerProperties.class); // our validator will not apply - TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090") - .applyTo(this.context); + TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090").applyTo(this.context); this.context.refresh(); SampleProperties properties = this.context.getBean(SampleProperties.class); assertThat(properties.getHost()).isEqualTo("192.168.0.1"); diff --git a/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleJob.java b/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleJob.java index 89b09de03c1..a0449fe9bfd 100644 --- a/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleJob.java +++ b/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleJob.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ public class SampleJob extends QuartzJobBean { } @Override - protected void executeInternal(JobExecutionContext context) - throws JobExecutionException { + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { System.out.println(String.format("Hello %s!", this.name)); } diff --git a/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleQuartzApplication.java b/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleQuartzApplication.java index 9590d0667a6..c6300b64f76 100644 --- a/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleQuartzApplication.java +++ b/spring-boot-samples/spring-boot-sample-quartz/src/main/java/sample/quartz/SampleQuartzApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,17 +35,17 @@ public class SampleQuartzApplication { @Bean public JobDetail sampleJobDetail() { - return JobBuilder.newJob(SampleJob.class).withIdentity("sampleJob") - .usingJobData("name", "World").storeDurably().build(); + return JobBuilder.newJob(SampleJob.class).withIdentity("sampleJob").usingJobData("name", "World").storeDurably() + .build(); } @Bean public Trigger sampleJobTrigger() { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(2).repeatForever(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2) + .repeatForever(); - return TriggerBuilder.newTrigger().forJob(sampleJobDetail()) - .withIdentity("sampleTrigger").withSchedule(scheduleBuilder).build(); + return TriggerBuilder.newTrigger().forJob(sampleJobDetail()).withIdentity("sampleTrigger") + .withSchedule(scheduleBuilder).build(); } } diff --git a/spring-boot-samples/spring-boot-sample-quartz/src/test/java/sample/quartz/SampleQuartzApplicationTests.java b/spring-boot-samples/spring-boot-sample-quartz/src/test/java/sample/quartz/SampleQuartzApplicationTests.java index bd940e78b86..9ca0a44681d 100644 --- a/spring-boot-samples/spring-boot-sample-quartz/src/test/java/sample/quartz/SampleQuartzApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-quartz/src/test/java/sample/quartz/SampleQuartzApplicationTests.java @@ -36,11 +36,9 @@ class SampleQuartzApplicationTests { @Test void quartzJobIsTriggered(CapturedOutput capturedOutput) throws InterruptedException { - try (ConfigurableApplicationContext context = SpringApplication - .run(SampleQuartzApplication.class)) { + try (ConfigurableApplicationContext context = SpringApplication.run(SampleQuartzApplication.class)) { long end = System.currentTimeMillis() + 5000; - while ((!capturedOutput.toString().contains("Hello World!")) - && System.currentTimeMillis() < end) { + while ((!capturedOutput.toString().contains("Hello World!")) && System.currentTimeMillis() < end) { Thread.sleep(100); } assertThat(capturedOutput).contains("Hello World!"); diff --git a/spring-boot-samples/spring-boot-sample-reactive-oauth2-client/src/test/java/sample/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java b/spring-boot-samples/spring-boot-sample-reactive-oauth2-client/src/test/java/sample/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java index 86923dd6ce7..3cc8c54e230 100644 --- a/spring-boot-samples/spring-boot-sample-reactive-oauth2-client/src/test/java/sample/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-reactive-oauth2-client/src/test/java/sample/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java @@ -26,8 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret", - "YAHOO-CLIENT-ID=my-google-client-id", - "YAHOO-CLIENT-SECRET=my-google-client-secret" }) + "YAHOO-CLIENT-ID=my-google-client-id", "YAHOO-CLIENT-SECRET=my-google-client-secret" }) class SampleReactiveOAuth2ClientApplicationTests { @Autowired @@ -35,14 +34,14 @@ class SampleReactiveOAuth2ClientApplicationTests { @Test void everythingShouldRedirectToLogin() { - this.webTestClient.get().uri("/").exchange().expectStatus().isFound() - .expectHeader().valueEquals("Location", "/login"); + this.webTestClient.get().uri("/").exchange().expectStatus().isFound().expectHeader().valueEquals("Location", + "/login"); } @Test void loginShouldHaveBothOAuthClientsToChooseFrom() { - byte[] body = this.webTestClient.get().uri("/login").exchange().expectStatus() - .isOk().returnResult(String.class).getResponseBodyContent(); + byte[] body = this.webTestClient.get().uri("/login").exchange().expectStatus().isOk().returnResult(String.class) + .getResponseBodyContent(); String bodyString = new String(body); assertThat(bodyString).contains("/oauth2/authorization/yahoo"); assertThat(bodyString).contains("/oauth2/authorization/github-client-1"); diff --git a/spring-boot-samples/spring-boot-sample-reactive-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java b/spring-boot-samples/spring-boot-sample-reactive-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java index ec63d663e11..3a01eef95b6 100644 --- a/spring-boot-samples/spring-boot-sample-reactive-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-reactive-oauth2-resource-server/src/test/java/sample/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java @@ -58,16 +58,14 @@ class SampleReactiveOAuth2ResourceServerApplicationTests { @Test void getWhenValidTokenShouldBeOk() { - this.webTestClient.get().uri("/") - .headers((headers) -> headers.setBearerAuth(VALID_TOKEN)).exchange() - .expectStatus().isOk().expectBody(String.class) - .isEqualTo("Hello, subject!"); + this.webTestClient.get().uri("/").headers((headers) -> headers.setBearerAuth(VALID_TOKEN)).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, subject!"); } @Test void getWhenNoTokenShouldBeUnauthorized() { - this.webTestClient.get().uri("/").exchange().expectStatus().isUnauthorized() - .expectHeader().valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); + this.webTestClient.get().uri("/").exchange().expectStatus().isUnauthorized().expectHeader() + .valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); } private static MockResponse mockResponse() { @@ -88,8 +86,7 @@ class SampleReactiveOAuth2ResourceServerApplicationTests { + "V9gWuOzSJ0iEuWvtQ6eGBP5M6m7pccLNZfwUse8Cb4Ngx3XiTlyuqM7pv0LPyppZusfEHVEdeelou7Dy9k0OQ_nJTI3b2E1WBoHC5" + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; - return new MockResponse() - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(200).setBody(body); } diff --git a/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/ManagementPortSampleSecureWebFluxTests.java b/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/ManagementPortSampleSecureWebFluxTests.java index c42fdaf200c..255b1333fa9 100644 --- a/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/ManagementPortSampleSecureWebFluxTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/ManagementPortSampleSecureWebFluxTests.java @@ -41,10 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.server.port=0" }, - classes = { ManagementPortSampleSecureWebFluxTests.SecurityConfiguration.class, - SampleSecureWebFluxApplication.class }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0" }, classes = { + ManagementPortSampleSecureWebFluxTests.SecurityConfiguration.class, SampleSecureWebFluxApplication.class }) class ManagementPortSampleSecureWebFluxTests { @LocalServerPort @@ -59,35 +57,29 @@ class ManagementPortSampleSecureWebFluxTests { @Test void testHome() { this.webClient.get().uri("http://localhost:" + this.port, String.class) - .header("Authorization", "basic " + getBasicAuth()).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("Hello user"); + .header("Authorization", "basic " + getBasicAuth()).exchange().expectStatus().isOk() + .expectBody(String.class).isEqualTo("Hello user"); } @Test void actuatorPathOnMainPortShouldNotMatch() { - this.webClient.get() - .uri("http://localhost:" + this.port + "/actuator", String.class) - .exchange().expectStatus().isUnauthorized(); - this.webClient.get() - .uri("http://localhost:" + this.port + "/actuator/health", String.class) - .exchange().expectStatus().isUnauthorized(); + this.webClient.get().uri("http://localhost:" + this.port + "/actuator", String.class).exchange().expectStatus() + .isUnauthorized(); + this.webClient.get().uri("http://localhost:" + this.port + "/actuator/health", String.class).exchange() + .expectStatus().isUnauthorized(); } @Test void testSecureActuator() { - this.webClient.get() - .uri("http://localhost:" + this.managementPort + "/actuator/env", - String.class) - .exchange().expectStatus().isUnauthorized(); + this.webClient.get().uri("http://localhost:" + this.managementPort + "/actuator/env", String.class).exchange() + .expectStatus().isUnauthorized(); } @Test void testInsecureActuator() { String responseBody = this.webClient.get() - .uri("http://localhost:" + this.managementPort + "/actuator/health", - String.class) - .exchange().expectStatus().isOk().expectBody(String.class).returnResult() - .getResponseBody(); + .uri("http://localhost:" + this.managementPort + "/actuator/health", String.class).exchange() + .expectStatus().isOk().expectBody(String.class).returnResult().getResponseBody(); assertThat(responseBody).contains("\"status\":\"UP\""); } @@ -100,14 +92,10 @@ class ManagementPortSampleSecureWebFluxTests { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - return http.authorizeExchange().matchers(EndpointRequest.to("health", "info")) - .permitAll() - .matchers(EndpointRequest.toAnyEndpoint() - .excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR") - .matchers(PathRequest.toStaticResources().atCommonLocations()) - .permitAll().pathMatchers("/login").permitAll().anyExchange() - .authenticated().and().httpBasic().and().build(); + return http.authorizeExchange().matchers(EndpointRequest.to("health", "info")).permitAll() + .matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)).hasRole("ACTUATOR") + .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll().pathMatchers("/login") + .permitAll().anyExchange().authenticated().and().httpBasic().and().build(); } } diff --git a/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxApplicationTests.java index 8c1f0302c42..5c61fad0a9d 100644 --- a/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxApplicationTests.java @@ -40,40 +40,39 @@ class SampleSecureWebFluxApplicationTests { @Test void userDefinedMappingsSecureByDefault() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); + this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void healthInsecureByDefault() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk(); + this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isOk(); } @Test void infoInsecureByDefault() { - this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk(); + this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk(); } @Test void otherActuatorsSecureByDefault() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isUnauthorized(); + this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isUnauthorized(); } @Test void userDefinedMappingsAccessibleOnLogin() { this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "basic " + getBasicAuth()).exchange() - .expectBody(String.class).isEqualTo("Hello user"); + .header("Authorization", "basic " + getBasicAuth()).exchange().expectBody(String.class) + .isEqualTo("Hello user"); } @Test void actuatorsAccessibleOnLogin() { this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "basic " + getBasicAuth()).exchange() - .expectBody(String.class).isEqualTo("{\"status\":\"UP\"}"); + .header("Authorization", "basic " + getBasicAuth()).exchange().expectBody(String.class) + .isEqualTo("{\"status\":\"UP\"}"); } private String getBasicAuth() { diff --git a/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java b/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java index 0d41d04a6f3..8d490c3703d 100644 --- a/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-webflux/src/test/java/sample/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java @@ -40,9 +40,8 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Madhura Bhave */ -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - classes = { SampleSecureWebFluxCustomSecurityTests.SecurityConfiguration.class, - SampleSecureWebFluxApplication.class }) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = { + SampleSecureWebFluxCustomSecurityTests.SecurityConfiguration.class, SampleSecureWebFluxApplication.class }) class SampleSecureWebFluxCustomSecurityTests { @Autowired @@ -50,52 +49,47 @@ class SampleSecureWebFluxCustomSecurityTests { @Test void userDefinedMappingsSecure() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); + this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void healthAndInfoDoNotRequireAuthentication() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk(); - this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk(); + this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isOk(); + this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk(); } @Test void actuatorsSecuredByRole() { this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "basic " + getBasicAuth()).exchange() - .expectStatus().isForbidden(); + .header("Authorization", "basic " + getBasicAuth()).exchange().expectStatus().isForbidden(); } @Test void actuatorsAccessibleOnCorrectLogin() { this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "basic " + getBasicAuthForAdmin()).exchange() - .expectStatus().isOk(); + .header("Authorization", "basic " + getBasicAuthForAdmin()).exchange().expectStatus().isOk(); } @Test void actuatorExcludedFromEndpointRequestMatcher() { this.webClient.get().uri("/actuator/mappings").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "basic " + getBasicAuth()).exchange() - .expectStatus().isOk(); + .header("Authorization", "basic " + getBasicAuth()).exchange().expectStatus().isOk(); } @Test void staticResourceShouldBeAccessible() { - this.webClient.get().uri("/css/bootstrap.min.css") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk(); + this.webClient.get().uri("/css/bootstrap.min.css").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isOk(); } @Test void actuatorLinksIsSecure() { + this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() + .isUnauthorized(); this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isUnauthorized(); - this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "basic " + getBasicAuthForAdmin()).exchange() - .expectStatus().isOk(); + .header("Authorization", "basic " + getBasicAuthForAdmin()).exchange().expectStatus().isOk(); } private String getBasicAuth() { @@ -113,22 +107,18 @@ class SampleSecureWebFluxCustomSecurityTests { @Bean public MapReactiveUserDetailsService userDetailsService() { return new MapReactiveUserDetailsService( - User.withDefaultPasswordEncoder().username("user") - .password("password").authorities("ROLE_USER").build(), + User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER") + .build(), User.withDefaultPasswordEncoder().username("admin").password("admin") .authorities("ROLE_ACTUATOR", "ROLE_USER").build()); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - return http.authorizeExchange().matchers(EndpointRequest.to("health", "info")) - .permitAll() - .matchers(EndpointRequest.toAnyEndpoint() - .excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR") - .matchers(PathRequest.toStaticResources().atCommonLocations()) - .permitAll().pathMatchers("/login").permitAll().anyExchange() - .authenticated().and().httpBasic().and().build(); + return http.authorizeExchange().matchers(EndpointRequest.to("health", "info")).permitAll() + .matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)).hasRole("ACTUATOR") + .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll().pathMatchers("/login") + .permitAll().anyExchange().authenticated().and().httpBasic().and().build(); } } diff --git a/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java b/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java index 60ec68c3a24..ec0afa4be33 100644 --- a/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java +++ b/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java @@ -36,9 +36,8 @@ public class SampleSecureApplication implements CommandLineRunner { @Override public void run(String... args) throws Exception { - SecurityContextHolder.getContext() - .setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", - AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", + AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); try { System.out.println(this.service.secure()); } diff --git a/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java b/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java index 0706d1e9552..e27a5914f5b 100644 --- a/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java +++ b/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java @@ -40,8 +40,7 @@ public class SampleServletApplication extends SpringBootServletInitializer { public Servlet dispatcherServlet() { return new GenericServlet() { @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); res.getWriter().append("Hello World"); } diff --git a/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java b/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java index 6614e1d69d5..c8af28e4a46 100644 --- a/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java @@ -48,15 +48,15 @@ class SampleServletApplicationTests { void testHomeIsSecure() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } diff --git a/spring-boot-samples/spring-boot-sample-session-webflux/src/test/java/sample/session/SampleSessionWebFluxApplicationTests.java b/spring-boot-samples/spring-boot-sample-session-webflux/src/test/java/sample/session/SampleSessionWebFluxApplicationTests.java index 018d03267a4..6eb2df44220 100644 --- a/spring-boot-samples/spring-boot-sample-session-webflux/src/test/java/sample/session/SampleSessionWebFluxApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-session-webflux/src/test/java/sample/session/SampleSessionWebFluxApplicationTests.java @@ -48,22 +48,17 @@ class SampleSessionWebFluxApplicationTests { @Test void userDefinedMappingsSecureByDefault() throws Exception { - WebClient webClient = this.webClientBuilder - .baseUrl("http://localhost:" + this.port + "/").build(); - ClientResponse response = webClient.get().header("Authorization", getBasicAuth()) - .exchange().block(Duration.ofSeconds(30)); + WebClient webClient = this.webClientBuilder.baseUrl("http://localhost:" + this.port + "/").build(); + ClientResponse response = webClient.get().header("Authorization", getBasicAuth()).exchange() + .block(Duration.ofSeconds(30)); assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); ResponseCookie sessionCookie = response.cookies().getFirst("SESSION"); - String sessionId = response.bodyToMono(String.class) - .block(Duration.ofSeconds(30)); - response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange() - .block(Duration.ofSeconds(30)); + String sessionId = response.bodyToMono(String.class).block(Duration.ofSeconds(30)); + response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange().block(Duration.ofSeconds(30)); assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.bodyToMono(String.class).block(Duration.ofSeconds(30))) - .isEqualTo(sessionId); + assertThat(response.bodyToMono(String.class).block(Duration.ofSeconds(30))).isEqualTo(sessionId); Thread.sleep(2000); - response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange() - .block(Duration.ofSeconds(30)); + response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange().block(Duration.ofSeconds(30)); assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-samples/spring-boot-sample-session/src/test/java/sample/session/SampleSessionApplicationTests.java b/spring-boot-samples/spring-boot-sample-session/src/test/java/sample/session/SampleSessionApplicationTests.java index 395370872a8..c7b973555ad 100644 --- a/spring-boot-samples/spring-boot-sample-session/src/test/java/sample/session/SampleSessionApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-session/src/test/java/sample/session/SampleSessionApplicationTests.java @@ -57,8 +57,7 @@ class SampleSessionApplicationTests { } private ConfigurableApplicationContext createContext() { - ConfigurableApplicationContext context = new SpringApplicationBuilder() - .sources(SampleSessionApplication.class) + ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(SampleSessionApplication.class) .properties("server.port:0", "server.servlet.session.timeout:1") .initializers(new ServerPortInfoApplicationContextInitializer()).run(); return context; @@ -66,14 +65,12 @@ class SampleSessionApplicationTests { private ResponseEntity<String> firstRequest(RestTemplate restTemplate, URI uri) { HttpHeaders headers = new HttpHeaders(); - headers.set("Authorization", "Basic " - + Base64.getEncoder().encodeToString("user:password".getBytes())); + headers.set("Authorization", "Basic " + Base64.getEncoder().encodeToString("user:password".getBytes())); RequestEntity<Object> request = new RequestEntity<>(headers, HttpMethod.GET, uri); return restTemplate.exchange(request, String.class); } - private ResponseEntity<String> nextRequest(RestTemplate restTemplate, URI uri, - String cookie) { + private ResponseEntity<String> nextRequest(RestTemplate restTemplate, URI uri, String cookie) { HttpHeaders headers = new HttpHeaders(); headers.set("Cookie", cookie); RequestEntity<Object> request = new RequestEntity<>(headers, HttpMethod.GET, uri); diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java index 67f2bd00968..3865cb3b17e 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,15 +35,12 @@ import org.springframework.web.client.RestTemplate; @Service public class RemoteVehicleDetailsService implements VehicleDetailsService { - private static final Log logger = LogFactory - .getLog(RemoteVehicleDetailsService.class); + private static final Log logger = LogFactory.getLog(RemoteVehicleDetailsService.class); private final RestTemplate restTemplate; - public RemoteVehicleDetailsService(ServiceProperties properties, - RestTemplateBuilder restTemplateBuilder) { - this.restTemplate = restTemplateBuilder - .rootUri(properties.getVehicleServiceRootUrl()).build(); + public RemoteVehicleDetailsService(ServiceProperties properties, RestTemplateBuilder restTemplateBuilder) { + this.restTemplate = restTemplateBuilder.rootUri(properties.getVehicleServiceRootUrl()).build(); } @Override @@ -52,8 +49,7 @@ public class RemoteVehicleDetailsService implements VehicleDetailsService { Assert.notNull(vin, "VIN must not be null"); logger.debug("Retrieving vehicle data for: " + vin); try { - return this.restTemplate.getForObject("/vehicle/{vin}/details", - VehicleDetails.class, vin); + return this.restTemplate.getForObject("/vehicle/{vin}/details", VehicleDetails.class, vin); } catch (HttpStatusCodeException ex) { if (HttpStatus.NOT_FOUND.equals(ex.getStatusCode())) { diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java index 118c81830f5..2dad1455f14 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class VehicleDetails { private final String model; @JsonCreator - public VehicleDetails(@JsonProperty("make") String make, - @JsonProperty("model") String model) { + public VehicleDetails(@JsonProperty("make") String make, @JsonProperty("model") String model) { Assert.notNull(make, "Make must not be null"); Assert.notNull(model, "Model must not be null"); this.make = make; diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java index 3a519d491b3..a7ee16f762b 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ public class VehicleIdentificationNumberNotFoundException extends RuntimeExcepti this(vin, null); } - public VehicleIdentificationNumberNotFoundException(VehicleIdentificationNumber vin, - Throwable cause) { + public VehicleIdentificationNumberNotFoundException(VehicleIdentificationNumber vin, Throwable cause) { super("Unable to find VehicleIdentificationNumber " + vin, cause); this.vehicleIdentificationNumber = vin; } diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java index e2933572380..8b22f4dd8db 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,15 +37,13 @@ public class UserVehicleService { private final VehicleDetailsService vehicleDetailsService; - public UserVehicleService(UserRepository userRepository, - VehicleDetailsService vehicleDetailsService) { + public UserVehicleService(UserRepository userRepository, VehicleDetailsService vehicleDetailsService) { this.userRepository = userRepository; this.vehicleDetailsService = vehicleDetailsService; } public VehicleDetails getVehicleDetails(String username) - throws UserNameNotFoundException, - VehicleIdentificationNumberNotFoundException { + throws UserNameNotFoundException, VehicleIdentificationNumberNotFoundException { Assert.notNull(username, "Username must not be null"); User user = this.userRepository.findByUsername(username); if (user == null) { diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java index 71b2a89009a..fa6b25272e0 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java @@ -40,8 +40,7 @@ import static org.mockito.BDDMockito.given; @AutoConfigureTestDatabase class SampleTestApplicationWebIntegrationTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "01234567890123456"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("01234567890123456"); @Autowired private TestRestTemplate restTemplate; @@ -51,8 +50,7 @@ class SampleTestApplicationWebIntegrationTests { @BeforeEach public void setup() { - given(this.vehicleDetailsService.getVehicleDetails(VIN)) - .willReturn(new VehicleDetails("Honda", "Civic")); + given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(new VehicleDetails("Honda", "Civic")); } @Test diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java index 44f9169ba8a..16dfc7ea7be 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java @@ -33,8 +33,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException @DataJpaTest class UserEntityTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Autowired private TestEntityManager entityManager; diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java index ebb24af2d60..9479c8205c1 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java @@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest class UserRepositoryTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Autowired private TestEntityManager entityManager; diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java index 8d982de2f3f..4dc8e04582d 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java @@ -35,22 +35,19 @@ class VehicleIdentificationNumberTests { @Test void createWhenVinIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new VehicleIdentificationNumber(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber(null)) .withMessage("VIN must not be null"); } @Test void createWhenVinIsMoreThan17CharsShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new VehicleIdentificationNumber("012345678901234567")) + assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber("012345678901234567")) .withMessage("VIN must be exactly 17 characters"); } @Test void createWhenVinIsLessThan17CharsShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new VehicleIdentificationNumber("0123456789012345")) + assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber("0123456789012345")) .withMessage("VIN must be exactly 17 characters"); } @@ -64,8 +61,7 @@ class VehicleIdentificationNumberTests { void equalsAndHashCodeShouldBeBasedOnVin() { VehicleIdentificationNumber vin1 = new VehicleIdentificationNumber(SAMPLE_VIN); VehicleIdentificationNumber vin2 = new VehicleIdentificationNumber(SAMPLE_VIN); - VehicleIdentificationNumber vin3 = new VehicleIdentificationNumber( - "00000000000000000"); + VehicleIdentificationNumber vin3 = new VehicleIdentificationNumber("00000000000000000"); assertThat(vin1.hashCode()).isEqualTo(vin2.hashCode()); assertThat(vin1).isEqualTo(vin1).isEqualTo(vin2).isNotEqualTo(vin3); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java index 6c61aa95ce7..8e844953837 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java @@ -53,38 +53,31 @@ class RemoteVehicleDetailsServiceTests { @Test void getVehicleDetailsWhenVinIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.service.getVehicleDetails(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.service.getVehicleDetails(null)) .withMessage("VIN must not be null"); } @Test void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), - MediaType.APPLICATION_JSON)); - VehicleDetails details = this.service - .getVehicleDetails(new VehicleIdentificationNumber(VIN)); + .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), MediaType.APPLICATION_JSON)); + VehicleDetails details = this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); assertThat(details.getMake()).isEqualTo("Honda"); assertThat(details.getModel()).isEqualTo("Civic"); } @Test void getVehicleDetailsWhenResultIsNotFoundShouldThrowException() { - this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); + this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withStatus(HttpStatus.NOT_FOUND)); assertThatExceptionOfType(VehicleIdentificationNumberNotFoundException.class) - .isThrownBy(() -> this.service - .getVehicleDetails(new VehicleIdentificationNumber(VIN))); + .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); } @Test void getVehicleDetailsWhenResultIServerErrorShouldThrowException() { - this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withServerError()); + this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withServerError()); assertThatExceptionOfType(HttpServerErrorException.class) - .isThrownBy(() -> this.service - .getVehicleDetails(new VehicleIdentificationNumber(VIN))); + .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); } private ClassPathResource getClassPathResource(String path) { diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java index c089520a8aa..f0ad51d7095 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java @@ -41,15 +41,13 @@ class VehicleDetailsJsonTests { assertThat(this.json.write(details)).isEqualTo("vehicledetails.json"); assertThat(this.json.write(details)).isEqualToJson("vehicledetails.json"); assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); - assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") - .isEqualTo("Honda"); + assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make").isEqualTo("Honda"); } @Test void deserializeJson() throws Exception { String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; - assertThat(this.json.parse(content)) - .isEqualTo(new VehicleDetails("Ford", "Focus")); + assertThat(this.json.parse(content)).isEqualTo(new VehicleDetails("Ford", "Focus")); assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java index c9386ffdca7..e2339cc1160 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java @@ -56,17 +56,15 @@ class UserVehicleControllerApplicationTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test void welcomeCommandLineRunnerShouldBeAvailable() { // Since we're a @SpringBootTest all beans should be available. - assertThat(this.applicationContext.getBean(WelcomeCommandLineRunner.class)) - .isNotNull(); + assertThat(this.applicationContext.getBean(WelcomeCommandLineRunner.class)).isNotNull(); } } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java index 47ba7bee3ad..5e9f5d7965b 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java @@ -44,8 +44,7 @@ class UserVehicleControllerHtmlUnitTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java index 01953c4e9ae..4d3214427b3 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java @@ -45,8 +45,7 @@ class UserVehicleControllerSeleniumTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); this.webDriver.get("/sboot/vehicle.html"); WebElement element = this.webDriver.findElement(By.tagName("h1")); assertThat(element.getText()).isEqualTo("Honda Civic"); diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java index f8182a1e891..f82c2224b6f 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java @@ -45,8 +45,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WebMvcTest(UserVehicleController.class) class UserVehicleControllerTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Autowired private MockMvc mvc; @@ -59,34 +58,28 @@ class UserVehicleControllerTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test void getVehicleWhenRequestingJsonShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json("{'make':'Honda','model':'Civic'}")); } @Test void getVehicleWhenRequestingHtmlShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)) - .andExpect(status().isOk()) + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) .andExpect(content().string(containsString("<h1>Honda Civic</h1>"))); } @Test void getVehicleWhenUserNotFoundShouldReturnNotFound() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willThrow(new UserNameNotFoundException("sboot")); + given(this.userVehicleService.getVehicleDetails("sboot")).willThrow(new UserNameNotFoundException("sboot")); this.mvc.perform(get("/sboot/vehicle")).andExpect(status().isNotFound()); } @@ -100,8 +93,7 @@ class UserVehicleControllerTests { @Test void welcomeCommandLineRunnerShouldBeAvailable() { // Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available. - Assertions.assertThatThrownBy( - () -> this.applicationContext.getBean(WelcomeCommandLineRunner.class)) + Assertions.assertThatThrownBy(() -> this.applicationContext.getBean(WelcomeCommandLineRunner.class)) .isInstanceOf(NoSuchBeanDefinitionException.class); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java index ba73ec68224..f709d1ee3ea 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java @@ -39,8 +39,7 @@ import static org.mockito.BDDMockito.given; */ class UserVehicleServiceTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Mock private VehicleDetailsService vehicleDetailsService; @@ -53,14 +52,12 @@ class UserVehicleServiceTests { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - this.service = new UserVehicleService(this.userRepository, - this.vehicleDetailsService); + this.service = new UserVehicleService(this.userRepository, this.vehicleDetailsService); } @Test void getVehicleDetailsWhenUsernameIsNullShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.service.getVehicleDetails(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.service.getVehicleDetails(null)) .withMessage("Username must not be null"); } @@ -73,8 +70,7 @@ class UserVehicleServiceTests { @Test void getVehicleDetailsShouldReturnMakeAndModel() { - given(this.userRepository.findByUsername(anyString())) - .willReturn(new User("sboot", VIN)); + given(this.userRepository.findByUsername(anyString())).willReturn(new User("sboot", VIN)); VehicleDetails details = new VehicleDetails("Honda", "Civic"); given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(details); VehicleDetails actual = this.service.getVehicleDetails("sboot"); diff --git a/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java index e4642f7c51e..726046a6034 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java @@ -68,12 +68,12 @@ class SampleTomcatTwoConnectorsApplicationTests { void testHello() { assertThat(this.ports.getHttpsPort()).isEqualTo(this.port); assertThat(this.ports.getHttpPort()).isNotEqualTo(this.port); - ResponseEntity<String> entity = this.restTemplate.getForEntity( - "http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); + ResponseEntity<String> entity = this.restTemplate + .getForEntity("http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); - ResponseEntity<String> httpsEntity = this.restTemplate - .getForEntity("https://localhost:" + this.port + "/hello", String.class); + ResponseEntity<String> httpsEntity = this.restTemplate.getForEntity("https://localhost:" + this.port + "/hello", + String.class); assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(httpsEntity.getBody()).isEqualTo("hello"); } @@ -87,8 +87,7 @@ class SampleTomcatTwoConnectorsApplicationTests { @Override public void onApplicationEvent(WebServerInitializedEvent event) { - Service service = ((TomcatWebServer) event.getWebServer()).getTomcat() - .getService(); + Service service = ((TomcatWebServer) event.getWebServer()).getTomcat().getService(); for (Connector connector : service.findConnectors()) { if (connector.getSecure()) { this.httpsPort = connector.getLocalPort(); diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java index 6530082551b..c672685675a 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java @@ -57,12 +57,10 @@ class NonAutoConfigurationSampleTomcatApplicationTests { } @Configuration(proxyBeanMethods = false) - @Import({ ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @Import({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) - @ComponentScan( - basePackageClasses = { SampleController.class, HelloWorldService.class }) + @ComponentScan(basePackageClasses = { SampleController.class, HelloWorldService.class }) public static class NonAutoConfigurationSampleTomcatApplication { public static void main(String[] args) { diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java index 3a7f6a61e8d..e51663520d4 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java @@ -67,23 +67,18 @@ class SampleTomcatApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - try (GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody()))) { - assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)) - .isEqualTo("Hello World"); + try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()))) { + assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)).isEqualTo("Hello World"); } } @Test void testTimeout() { ServletWebServerApplicationContext context = (ServletWebServerApplicationContext) this.applicationContext; - TomcatWebServer embeddedServletContainer = (TomcatWebServer) context - .getWebServer(); - ProtocolHandler protocolHandler = embeddedServletContainer.getTomcat() - .getConnector().getProtocolHandler(); + TomcatWebServer embeddedServletContainer = (TomcatWebServer) context.getWebServer(); + ProtocolHandler protocolHandler = embeddedServletContainer.getTomcat().getConnector().getProtocolHandler(); int timeout = ((AbstractProtocol<?>) protocolHandler).getConnectionTimeout(); assertThat(timeout).isEqualTo(5000); } diff --git a/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java b/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java index c883d27c461..f297f30e026 100644 --- a/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java +++ b/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java @@ -51,8 +51,7 @@ public class WebConfig implements WebMvcConfigurer { } @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } diff --git a/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java b/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java index 62dac73ba10..a96db51f5d6 100644 --- a/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java @@ -48,8 +48,7 @@ class SampleTraditionalApplicationTests { @Test void testStaticPage() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/index.html", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/index.html", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); assertThat(body).contains("<html>").contains("<h1>Hello</h1>"); diff --git a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java index 022065d6184..973431aa750 100644 --- a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java @@ -62,20 +62,16 @@ class SampleUndertowApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - try (GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody()))) { - assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)) - .isEqualTo("Hello World"); + try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()))) { + assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)).isEqualTo("Hello World"); } } private void assertOkResponse(String path, String body) { - ResponseEntity<String> entity = this.restTemplate.getForEntity(path, - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity(path, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo(body); } diff --git a/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java index e537c0a994e..21e9c1e3d7d 100644 --- a/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java @@ -47,8 +47,7 @@ class SampleWebFreeMarkerApplicationTests { @Test void testFreeMarkerTemplate() { - ResponseEntity<String> entity = this.testRestTemplate.getForEntity("/", - String.class); + ResponseEntity<String> entity = this.testRestTemplate.getForEntity("/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello, Andy"); } @@ -59,12 +58,11 @@ class SampleWebFreeMarkerApplicationTests { headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> responseEntity = this.testRestTemplate - .exchange("/does-not-exist", HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> responseEntity = this.testRestTemplate.exchange("/does-not-exist", HttpMethod.GET, + requestEntity, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(responseEntity.getBody()) - .contains("Something went wrong: 404 Not Found"); + assertThat(responseEntity.getBody()).contains("Something went wrong: 404 Not Found"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java index b4d0f2d9d0e..c7a57071f91 100644 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java @@ -63,8 +63,7 @@ public class MessageController { } @PostMapping - public ModelAndView create(@Valid Message message, BindingResult result, - RedirectAttributes redirect) { + public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { ModelAndView mav = new ModelAndView("messages/form"); mav.addObject("formErrors", result.getAllErrors()); diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java index 69230dbaa81..c7c201ce816 100755 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java @@ -63,15 +63,13 @@ class MessageControllerWebTests { @Test void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) - .andExpect(status().isFound()) + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")) - .andExpect(status().isOk()) + this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) .andExpect(content().string(containsString("is required"))); } @@ -95,8 +93,7 @@ class MessageControllerWebTests { @Override public void describeTo(Description description) { - description.appendText("a string that matches regex: ") - .appendText(this.regex); + description.appendText("a string that matches regex: ").appendText(this.regex); } public static org.hamcrest.Matcher<java.lang.String> matches(String regex) { diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java index 61941d3352d..da7deaad953 100644 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java @@ -65,8 +65,7 @@ class SampleGroovyTemplateApplicationTests { @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java index da7532878e3..4d7e6dc8d03 100644 --- a/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java @@ -56,12 +56,10 @@ class SampleWebJspApplicationTests { void customErrorPage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, - URI.create("/foo")); + RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create("/foo")); ResponseEntity<String> entity = this.restTemplate.exchange(request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()) - .contains("Something went wrong: 500 Internal Server Error"); + assertThat(entity.getBody()).contains("Something went wrong: 500 Internal Server Error"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java b/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java index 5b65b9d4d78..504d9b1ab54 100644 --- a/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java @@ -62,8 +62,7 @@ public class SampleMethodSecurityApplication implements WebMvcConfigurer { return new InMemoryUserDetailsManager( User.withDefaultPasswordEncoder().username("admin").password("admin") .roles("ADMIN", "USER", "ACTUATOR").build(), - User.withDefaultPasswordEncoder().username("user").password("user") - .roles("USER").build()); + User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build()); } } diff --git a/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java index 4f4b56796d5..c45a3d97ce9 100644 --- a/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java @@ -57,8 +57,8 @@ class SampleMethodSecurityApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("<title>Login"); } @@ -71,11 +71,10 @@ class SampleMethodSecurityApplicationTests { form.set("username", "admin"); form.set("password", "admin"); getCsrf(form, headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .isEqualTo("http://localhost:" + this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).isEqualTo("http://localhost:" + this.port + "/"); } @Test @@ -86,13 +85,12 @@ class SampleMethodSecurityApplicationTests { form.set("username", "user"); form.set("password", "user"); getCsrf(form, headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); String cookie = entity.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); - ResponseEntity<String> page = this.restTemplate.exchange( - entity.getHeaders().getLocation(), HttpMethod.GET, + ResponseEntity<String> page = this.restTemplate.exchange(entity.getHeaders().getLocation(), HttpMethod.GET, new HttpEntity<Void>(headers), String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(page.getBody()).contains("Access denied"); @@ -102,35 +100,30 @@ class SampleMethodSecurityApplicationTests { void testManagementProtected() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> entity = this.restTemplate.exchange("/actuator/beans", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/actuator/beans", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testManagementAuthorizedAccess() { - BasicAuthenticationInterceptor basicAuthInterceptor = new BasicAuthenticationInterceptor( - "admin", "admin"); + BasicAuthenticationInterceptor basicAuthInterceptor = new BasicAuthenticationInterceptor("admin", "admin"); this.restTemplate.getRestTemplate().getInterceptors().add(basicAuthInterceptor); try { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/actuator/beans", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/beans", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } finally { - this.restTemplate.getRestTemplate().getInterceptors() - .remove(basicAuthInterceptor); + this.restTemplate.getRestTemplate().getInterceptors().remove(basicAuthInterceptor); } } private void getCsrf(MultiValueMap<String, String> form, HttpHeaders headers) { - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); String body = page.getBody(); - Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*") - .matcher(body); + Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*").matcher(body); matcher.find(); form.set("_csrf", matcher.group(1)); } diff --git a/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java index bce076db310..0d237be9422 100644 --- a/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java @@ -57,11 +57,10 @@ class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> responseEntity = this.restTemplate - .exchange("/does-not-exist", HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> responseEntity = this.restTemplate.exchange("/does-not-exist", HttpMethod.GET, + requestEntity, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(responseEntity.getBody()) - .contains("Something went wrong: 404 Not Found"); + assertThat(responseEntity.getBody()).contains("Something went wrong: 404 Not Found"); } @Test @@ -69,8 +68,8 @@ class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/serviceUnavailable", - HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/serviceUnavailable", HttpMethod.GET, requestEntity, + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); assertThat(entity.getBody()).contains("I'm a 503"); } @@ -80,8 +79,8 @@ class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/bang", - HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/bang", HttpMethod.GET, requestEntity, + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody()).contains("I'm a 5xx"); } @@ -91,8 +90,8 @@ class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/insufficientStorage", - HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/insufficientStorage", HttpMethod.GET, + requestEntity, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INSUFFICIENT_STORAGE); assertThat(entity.getBody()).contains("I'm a 507"); } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java index ec4c9fa26c1..938789ae865 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java @@ -61,9 +61,8 @@ public class SampleWebSecureCustomApplication implements WebMvcConfigurer { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest() - .fullyAuthenticated().and().formLogin().loginPage("/login") - .failureUrl("/login?error").permitAll().and().logout().permitAll(); + http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest().fullyAuthenticated().and() + .formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and().logout().permitAll(); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java index f85f250ec5c..ea45ad6db9d 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java @@ -56,19 +56,18 @@ class SampleWebSecureCustomApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/login"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login"); } @Test void testLoginPage() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("_csrf"); } @@ -81,18 +80,16 @@ class SampleWebSecureCustomApplicationTests { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "password"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); @@ -105,8 +102,7 @@ class SampleWebSecureCustomApplicationTests { @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java index bd941e649d8..882362f5fdb 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java @@ -65,9 +65,8 @@ public class SampleWebSecureJdbcApplication implements WebMvcConfigurer { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest() - .fullyAuthenticated().and().formLogin().loginPage("/login") - .failureUrl("/login?error").permitAll().and().logout().permitAll(); + http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest().fullyAuthenticated().and() + .formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and().logout().permitAll(); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java index 2dd16921146..136783c96bf 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java @@ -56,19 +56,18 @@ class SampleWebSecureJdbcApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/login"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login"); } @Test void testLoginPage() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("_csrf"); } @@ -81,18 +80,16 @@ class SampleWebSecureJdbcApplicationTests { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "user"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); @@ -105,8 +102,7 @@ class SampleWebSecureJdbcApplicationTests { @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java index 3b0de0f7918..9b1a9f03a58 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java @@ -56,19 +56,18 @@ class SampleSecureApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/login"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login"); } @Test void testLoginPage() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("_csrf"); } @@ -81,18 +80,16 @@ class SampleSecureApplicationTests { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "password"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); @@ -105,8 +102,7 @@ class SampleSecureApplicationTests { @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java index c78616c35a7..efcc4f31600 100644 --- a/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java @@ -48,12 +48,11 @@ class SampleWebStaticApplicationTests { @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate.getForEntity( - "/webjars/bootstrap/3.0.3/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/webjars/bootstrap/3.0.3/css/bootstrap.min.css", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); - assertThat(entity.getHeaders().getContentType()) - .isEqualTo(MediaType.valueOf("text/css")); + assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("text/css")); } } diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java b/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java index 96ba436f925..55df4f71a86 100755 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java @@ -58,8 +58,7 @@ public class MessageController { } @PostMapping - public ModelAndView create(@Valid Message message, BindingResult result, - RedirectAttributes redirect) { + public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); } diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java index 47f0de77d11..106ec671132 100644 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java @@ -63,15 +63,13 @@ class MessageControllerWebTests { @Test void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) - .andExpect(status().isFound()) + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")) - .andExpect(status().isOk()) + this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) .andExpect(content().string(containsString("is required"))); } @@ -95,8 +93,7 @@ class MessageControllerWebTests { @Override public void describeTo(Description description) { - description.appendText("a string that matches regex: ") - .appendText(this.regex); + description.appendText("a string that matches regex: ").appendText(this.regex); } public static org.hamcrest.Matcher<java.lang.String> matches(String regex) { diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java index 7c3640b847b..1df6c0529ba 100644 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java @@ -65,8 +65,8 @@ class SampleWebUiApplicationTests { @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate.getForEntity( - "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate + .getForEntity("http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-webflux/src/main/java/sample/webflux/ExampleController.java b/spring-boot-samples/spring-boot-sample-webflux/src/main/java/sample/webflux/ExampleController.java index a42266d67e2..1b5062d6f6c 100644 --- a/spring-boot-samples/spring-boot-sample-webflux/src/main/java/sample/webflux/ExampleController.java +++ b/spring-boot-samples/spring-boot-sample-webflux/src/main/java/sample/webflux/ExampleController.java @@ -23,10 +23,8 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class ExampleController { - @PostMapping(path = "/", - consumes = { MediaType.APPLICATION_JSON_VALUE, "!application/xml" }, - produces = MediaType.TEXT_PLAIN_VALUE, headers = "X-Custom=Foo", - params = "a!=alpha") + @PostMapping(path = "/", consumes = { MediaType.APPLICATION_JSON_VALUE, "!application/xml" }, + produces = MediaType.TEXT_PLAIN_VALUE, headers = "X-Custom=Foo", params = "a!=alpha") public String example() { return "Hello World"; } diff --git a/spring-boot-samples/spring-boot-sample-webflux/src/test/java/sample/webflux/SampleWebFluxApplicationTests.java b/spring-boot-samples/spring-boot-sample-webflux/src/test/java/sample/webflux/SampleWebFluxApplicationTests.java index 5fe0b365be8..2177fdc67ef 100644 --- a/spring-boot-samples/spring-boot-sample-webflux/src/test/java/sample/webflux/SampleWebFluxApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-webflux/src/test/java/sample/webflux/SampleWebFluxApplicationTests.java @@ -38,23 +38,21 @@ class SampleWebFluxApplicationTests { @Test void testWelcome() { - this.webClient.get().uri("/").accept(MediaType.TEXT_PLAIN).exchange() - .expectBody(String.class).isEqualTo("Hello World"); + this.webClient.get().uri("/").accept(MediaType.TEXT_PLAIN).exchange().expectBody(String.class) + .isEqualTo("Hello World"); } @Test void testEcho() { - this.webClient.post().uri("/echo").contentType(MediaType.TEXT_PLAIN) - .accept(MediaType.TEXT_PLAIN) - .body(Mono.just("Hello WebFlux!"), String.class).exchange() - .expectBody(String.class).isEqualTo("Hello WebFlux!"); + this.webClient.post().uri("/echo").contentType(MediaType.TEXT_PLAIN).accept(MediaType.TEXT_PLAIN) + .body(Mono.just("Hello WebFlux!"), String.class).exchange().expectBody(String.class) + .isEqualTo("Hello WebFlux!"); } @Test void testActuatorStatus() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .json("{\"status\":\"UP\"}"); + this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() + .expectBody().json("{\"status\":\"UP\"}"); } } diff --git a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java index 1ebe83f2079..e5be9211e4d 100644 --- a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,28 +48,21 @@ public class HolidayEndpoint { private HumanResourceService humanResourceService; public HolidayEndpoint(HumanResourceService humanResourceService) - throws JDOMException, XPathFactoryConfigurationException, - XPathExpressionException { + throws JDOMException, XPathFactoryConfigurationException, XPathExpressionException { this.humanResourceService = humanResourceService; Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI); XPathFactory xPathFactory = XPathFactory.instance(); - this.startDateExpression = xPathFactory.compile("//hr:StartDate", - Filters.element(), null, namespace); - this.endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), - null, namespace); - this.nameExpression = xPathFactory.compile( - "concat(//hr:FirstName,' ',//hr:LastName)", Filters.fstring(), null, + this.startDateExpression = xPathFactory.compile("//hr:StartDate", Filters.element(), null, namespace); + this.endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace); + this.nameExpression = xPathFactory.compile("concat(//hr:FirstName,' ',//hr:LastName)", Filters.fstring(), null, namespace); } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "HolidayRequest") - public void handleHolidayRequest(@RequestPayload Element holidayRequest) - throws Exception { + public void handleHolidayRequest(@RequestPayload Element holidayRequest) throws Exception { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date startDate = dateFormat - .parse(this.startDateExpression.evaluateFirst(holidayRequest).getText()); - Date endDate = dateFormat - .parse(this.endDateExpression.evaluateFirst(holidayRequest).getText()); + Date startDate = dateFormat.parse(this.startDateExpression.evaluateFirst(holidayRequest).getText()); + Date endDate = dateFormat.parse(this.endDateExpression.evaluateFirst(holidayRequest).getText()); String name = this.nameExpression.evaluateFirst(holidayRequest); this.humanResourceService.bookHoliday(startDate, endDate, name); } diff --git a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java index d036d6374ef..6ae3ff29549 100644 --- a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java +++ b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ public class StubHumanResourceService implements HumanResourceService { @Override public void bookHoliday(Date startDate, Date endDate, String name) { - this.logger.info("Booking holiday for [" + startDate + " - " + endDate + "] for [" - + name + "]"); + this.logger.info("Booking holiday for [" + startDate + " - " + endDate + "] for [" + name + "]"); } } diff --git a/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java b/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java index b7654fc0225..616382b8f63 100644 --- a/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java @@ -45,19 +45,16 @@ class SampleWsApplicationTests { @BeforeEach public void setUp() { - this.webServiceTemplate - .setDefaultUri("http://localhost:" + this.serverPort + "/services/"); + this.webServiceTemplate.setDefaultUri("http://localhost:" + this.serverPort + "/services/"); } @Test void testSendingHolidayRequest(CapturedOutput capturedOutput) { final String request = "<hr:HolidayRequest xmlns:hr=\"https://company.example.com/hr/schemas\">" + " <hr:Holiday>" + " <hr:StartDate>2013-10-20</hr:StartDate>" - + " <hr:EndDate>2013-11-22</hr:EndDate>" + " </hr:Holiday>" - + " <hr:Employee>" + " <hr:Number>1</hr:Number>" - + " <hr:FirstName>John</hr:FirstName>" - + " <hr:LastName>Doe</hr:LastName>" + " </hr:Employee>" - + "</hr:HolidayRequest>"; + + " <hr:EndDate>2013-11-22</hr:EndDate>" + " </hr:Holiday>" + " <hr:Employee>" + + " <hr:Number>1</hr:Number>" + " <hr:FirstName>John</hr:FirstName>" + + " <hr:LastName>Doe</hr:LastName>" + " </hr:Employee>" + "</hr:HolidayRequest>"; StreamSource source = new StreamSource(new StringReader(request)); StreamResult result = new StreamResult(System.out); this.webServiceTemplate.sendSourceAndReceiveToResult(source, result); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java index 8b398825331..c2e18cd7e5a 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java @@ -40,8 +40,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration @EnableWebSocket -public class SampleJettyWebSocketsApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleJettyWebSocketsApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java index d8414a77bea..5f8be527b39 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java index fdba63d8f11..22c2e0ce8ff 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java index 7e04228d7f8..857b3a5b14d 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java index f3f18b119d1..2d2bba68c24 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java index 212cb46f28a..8bf1a1fc052 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java index 70b6203ac3b..054a252d8ac 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java index 4430afe6d90..4023957bd4a 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java index f80ddc34fe8..5aad8587f59 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java @@ -42,8 +42,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest(classes = SampleJettyWebSocketsApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleJettyWebSocketsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) class SampleWebSocketsApplicationTests { private static Log logger = LogFactory.getLog(SampleWebSocketsApplicationTests.class); @@ -53,30 +52,25 @@ class SampleWebSocketsApplicationTests { @Test void echoEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test void reverseEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -106,8 +100,7 @@ class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -120,8 +113,7 @@ class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java index 4543999489d..a6e414c6dff 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java @@ -46,44 +46,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest( - classes = { SampleJettyWebSocketsApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleJettyWebSocketsApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT) class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); @LocalServerPort private int port; @Test void echoEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test void reverseEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -123,8 +115,7 @@ class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -137,8 +128,7 @@ class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java index e74ad6427fa..25efa6bb100 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java @@ -40,8 +40,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration @EnableWebSocket -public class SampleTomcatWebSocketApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleTomcatWebSocketApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java index b64d4e8bfa6..685c70924a1 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java index 8ce8fbef9a1..7b7312d3a86 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java index 7db696b4807..0d3e2245cce 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java index d9caf6b1d12..b576047e1e6 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java index 173dfa98d95..69595d08622 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java index 8fbb5910203..ff0e3764ef2 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java index a9e880c866f..c35a633eb62 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java index f5ed0846842..47023e4547b 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java @@ -42,8 +42,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest(classes = SampleTomcatWebSocketApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleTomcatWebSocketApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) class SampleWebSocketsApplicationTests { private static Log logger = LogFactory.getLog(SampleWebSocketsApplicationTests.class); @@ -53,30 +52,25 @@ class SampleWebSocketsApplicationTests { @Test void echoEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test void reverseEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -106,8 +100,7 @@ class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -120,8 +113,7 @@ class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java index b9363218d82..7ca76c7148d 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java @@ -46,44 +46,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest( - classes = { SampleTomcatWebSocketApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleTomcatWebSocketApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT) class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); @LocalServerPort private int port; @Test void echoEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test void reverseEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -123,8 +115,7 @@ class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -137,8 +128,7 @@ class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java index 0d5a22daeee..ebd0d7d5e7c 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java @@ -40,15 +40,12 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration @EnableWebSocket -public class SampleUndertowWebSocketsApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleUndertowWebSocketsApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*") - .withSockJS(); - registry.addHandler(snakeWebSocketHandler(), "/snake").setAllowedOrigins("*") - .withSockJS(); + registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*").withSockJS(); + registry.addHandler(snakeWebSocketHandler(), "/snake").setAllowedOrigins("*").withSockJS(); } @Override diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java index d43bb546a38..4ada967e841 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java index f6e02d348e5..ca51c578240 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java index b8e1b61d26a..a5a9de3f076 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java index 5f77854f46c..8b7ea21b3e2 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java index 3ec277f0b0e..9cab39ad37c 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java index 85a319b2762..a41587c76c8 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java index 27fe1607daa..aefc5f2eabf 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java index aa64d95e891..2d48780b35e 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java @@ -42,8 +42,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest(classes = SampleUndertowWebSocketsApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleUndertowWebSocketsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) class SampleWebSocketsApplicationTests { private static Log logger = LogFactory.getLog(SampleWebSocketsApplicationTests.class); @@ -53,30 +52,25 @@ class SampleWebSocketsApplicationTests { @Test void echoEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test void reverseEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -106,8 +100,7 @@ class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -120,8 +113,7 @@ class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java index 3a7100719e8..8485c0c9654 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java @@ -46,44 +46,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; -@SpringBootTest( - classes = { SampleUndertowWebSocketsApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleUndertowWebSocketsApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT) class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); @LocalServerPort private int port; @Test void echoEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test void reverseEndpoint() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -123,8 +115,7 @@ class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -137,8 +128,7 @@ class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java index eac442090dd..bafe78c3da4 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,21 +40,17 @@ public class ConfigurationProcessorIntegrationTests { @BeforeClass public static void readMetadata() throws IOException { - Resource resource = new ClassPathResource( - "META-INF/spring-configuration-metadata.json"); + Resource resource = new ClassPathResource("META-INF/spring-configuration-metadata.json"); assertThat(resource.exists()).isTrue(); // Make sure the right file is detected - assertThat(resource.getURL().toString()) - .contains("spring-boot-configuration-processor-tests"); - repository = ConfigurationMetadataRepositoryJsonBuilder - .create(resource.getInputStream()).build(); + assertThat(resource.getURL().toString()).contains("spring-boot-configuration-processor-tests"); + repository = ConfigurationMetadataRepositoryJsonBuilder.create(resource.getInputStream()).build(); } @Test public void extractTypeFromAnnotatedGetter() { - ConfigurationMetadataProperty property = repository.getAllProperties() - .get("annotated.name"); + ConfigurationMetadataProperty property = repository.getAllProperties().get("annotated.name"); assertThat(property).isNotNull(); assertThat(property.getType()).isEqualTo("java.lang.String"); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java index 73c5597e6fe..c56ac971ea8 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import org.springframework.boot.web.context.WebServerPortFileWriter; public class DevToolsTestApplication { public static void main(String[] args) { - new SpringApplicationBuilder(DevToolsTestApplication.class) - .listeners(new WebServerPortFileWriter(args[0])).run(args); + new SpringApplicationBuilder(DevToolsTestApplication.class).listeners(new WebServerPortFileWriter(args[0])) + .run(args); } } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java index 2ad7b9304e4..3aa01ad6aef 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,14 +40,13 @@ abstract class AbstractApplicationLauncher implements ApplicationLauncher { protected final void copyApplicationTo(File location) throws IOException { FileSystemUtils.deleteRecursively(location); location.mkdirs(); - FileSystemUtils.copyRecursively( - new File(this.directories.getTestClassesDirectory(), "com"), + FileSystemUtils.copyRecursively(new File(this.directories.getTestClassesDirectory(), "com"), new File(location, "com")); } protected final List<String> getDependencyJarPaths() { - return Stream.of(this.directories.getDependenciesDirectory().listFiles()) - .map(File::getAbsolutePath).collect(Collectors.toList()); + return Stream.of(this.directories.getDependenciesDirectory().listFiles()).map(File::getAbsolutePath) + .collect(Collectors.toList()); } protected final Directories getDirectories() { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ApplicationLauncher.java index 9a112d709e6..7e8e541cfe8 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ApplicationLauncher.java @@ -26,10 +26,9 @@ import java.io.File; */ public interface ApplicationLauncher { - LaunchedApplication launchApplication(JvmLauncher javaLauncher, File serverPortFile) + LaunchedApplication launchApplication(JvmLauncher javaLauncher, File serverPortFile) throws Exception; + + LaunchedApplication launchApplication(JvmLauncher jvmLauncher, File serverPortFile, String... additionalArgs) throws Exception; - LaunchedApplication launchApplication(JvmLauncher jvmLauncher, File serverPortFile, - String... additionalArgs) throws Exception; - } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java index a0db9c70179..322ea877898 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,7 @@ public class DevToolsIntegrationTests { @ClassRule public static final TemporaryFolder temp = new TemporaryFolder(); - private static final BuildOutput buildOutput = new BuildOutput( - DevToolsIntegrationTests.class); + private static final BuildOutput buildOutput = new BuildOutput(DevToolsIntegrationTests.class); private LaunchedApplication launchedApplication; @@ -72,15 +71,13 @@ public class DevToolsIntegrationTests { public DevToolsIntegrationTests(ApplicationLauncher applicationLauncher) { this.applicationLauncher = applicationLauncher; - this.serverPortFile = new File( - DevToolsIntegrationTests.buildOutput.getRootLocation(), "server.port"); + this.serverPortFile = new File(DevToolsIntegrationTests.buildOutput.getRootLocation(), "server.port"); } @Before public void launchApplication() throws Exception { this.serverPortFile.delete(); - this.launchedApplication = this.applicationLauncher - .launchApplication(this.javaLauncher, this.serverPortFile); + this.launchedApplication = this.applicationLauncher.launchApplication(this.javaLauncher, this.serverPortFile); } @After @@ -92,25 +89,20 @@ public class DevToolsIntegrationTests { public void addARequestMappingToAnExistingController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); - controller("com.example.ControllerOne").withRequestMapping("one") - .withRequestMapping("two").build(); + controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); } @Test public void removeARequestMappingFromAnExistingController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); controller("com.example.ControllerOne").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForEntity(urlBase + "/one", String.class).getStatusCode()) @@ -121,16 +113,13 @@ public class DevToolsIntegrationTests { public void createAController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); } @@ -138,57 +127,43 @@ public class DevToolsIntegrationTests { public void createAControllerAndThenAddARequestMapping() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); - controller("com.example.ControllerTwo").withRequestMapping("two") - .withRequestMapping("three").build(); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); + controller("com.example.ControllerTwo").withRequestMapping("two").withRequestMapping("three").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/three", String.class)) - .isEqualTo("three"); + assertThat(template.getForObject(urlBase + "/three", String.class)).isEqualTo("three"); } @Test - public void createAControllerAndThenAddARequestMappingToAnExistingController() - throws Exception { + public void createAControllerAndThenAddARequestMappingToAnExistingController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); - controller("com.example.ControllerOne").withRequestMapping("one") - .withRequestMapping("three").build(); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); + controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("three").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); - assertThat(template.getForObject(urlBase + "/three", String.class)) - .isEqualTo("three"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); + assertThat(template.getForObject(urlBase + "/three", String.class)).isEqualTo("three"); } @Test public void deleteAController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(new File(this.launchedApplication.getClassesDirectory(), - "com/example/ControllerOne.class").delete()).isTrue(); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerOne.class").delete()) + .isTrue(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForEntity(urlBase + "/one", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); @@ -199,18 +174,15 @@ public class DevToolsIntegrationTests { public void createAControllerAndThenDeleteIt() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); - assertThat(new File(this.launchedApplication.getClassesDirectory(), - "com/example/ControllerTwo.class").delete()).isTrue(); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); + assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerTwo.class").delete()) + .isTrue(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); @@ -223,13 +195,10 @@ public class DevToolsIntegrationTests { while (this.serverPortFile.length() == 0) { if (System.currentTimeMillis() > end) { throw new IllegalStateException(String.format( - "server.port file '" + this.serverPortFile - + "' was not written within " + timeToWait.toMillis() + "server.port file '" + this.serverPortFile + "' was not written within " + timeToWait.toMillis() + "ms. " + "Application output:%n%s%s", - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardOut())), - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardError())))); + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardOut())), + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardError())))); } Thread.sleep(100); } @@ -243,8 +212,7 @@ public class DevToolsIntegrationTests { } private ControllerBuilder controller(String name) { - return new ControllerBuilder(name, - this.launchedApplication.getClassesDirectory()); + return new ControllerBuilder(name, this.launchedApplication.getClassesDirectory()); } @Parameters(name = "{0}") @@ -274,14 +242,12 @@ public class DevToolsIntegrationTests { } public void build() throws Exception { - Builder<Object> builder = new ByteBuddy().subclass(Object.class) - .name(this.name).annotateType(AnnotationDescription.Builder - .ofType(RestController.class).build()); + Builder<Object> builder = new ByteBuddy().subclass(Object.class).name(this.name) + .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); for (String mapping : this.mappings) { builder = builder.defineMethod(mapping, String.class, Visibility.PUBLIC) - .intercept(FixedValue.value(mapping)).annotateMethod( - AnnotationDescription.Builder.ofType(RequestMapping.class) - .defineArray("value", mapping).build()); + .intercept(FixedValue.value(mapping)).annotateMethod(AnnotationDescription.Builder + .ofType(RequestMapping.class).defineArray("value", mapping).build()); } builder.make().saveIn(this.classesDirectory); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java index 76762c95000..7238dfea9e5 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java @@ -57,8 +57,7 @@ public class DevToolsWithLazyInitializationIntegrationTests { @ClassRule public static final TemporaryFolder temp = new TemporaryFolder(); - private static final BuildOutput buildOutput = new BuildOutput( - DevToolsIntegrationTests.class); + private static final BuildOutput buildOutput = new BuildOutput(DevToolsIntegrationTests.class); private LaunchedApplication launchedApplication; @@ -69,8 +68,7 @@ public class DevToolsWithLazyInitializationIntegrationTests { @Rule public JvmLauncher javaLauncher = new JvmLauncher(); - public DevToolsWithLazyInitializationIntegrationTests( - ApplicationLauncher applicationLauncher) { + public DevToolsWithLazyInitializationIntegrationTests(ApplicationLauncher applicationLauncher) { this.applicationLauncher = applicationLauncher; this.serverPortFile = new File(buildOutput.getRootLocation(), "server.port"); } @@ -78,8 +76,7 @@ public class DevToolsWithLazyInitializationIntegrationTests { @Before public void launchApplication() throws Exception { this.serverPortFile.delete(); - this.launchedApplication = this.applicationLauncher.launchApplication( - this.javaLauncher, this.serverPortFile, + this.launchedApplication = this.applicationLauncher.launchApplication(this.javaLauncher, this.serverPortFile, "--spring.main.lazy-initialization=true"); } @@ -92,17 +89,13 @@ public class DevToolsWithLazyInitializationIntegrationTests { public void addARequestMappingToAnExistingControllerWhenLazyInit() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); - controller("com.example.ControllerOne").withRequestMapping("one") - .withRequestMapping("two").build(); + controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject(urlBase + "/two", String.class)) - .isEqualTo("two"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); } private int awaitServerPort() throws Exception { @@ -112,13 +105,10 @@ public class DevToolsWithLazyInitializationIntegrationTests { while (this.serverPortFile.length() == 0) { if (System.currentTimeMillis() > end) { throw new IllegalStateException(String.format( - "server.port file '" + this.serverPortFile - + "' was not written within " + timeToWait.toMillis() + "server.port file '" + this.serverPortFile + "' was not written within " + timeToWait.toMillis() + "ms. " + "Application output:%n%s%s", - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardOut())), - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardError())))); + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardOut())), + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardError())))); } Thread.sleep(100); } @@ -132,8 +122,7 @@ public class DevToolsWithLazyInitializationIntegrationTests { } private ControllerBuilder controller(String name) { - return new ControllerBuilder(name, - this.launchedApplication.getClassesDirectory()); + return new ControllerBuilder(name, this.launchedApplication.getClassesDirectory()); } @Parameterized.Parameters(name = "{0}") @@ -164,14 +153,12 @@ public class DevToolsWithLazyInitializationIntegrationTests { } public void build() throws Exception { - DynamicType.Builder<Object> builder = new ByteBuddy().subclass(Object.class) - .name(this.name).annotateType(AnnotationDescription.Builder - .ofType(RestController.class).build()); + DynamicType.Builder<Object> builder = new ByteBuddy().subclass(Object.class).name(this.name) + .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); for (String mapping : this.mappings) { builder = builder.defineMethod(mapping, String.class, Visibility.PUBLIC) - .intercept(FixedValue.value(mapping)).annotateMethod( - AnnotationDescription.Builder.ofType(RequestMapping.class) - .defineArray("value", mapping).build()); + .intercept(FixedValue.value(mapping)).annotateMethod(AnnotationDescription.Builder + .ofType(RequestMapping.class).defineArray("value", mapping).build()); } builder.make().saveIn(this.classesDirectory); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java index 2c8b37b37d7..a95aea729d8 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,27 +49,24 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); File appJar = new File(appDirectory, "app.jar"); - JarOutputStream output = new JarOutputStream(new FileOutputStream(appJar), - manifest); + JarOutputStream output = new JarOutputStream(new FileOutputStream(appJar), manifest); addToJar(output, appDirectory, appDirectory); output.close(); List<String> entries = new ArrayList<>(); entries.add(appJar.getAbsolutePath()); entries.addAll(getDependencyJarPaths()); - String classpath = StringUtils.collectionToDelimitedString(entries, - File.pathSeparator); + String classpath = StringUtils.collectionToDelimitedString(entries, File.pathSeparator); return classpath; } - private void addToJar(JarOutputStream output, File root, File current) - throws IOException { + private void addToJar(JarOutputStream output, File root, File current) throws IOException { for (File file : current.listFiles()) { if (file.isDirectory()) { addToJar(output, root, file); } output.putNextEntry(new ZipEntry( - file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1) - .replace("\\", "/") + (file.isDirectory() ? "/" : ""))); + file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1).replace("\\", "/") + + (file.isDirectory() ? "/" : ""))); if (file.isFile()) { try (FileInputStream input = new FileInputStream(file)) { StreamUtils.copy(input, output); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java index 7a778f64c88..332b0f7efab 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,20 +47,19 @@ class JvmLauncher implements TestRule { @Override public Statement apply(Statement base, Description description) { this.outputDirectory = new File(this.buildOutput.getRootLocation(), - "output/" + NON_ALPHABET_PATTERN.matcher(description.getMethodName()) - .replaceAll("")); + "output/" + NON_ALPHABET_PATTERN.matcher(description.getMethodName()).replaceAll("")); this.outputDirectory.mkdirs(); return base; } LaunchedJvm launch(String name, String classpath, String... args) throws IOException { - List<String> command = new ArrayList<>(Arrays - .asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath)); + List<String> command = new ArrayList<>( + Arrays.asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath)); command.addAll(Arrays.asList(args)); File standardOut = new File(this.outputDirectory, name + ".out"); File standardError = new File(this.outputDirectory, name + ".err"); - Process process = new ProcessBuilder(StringUtils.toStringArray(command)) - .redirectError(standardError).redirectOutput(standardOut).start(); + Process process = new ProcessBuilder(StringUtils.toStringArray(command)).redirectError(standardError) + .redirectOutput(standardOut).start(); return new LaunchedJvm(process, standardOut, standardError); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LaunchedApplication.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LaunchedApplication.java index 680d76a13f1..a612a91dcae 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LaunchedApplication.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LaunchedApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,9 +38,8 @@ class LaunchedApplication { private final BiFunction<Integer, File, Process> remoteProcessRestarter; - LaunchedApplication(File classesDirectory, File standardOut, File standardError, - Process localProcess, Process remoteProcess, - BiFunction<Integer, File, Process> remoteProcessRestarter) { + LaunchedApplication(File classesDirectory, File standardOut, File standardError, Process localProcess, + Process remoteProcess, BiFunction<Integer, File, Process> remoteProcessRestarter) { this.classesDirectory = classesDirectory; this.standardOut = standardOut; this.standardError = standardError; @@ -52,8 +51,7 @@ class LaunchedApplication { public void restartRemote(int port) throws InterruptedException { if (this.remoteProcessRestarter != null) { stop(this.remoteProcess); - this.remoteProcess = this.remoteProcessRestarter.apply(port, - this.classesDirectory); + this.remoteProcess = this.remoteProcessRestarter.apply(port, this.classesDirectory); } } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java index ce2d55cecdf..b959c66c516 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java @@ -36,28 +36,22 @@ public class LocalApplicationLauncher extends AbstractApplicationLauncher { } @Override - public LaunchedApplication launchApplication(JvmLauncher jvmLauncher, - File serverPortFile) throws Exception { + public LaunchedApplication launchApplication(JvmLauncher jvmLauncher, File serverPortFile) throws Exception { LaunchedJvm jvm = jvmLauncher.launch("local", createApplicationClassPath(), - "com.example.DevToolsTestApplication", serverPortFile.getAbsolutePath(), - "--server.port=0"); - return new LaunchedApplication(getDirectories().getAppDirectory(), - jvm.getStandardOut(), jvm.getStandardError(), jvm.getProcess(), null, - null); + "com.example.DevToolsTestApplication", serverPortFile.getAbsolutePath(), "--server.port=0"); + return new LaunchedApplication(getDirectories().getAppDirectory(), jvm.getStandardOut(), jvm.getStandardError(), + jvm.getProcess(), null, null); } @Override - public LaunchedApplication launchApplication(JvmLauncher jvmLauncher, - File serverPortFile, String... additionalArgs) throws Exception { - List<String> args = new ArrayList<>( - Arrays.asList("com.example.DevToolsTestApplication", - serverPortFile.getAbsolutePath(), "--server.port=0")); + public LaunchedApplication launchApplication(JvmLauncher jvmLauncher, File serverPortFile, String... additionalArgs) + throws Exception { + List<String> args = new ArrayList<>(Arrays.asList("com.example.DevToolsTestApplication", + serverPortFile.getAbsolutePath(), "--server.port=0")); args.addAll(Arrays.asList(additionalArgs)); - LaunchedJvm jvm = jvmLauncher.launch("local", createApplicationClassPath(), - args.toArray(new String[] {})); - return new LaunchedApplication(getDirectories().getAppDirectory(), - jvm.getStandardOut(), jvm.getStandardError(), jvm.getProcess(), null, - null); + LaunchedJvm jvm = jvmLauncher.launch("local", createApplicationClassPath(), args.toArray(new String[] {})); + return new LaunchedApplication(getDirectories().getAppDirectory(), jvm.getStandardOut(), jvm.getStandardError(), + jvm.getProcess(), null, null); } protected String createApplicationClassPath() throws Exception { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java index b8d9737a842..124f347f69e 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java @@ -41,48 +41,38 @@ abstract class RemoteApplicationLauncher extends AbstractApplicationLauncher { } @Override - public LaunchedApplication launchApplication(JvmLauncher javaLauncher, - File serverPortFile) throws Exception { - LaunchedJvm applicationJvm = javaLauncher.launch("app", - createApplicationClassPath(), "com.example.DevToolsTestApplication", - serverPortFile.getAbsolutePath(), "--server.port=0", + public LaunchedApplication launchApplication(JvmLauncher javaLauncher, File serverPortFile) throws Exception { + LaunchedJvm applicationJvm = javaLauncher.launch("app", createApplicationClassPath(), + "com.example.DevToolsTestApplication", serverPortFile.getAbsolutePath(), "--server.port=0", "--spring.devtools.remote.secret=secret"); int port = awaitServerPort(applicationJvm.getStandardOut(), serverPortFile); - BiFunction<Integer, File, Process> remoteRestarter = getRemoteRestarter( - javaLauncher); - return new LaunchedApplication(getDirectories().getRemoteAppDirectory(), - applicationJvm.getStandardOut(), applicationJvm.getStandardError(), - applicationJvm.getProcess(), remoteRestarter.apply(port, null), + BiFunction<Integer, File, Process> remoteRestarter = getRemoteRestarter(javaLauncher); + return new LaunchedApplication(getDirectories().getRemoteAppDirectory(), applicationJvm.getStandardOut(), + applicationJvm.getStandardError(), applicationJvm.getProcess(), remoteRestarter.apply(port, null), remoteRestarter); } @Override - public LaunchedApplication launchApplication(JvmLauncher javaLauncher, - File serverPortFile, String... additionalArgs) throws Exception { - List<String> args = new ArrayList<>(Arrays.asList( - "com.example.DevToolsTestApplication", serverPortFile.getAbsolutePath(), - "--server.port=0", "--spring.devtools.remote.secret=secret")); + public LaunchedApplication launchApplication(JvmLauncher javaLauncher, File serverPortFile, + String... additionalArgs) throws Exception { + List<String> args = new ArrayList<>(Arrays.asList("com.example.DevToolsTestApplication", + serverPortFile.getAbsolutePath(), "--server.port=0", "--spring.devtools.remote.secret=secret")); args.addAll(Arrays.asList(additionalArgs)); - LaunchedJvm applicationJvm = javaLauncher.launch("app", - createApplicationClassPath(), args.toArray(new String[] {})); + LaunchedJvm applicationJvm = javaLauncher.launch("app", createApplicationClassPath(), + args.toArray(new String[] {})); int port = awaitServerPort(applicationJvm.getStandardOut(), serverPortFile); - BiFunction<Integer, File, Process> remoteRestarter = getRemoteRestarter( - javaLauncher); - return new LaunchedApplication(getDirectories().getRemoteAppDirectory(), - applicationJvm.getStandardOut(), applicationJvm.getStandardError(), - applicationJvm.getProcess(), remoteRestarter.apply(port, null), + BiFunction<Integer, File, Process> remoteRestarter = getRemoteRestarter(javaLauncher); + return new LaunchedApplication(getDirectories().getRemoteAppDirectory(), applicationJvm.getStandardOut(), + applicationJvm.getStandardError(), applicationJvm.getProcess(), remoteRestarter.apply(port, null), remoteRestarter); } - private BiFunction<Integer, File, Process> getRemoteRestarter( - JvmLauncher javaLauncher) { + private BiFunction<Integer, File, Process> getRemoteRestarter(JvmLauncher javaLauncher) { return (port, classesDirectory) -> { try { - LaunchedJvm remoteSpringApplicationJvm = javaLauncher.launch( - "remote-spring-application", + LaunchedJvm remoteSpringApplicationJvm = javaLauncher.launch("remote-spring-application", createRemoteSpringApplicationClassPath(classesDirectory), - RemoteSpringApplication.class.getName(), - "--spring.devtools.remote.secret=secret", + RemoteSpringApplication.class.getName(), "--spring.devtools.remote.secret=secret", "http://localhost:" + port); awaitRemoteSpringApplication(remoteSpringApplicationJvm.getStandardOut()); return remoteSpringApplicationJvm.getProcess(); @@ -95,8 +85,7 @@ abstract class RemoteApplicationLauncher extends AbstractApplicationLauncher { protected abstract String createApplicationClassPath() throws Exception; - private String createRemoteSpringApplicationClassPath(File classesDirectory) - throws Exception { + private String createRemoteSpringApplicationClassPath(File classesDirectory) throws Exception { File remoteAppDirectory = getDirectories().getRemoteAppDirectory(); if (classesDirectory == null) { copyApplicationTo(remoteAppDirectory); @@ -112,8 +101,7 @@ abstract class RemoteApplicationLauncher extends AbstractApplicationLauncher { while (serverPortFile.length() == 0) { if (System.currentTimeMillis() > end) { throw new IllegalStateException(String.format( - "server.port file was not written within 30 seconds. " - + "Application output:%n%s", + "server.port file was not written within 30 seconds. " + "Application output:%n%s", FileCopyUtils.copyToString(new FileReader(standardOut)))); } Thread.sleep(100); @@ -127,16 +115,13 @@ abstract class RemoteApplicationLauncher extends AbstractApplicationLauncher { long end = System.currentTimeMillis() + 30000; while (!standardOut.exists()) { if (System.currentTimeMillis() > end) { - throw new IllegalStateException( - "Standard out file was not written " + "within 30 seconds"); + throw new IllegalStateException("Standard out file was not written " + "within 30 seconds"); } Thread.sleep(100); } - while (!FileCopyUtils.copyToString(new FileReader(standardOut)) - .contains("Started RemoteSpringApplication")) { + while (!FileCopyUtils.copyToString(new FileReader(standardOut)).contains("Started RemoteSpringApplication")) { if (System.currentTimeMillis() > end) { - throw new IllegalStateException( - "RemoteSpringApplication did not start within 30 seconds"); + throw new IllegalStateException("RemoteSpringApplication did not start within 30 seconds"); } Thread.sleep(100); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java index 2595e0dd8d8..43200e19556 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,70 +103,60 @@ public class SysVinitLaunchScriptIT { public void statusWhenStarted() throws Exception { String output = doTest("status-when-started.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test public void statusWhenKilled() throws Exception { String output = doTest("status-when-killed.sh"); assertThat(output).contains("Status: 1"); - assertThat(output).has(coloredString(AnsiColor.RED, - "Not running (process " + extractPid(output) + " not found)")); + assertThat(output) + .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); } @Test public void stopWhenStopped() throws Exception { String output = doTest("stop-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output) - .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); } @Test public void forceStopWhenStopped() throws Exception { String output = doTest("force-stop-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output) - .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); } @Test public void startWhenStarted() throws Exception { String output = doTest("start-when-started.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, - "Already running [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Already running [" + extractPid(output) + "]")); } @Test public void restartWhenStopped() throws Exception { String output = doTest("restart-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output) - .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test public void restartWhenStarted() throws Exception { String output = doTest("restart-when-started.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.GREEN, - "Started [" + extract("PID1", output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, - "Stopped [" + extract("PID1", output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, - "Started [" + extract("PID2", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID1", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extract("PID1", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID2", output) + "]")); } @Test public void startWhenStopped() throws Exception { String output = doTest("start-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test @@ -178,15 +168,15 @@ public class SysVinitLaunchScriptIT { @Test public void launchWithMissingLogFolderGeneratesAWarning() throws Exception { String output = doTest("launch-with-missing-log-folder.sh"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, - "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + assertThat(output).has( + coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); } @Test public void launchWithMissingPidFolderGeneratesAWarning() throws Exception { String output = doTest("launch-with-missing-pid-folder.sh"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, - "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + assertThat(output).has( + coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); } @Test @@ -234,12 +224,9 @@ public class SysVinitLaunchScriptIT { @Test public void launchWithRelativePidFolder() throws Exception { String output = doTest("launch-with-relative-pid-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Running [" + extractPid(output) + "]")); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Stopped [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Running [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extractPid(output) + "]")); } @Test @@ -290,10 +277,8 @@ public class SysVinitLaunchScriptIT { copyFilesToContainer(docker, container, script); docker.startContainerCmd(container).exec(); StringBuilder output = new StringBuilder(); - AttachContainerResultCallback resultCallback = docker - .attachContainerCmd(container).withStdOut(true).withStdErr(true) - .withFollowStream(true).withLogs(true) - .exec(new AttachContainerResultCallback() { + AttachContainerResultCallback resultCallback = docker.attachContainerCmd(container).withStdOut(true) + .withStdErr(true).withFollowStream(true).withLogs(true).exec(new AttachContainerResultCallback() { @Override public void onNext(Frame item) { @@ -319,17 +304,14 @@ public class SysVinitLaunchScriptIT { } private DockerClient createClient() { - DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() - .withApiVersion("1.19").build(); - return DockerClientBuilder.getInstance(config) - .withDockerCmdExecFactory(this.commandExecFactory).build(); + DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withApiVersion("1.19") + .build(); + return DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(this.commandExecFactory).build(); } private String buildImage(DockerClient docker) { - String dockerfile = "src/test/resources/conf/" + this.os + "/" + this.version - + "/Dockerfile"; - String tag = "spring-boot-it/" + this.os.toLowerCase(Locale.ENGLISH) + ":" - + this.version; + String dockerfile = "src/test/resources/conf/" + this.os + "/" + this.version + "/Dockerfile"; + String tag = "spring-boot-it/" + this.os.toLowerCase(Locale.ENGLISH) + ":" + this.version; BuildImageResultCallback resultCallback = new BuildImageResultCallback() { private List<BuildResponseItem> items = new ArrayList<>(); @@ -346,8 +328,7 @@ public class SysVinitLaunchScriptIT { awaitCompletion(); } catch (InterruptedException ex) { - throw new DockerClientException( - "Interrupted while waiting for image id", ex); + throw new DockerClientException("Interrupted while waiting for image id", ex); } return getImageId(); } @@ -359,8 +340,8 @@ public class SysVinitLaunchScriptIT { } String imageId = extractImageId(); if (imageId == null) { - throw new DockerClientException("Could not build image: " - + this.items.get(this.items.size() - 1).getError()); + throw new DockerClientException( + "Could not build image: " + this.items.get(this.items.size() - 1).getError()); } return imageId; } @@ -379,38 +360,30 @@ public class SysVinitLaunchScriptIT { } }; - docker.buildImageCmd(new File(dockerfile)) - .withTags(new HashSet<>(Arrays.asList(tag))).exec(resultCallback); + docker.buildImageCmd(new File(dockerfile)).withTags(new HashSet<>(Arrays.asList(tag))).exec(resultCallback); String imageId = resultCallback.awaitImageId(); return imageId; } - private String createContainer(DockerClient docker, String imageId, - String testScript) { - return docker.createContainerCmd(imageId).withTty(false).withCmd("/bin/bash", - "-c", "chmod +x " + testScript + " && ./" + testScript).exec().getId(); + private String createContainer(DockerClient docker, String imageId, String testScript) { + return docker.createContainerCmd(imageId).withTty(false) + .withCmd("/bin/bash", "-c", "chmod +x " + testScript + " && ./" + testScript).exec().getId(); } - private void copyFilesToContainer(DockerClient docker, final String container, - String script) { + private void copyFilesToContainer(DockerClient docker, final String container, String script) { copyToContainer(docker, container, findApplication()); - copyToContainer(docker, container, - new File("src/test/resources/scripts/test-functions.sh")); - copyToContainer(docker, container, - new File("src/test/resources/scripts/" + script)); + copyToContainer(docker, container, new File("src/test/resources/scripts/test-functions.sh")); + copyToContainer(docker, container, new File("src/test/resources/scripts/" + script)); } - private void copyToContainer(DockerClient docker, final String container, - final File file) { - this.commandExecFactory.createCopyToContainerCmdExec() - .exec(new CopyToContainerCmd(container, file)); + private void copyToContainer(DockerClient docker, final String container, final File file) { + this.commandExecFactory.createCopyToContainerCmdExec().exec(new CopyToContainerCmd(container, file)); } private File findApplication() { File targetDir = new File("target"); for (File file : targetDir.listFiles()) { - if (file.getName().startsWith("spring-boot-launch-script-tests") - && file.getName().endsWith(".jar") + if (file.getName().startsWith("spring-boot-launch-script-tests") && file.getName().endsWith(".jar") && !file.getName().endsWith("-sources.jar")) { return file; } @@ -441,15 +414,12 @@ public class SysVinitLaunchScriptIT { if (matcher.matches()) { return matcher.group(1); } - throw new IllegalArgumentException( - "Failed to extract " + label + " from output: " + output); + throw new IllegalArgumentException("Failed to extract " + label + " from output: " + output); } - private static final class CopyToContainerCmdExec - extends AbstrSyncDockerCmdExec<CopyToContainerCmd, Void> { + private static final class CopyToContainerCmdExec extends AbstrSyncDockerCmdExec<CopyToContainerCmd, Void> { - private CopyToContainerCmdExec(WebTarget baseResource, - DockerClientConfig dockerClientConfig) { + private CopyToContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @@ -457,12 +427,10 @@ public class SysVinitLaunchScriptIT { protected Void execute(CopyToContainerCmd command) { try (InputStream streamToUpload = new FileInputStream( CompressArchiveUtil.archiveTARFiles(command.getFile().getParentFile(), - Arrays.asList(command.getFile()), - command.getFile().getName()))) { - WebTarget webResource = getBaseResource().path("/containers/{id}/archive") - .resolveTemplate("id", command.getContainer()); - webResource.queryParam("path", ".") - .queryParam("noOverwriteDirNonDir", false).request() + Arrays.asList(command.getFile()), command.getFile().getName()))) { + WebTarget webResource = getBaseResource().path("/containers/{id}/archive").resolveTemplate("id", + command.getContainer()); + webResource.queryParam("path", ".").queryParam("noOverwriteDirNonDir", false).request() .put(Entity.entity(streamToUpload, "application/x-tar")).close(); return null; } @@ -499,8 +467,7 @@ public class SysVinitLaunchScriptIT { } - private static final class SpringBootDockerCmdExecFactory - extends JerseyDockerCmdExecFactory { + private static final class SpringBootDockerCmdExecFactory extends JerseyDockerCmdExecFactory { private CopyToContainerCmdExec createCopyToContainerCmdExec() { return new CopyToContainerCmdExec(getBaseResource(), getDockerClientConfig()); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/com/example/ResourceHandlingApplication.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/com/example/ResourceHandlingApplication.java index 1686da87440..1356b602888 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/com/example/ResourceHandlingApplication.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/com/example/ResourceHandlingApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,31 +39,28 @@ import org.springframework.context.annotation.Bean; public class ResourceHandlingApplication { public static void main(String[] args) { - new SpringApplicationBuilder(ResourceHandlingApplication.class) - .properties("server.port:0") + new SpringApplicationBuilder(ResourceHandlingApplication.class).properties("server.port:0") .listeners(new WebServerPortFileWriter(args[0])).run(args); } @Bean public ServletRegistrationBean<?> resourceServletRegistration() { - ServletRegistrationBean<?> registration = new ServletRegistrationBean<HttpServlet>( - new HttpServlet() { + ServletRegistrationBean<?> registration = new ServletRegistrationBean<HttpServlet>(new HttpServlet() { - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - URL resource = getServletContext() - .getResource(req.getQueryString()); - if (resource == null) { - resp.sendError(404); - } - else { - resp.getWriter().println(resource); - resp.getWriter().flush(); - } - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + URL resource = getServletContext().getResource(req.getQueryString()); + if (resource == null) { + resp.sendError(404); + } + else { + resp.getWriter().println(resource); + resp.getWriter().flush(); + } + } - }); + }); registration.addUrlMappings("/servletContext"); return registration; } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java index d5e2b59d9df..9c46a637c12 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,7 @@ abstract class AbstractApplicationLauncher extends ExternalResource { private int httpPort; - protected AbstractApplicationLauncher(ApplicationBuilder applicationBuilder, - BuildOutput buildOutput) { + protected AbstractApplicationLauncher(ApplicationBuilder applicationBuilder, BuildOutput buildOutput) { this.applicationBuilder = applicationBuilder; this.buildOutput = buildOutput; } @@ -81,8 +80,7 @@ abstract class AbstractApplicationLauncher extends ExternalResource { List<String> arguments = new ArrayList<>(); arguments.add(System.getProperty("java.home") + "/bin/java"); arguments.addAll(getArguments(archive, serverPortFile)); - ProcessBuilder processBuilder = new ProcessBuilder( - StringUtils.toStringArray(arguments)); + ProcessBuilder processBuilder = new ProcessBuilder(StringUtils.toStringArray(arguments)); if (workingDirectory != null) { processBuilder.directory(workingDirectory); } @@ -97,16 +95,14 @@ abstract class AbstractApplicationLauncher extends ExternalResource { long end = System.currentTimeMillis() + 30000; while (serverPortFile.length() == 0) { if (System.currentTimeMillis() > end) { - throw new IllegalStateException( - "server.port file was not written within 30 seconds"); + throw new IllegalStateException("server.port file was not written within 30 seconds"); } if (!process.isAlive()) { throw new IllegalStateException("Application failed to launch"); } Thread.sleep(100); } - return Integer - .parseInt(FileCopyUtils.copyToString(new FileReader(serverPortFile))); + return Integer.parseInt(FileCopyUtils.copyToString(new FileReader(serverPortFile))); } private static class ConsoleCopy extends Thread { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java index 5f63a1e01a2..1ad46088791 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,16 +69,13 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { private static List<Object> createParameters(String packaging, String container, List<Class<? extends AbstractApplicationLauncher>> applicationLaunchers) { List<Object> parameters = new ArrayList<>(); - ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, - packaging, container); + ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, packaging, container); for (Class<? extends AbstractApplicationLauncher> launcherClass : applicationLaunchers) { try { AbstractApplicationLauncher launcher = launcherClass - .getDeclaredConstructor(ApplicationBuilder.class, - BuildOutput.class) + .getDeclaredConstructor(ApplicationBuilder.class, BuildOutput.class) .newInstance(applicationBuilder, buildOutput); - String name = StringUtils.capitalize(container) + ": " - + launcher.getDescription(packaging); + String name = StringUtils.capitalize(container) + ": " + launcher.getDescription(packaging); parameters.add(new Object[] { name, launcher }); } catch (Exception ex) { @@ -88,8 +85,7 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { return parameters; } - protected AbstractEmbeddedServletContainerIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + protected AbstractEmbeddedServletContainerIntegrationTests(String name, AbstractApplicationLauncher launcher) { this.launcher = launcher; this.rest.setErrorHandler(new ResponseErrorHandler() { @@ -108,14 +104,12 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { @Override public URI expand(String uriTemplate, Object... uriVariables) { - return URI.create( - "http://localhost:" + launcher.getHttpPort() + uriTemplate); + return URI.create("http://localhost:" + launcher.getHttpPort() + uriTemplate); } @Override public URI expand(String uriTemplate, Map<String, ?> uriVariables) { - return URI.create( - "http://localhost:" + launcher.getHttpPort() + uriTemplate); + return URI.create("http://localhost:" + launcher.getHttpPort() + uriTemplate); } }); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java index 788df303580..38a3b4ff0a1 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,7 @@ class ApplicationBuilder { return doBuildApplication(containerFolder); } - private File doBuildApplication(File containerFolder) - throws IOException, MavenInvocationException { + private File doBuildApplication(File containerFolder) throws IOException, MavenInvocationException { File resourcesJar = createResourcesJar(); File appFolder = new File(containerFolder, "app"); appFolder.mkdirs(); @@ -85,12 +84,10 @@ class ApplicationBuilder { if (resourcesJar.exists()) { return resourcesJar; } - try (JarOutputStream resourcesJarStream = new JarOutputStream( - new FileOutputStream(resourcesJar))) { + try (JarOutputStream resourcesJarStream = new JarOutputStream(new FileOutputStream(resourcesJar))) { resourcesJarStream.putNextEntry(new ZipEntry("META-INF/resources/")); resourcesJarStream.closeEntry(); - resourcesJarStream.putNextEntry( - new ZipEntry("META-INF/resources/nested-meta-inf-resource.txt")); + resourcesJarStream.putNextEntry(new ZipEntry("META-INF/resources/nested-meta-inf-resource.txt")); resourcesJarStream.write("nested".getBytes()); resourcesJarStream.closeEntry(); return resourcesJar; @@ -104,10 +101,8 @@ class ApplicationBuilder { context.put("bootVersion", Versions.getBootVersion()); context.put("resourcesJarPath", resourcesJar.getAbsolutePath()); try (FileWriter out = new FileWriter(new File(appFolder, "pom.xml")); - FileReader templateReader = new FileReader( - "src/test/resources/pom-template.xml")) { - Mustache.compiler().escapeHTML(false).compile(templateReader).execute(context, - out); + FileReader templateReader = new FileReader("src/test/resources/pom-template.xml")) { + Mustache.compiler().escapeHTML(false).compile(templateReader).execute(context, out); } } @@ -120,10 +115,8 @@ class ApplicationBuilder { context.put("repository", repository); File settingsXml = new File(appFolder, "settings.xml"); try (FileWriter out = new FileWriter(settingsXml); - FileReader templateReader = new FileReader( - "src/test/resources/settings-template.xml")) { - Mustache.compiler().escapeHTML(false).compile(templateReader).execute(context, - out); + FileReader templateReader = new FileReader("src/test/resources/settings-template.xml")) { + Mustache.compiler().escapeHTML(false).compile(templateReader).execute(context, out); } return settingsXml; } @@ -131,19 +124,16 @@ class ApplicationBuilder { private void copyApplicationSource(File appFolder) throws IOException { File examplePackage = new File(appFolder, "src/main/java/com/example"); examplePackage.mkdirs(); - FileCopyUtils.copy( - new File("src/test/java/com/example/ResourceHandlingApplication.java"), + FileCopyUtils.copy(new File("src/test/java/com/example/ResourceHandlingApplication.java"), new File(examplePackage, "ResourceHandlingApplication.java")); if ("war".equals(this.packaging)) { File srcMainWebapp = new File(appFolder, "src/main/webapp"); srcMainWebapp.mkdirs(); - FileCopyUtils.copy("webapp resource", - new FileWriter(new File(srcMainWebapp, "webapp-resource.txt"))); + FileCopyUtils.copy("webapp resource", new FileWriter(new File(srcMainWebapp, "webapp-resource.txt"))); } } - private void packageApplication(File appFolder, File settingsXml) - throws MavenInvocationException { + private void packageApplication(File appFolder, File settingsXml) throws MavenInvocationException { InvocationRequest invocation = new DefaultInvocationRequest(); invocation.setBaseDirectory(appFolder); invocation.setGoals(Collections.singletonList("package")); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java index d1711336b4d..a86fd2afbc7 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { private final File exploded; - BootRunApplicationLauncher(ApplicationBuilder applicationBuilder, - BuildOutput buildOutput) { + BootRunApplicationLauncher(ApplicationBuilder applicationBuilder, BuildOutput buildOutput) { super(applicationBuilder, buildOutput); this.exploded = new File(buildOutput.getRootLocation(), "run"); } @@ -64,11 +63,8 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { for (File dependency : dependencies.listFiles()) { classpath.add(dependency.getAbsolutePath()); } - return Arrays.asList("-cp", - StringUtils.collectionToDelimitedString(classpath, - File.pathSeparator), - "com.example.ResourceHandlingApplication", - serverPortFile.getAbsolutePath()); + return Arrays.asList("-cp", StringUtils.collectionToDelimitedString(classpath, File.pathSeparator), + "com.example.ResourceHandlingApplication", serverPortFile.getAbsolutePath()); } catch (IOException ex) { throw new RuntimeException(ex); @@ -111,13 +107,11 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { } private String getClassesPath(File archive) { - return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" - : "WEB-INF/classes"); + return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" : "WEB-INF/classes"); } private List<String> getLibPaths(File archive) { - return (archive.getName().endsWith(".jar") - ? Collections.singletonList("BOOT-INF/lib") + return (archive.getName().endsWith(".jar") ? Collections.singletonList("BOOT-INF/lib") : Arrays.asList("WEB-INF/lib", "WEB-INF/lib-provided")); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java index a5732b04343..6b61c999862 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,26 +40,24 @@ public class EmbeddedServletContainerJarDevelopmentIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", Arrays - .asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); + return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", + Arrays.asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); } - public EmbeddedServletContainerJarDevelopmentIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerJarDevelopmentIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void metaInfResourceFromDependencyIsAvailableViaHttp() { - ResponseEntity<String> entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void metaInfResourceFromDependencyIsAvailableViaServletContext() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java index f11c20cea89..06900c056e6 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,48 +41,43 @@ public class EmbeddedServletContainerJarPackagingIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", - Arrays.asList(PackagedApplicationLauncher.class, - ExplodedApplicationLauncher.class)); + Arrays.asList(PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class)); } - public EmbeddedServletContainerJarPackagingIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerJarPackagingIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void nestedMetaInfResourceIsAvailableViaHttp() { - ResponseEntity<String> entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedMetaInfResourceIsAvailableViaServletContext() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedJarIsNotAvailableViaHttp() { - ResponseEntity<String> entity = this.rest - .getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void applicationClassesAreNotAvailableViaHttp() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", - String.class); + ResponseEntity<String> entity = this.rest + .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void launcherIsNotAvailableViaHttp() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/org/springframework/boot/loader/Launcher.class", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/org/springframework/boot/loader/Launcher.class", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java index 4d168798a96..c0731c56381 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,33 +40,30 @@ public class EmbeddedServletContainerWarDevelopmentIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", Arrays - .asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); + return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", + Arrays.asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); } - public EmbeddedServletContainerWarDevelopmentIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerWarDevelopmentIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void metaInfResourceFromDependencyIsAvailableViaHttp() { - ResponseEntity<String> entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void metaInfResourceFromDependencyIsAvailableViaServletContext() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void webappResourcesAreAvailableViaHttp() { - ResponseEntity<String> entity = this.rest.getForEntity("/webapp-resource.txt", - String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java index 5947335c72b..cd938996511 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,58 +41,51 @@ public class EmbeddedServletContainerWarPackagingIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", - Arrays.asList(PackagedApplicationLauncher.class, - ExplodedApplicationLauncher.class)); + Arrays.asList(PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class)); } - public EmbeddedServletContainerWarPackagingIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerWarPackagingIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void nestedMetaInfResourceIsAvailableViaHttp() { - ResponseEntity<String> entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedMetaInfResourceIsAvailableViaServletContext() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedJarIsNotAvailableViaHttp() { - ResponseEntity<String> entity = this.rest - .getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void applicationClassesAreNotAvailableViaHttp() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/WEB-INF/classes/com/example/ResourceHandlingApplication.class", - String.class); + ResponseEntity<String> entity = this.rest + .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void webappResourcesAreAvailableViaHttp() { - ResponseEntity<String> entity = this.rest.getForEntity("/webapp-resource.txt", - String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void loaderClassesAreNotAvailableViaHttp() { - ResponseEntity<String> entity = this.rest.getForEntity( - "/org/springframework/boot/loader/Launcher.class", String.class); + ResponseEntity<String> entity = this.rest.getForEntity("/org/springframework/boot/loader/Launcher.class", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - entity = this.rest.getForEntity( - "/org/springframework/../springframework/boot/loader/Launcher.class", + entity = this.rest.getForEntity("/org/springframework/../springframework/boot/loader/Launcher.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java index 58d8d63b8ae..2370caa7d11 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,7 @@ class ExplodedApplicationLauncher extends AbstractApplicationLauncher { private final Supplier<File> exploded; - ExplodedApplicationLauncher(ApplicationBuilder applicationBuilder, - BuildOutput buildOutput) { + ExplodedApplicationLauncher(ApplicationBuilder applicationBuilder, BuildOutput buildOutput) { super(applicationBuilder, buildOutput); this.exploded = () -> new File(buildOutput.getRootLocation(), "exploded"); } @@ -58,8 +57,7 @@ class ExplodedApplicationLauncher extends AbstractApplicationLauncher { @Override protected List<String> getArguments(File archive, File serverPortFile) { - String mainClass = (archive.getName().endsWith(".war") - ? "org.springframework.boot.loader.WarLauncher" + String mainClass = (archive.getName().endsWith(".war") ? "org.springframework.boot.loader.WarLauncher" : "org.springframework.boot.loader.JarLauncher"); try { explodeArchive(archive); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java index cf96b55db34..dd21bba8dec 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { private final File exploded; - IdeApplicationLauncher(ApplicationBuilder applicationBuilder, - BuildOutput buildOutput) { + IdeApplicationLauncher(ApplicationBuilder applicationBuilder, BuildOutput buildOutput) { super(applicationBuilder, buildOutput); this.exploded = new File(buildOutput.getRootLocation(), "the+ide application"); } @@ -76,11 +75,8 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { classpath.add(dependency.getAbsolutePath()); } classpath.add(resourcesProject.getAbsolutePath()); - return Arrays.asList("-cp", - StringUtils.collectionToDelimitedString(classpath, - File.pathSeparator), - "com.example.ResourceHandlingApplication", - serverPortFile.getAbsolutePath()); + return Arrays.asList("-cp", StringUtils.collectionToDelimitedString(classpath, File.pathSeparator), + "com.example.ResourceHandlingApplication", serverPortFile.getAbsolutePath()); } catch (IOException ex) { throw new RuntimeException(ex); @@ -111,8 +107,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { } private File explodedResourcesProject(File dependencies) throws IOException { - File resourcesProject = new File(this.exploded, - "resources-project/built/classes"); + File resourcesProject = new File(this.exploded, "resources-project/built/classes"); File resourcesJar = new File(dependencies, "resources-1.0.jar"); explodeArchive(resourcesJar, resourcesProject); resourcesJar.delete(); @@ -132,13 +127,11 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { } private String getClassesPath(File archive) { - return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" - : "WEB-INF/classes"); + return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" : "WEB-INF/classes"); } private List<String> getLibPaths(File archive) { - return (archive.getName().endsWith(".jar") - ? Collections.singletonList("BOOT-INF/lib") + return (archive.getName().endsWith(".jar") ? Collections.singletonList("BOOT-INF/lib") : Arrays.asList("WEB-INF/lib", "WEB-INF/lib-provided")); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/PackagedApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/PackagedApplicationLauncher.java index c590597cd8b..6bd33bb9f9a 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/PackagedApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/PackagedApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.springframework.boot.testsupport.BuildOutput; */ class PackagedApplicationLauncher extends AbstractApplicationLauncher { - PackagedApplicationLauncher(ApplicationBuilder applicationBuilder, - BuildOutput buildOutput) { + PackagedApplicationLauncher(ApplicationBuilder applicationBuilder, BuildOutput buildOutput) { super(applicationBuilder, buildOutput); } @@ -47,8 +46,7 @@ class PackagedApplicationLauncher extends AbstractApplicationLauncher { @Override protected List<String> getArguments(File archive, File serverPortFile) { - return Arrays.asList("-jar", archive.getAbsolutePath(), - serverPortFile.getAbsolutePath()); + return Arrays.asList("-jar", archive.getAbsolutePath(), serverPortFile.getAbsolutePath()); } } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/Versions.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/Versions.java index 18e29b2077f..dfb9f217f52 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/Versions.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/Versions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,11 +40,9 @@ final class Versions { public static String getBootVersion() { String baseDir = StringUtils.cleanPath(new File(".").getAbsolutePath()); - String mainBaseDir = evaluateExpression("pom.xml", - PROPERTIES + "/*[local-name()='main.basedir']/text()"); + String mainBaseDir = evaluateExpression("pom.xml", PROPERTIES + "/*[local-name()='main.basedir']/text()"); mainBaseDir = mainBaseDir.replace("${basedir}", baseDir); - return evaluateExpression(mainBaseDir + "/pom.xml", - PROPERTIES + "/*[local-name()='revision']/text()"); + return evaluateExpression(mainBaseDir + "/pom.xml", PROPERTIES + "/*[local-name()='revision']/text()"); } private static String evaluateExpression(String file, String expression) {